title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Event bubbling vs event capturing in JavaScript?
Event Bubbling − Whenever an event happens on an element, the event handlers will first run on it and then on its parent and finally all the way up to its other ancestors. Event Capturing − It is the reverse of the event bubbling and here the event starts from the parent element and then to its child element. Following is the code for event bubbling vs event capturing in JavaScript − Live Demo <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .result { font-size: 18px; font-weight: 500; color: blueviolet; } .outer { display: inline-block; width: 400px; height: 200px; font-size: 20px; background-color: chartreuse; } .inner { width: 200px; height: 100px; font-size: 20px; background-color: blueviolet; text-align: center; margin: 20px; } .tags { display: inline-block; width: 400px; font-weight: bold; font-size: 18px; } </style> </head> <body> <h1>Event bubbling vs event capturing</h1> <div class="outer"> OUTER <div class="inner">INNER</div> </div> <div class="outer"> OUTER <div class="inner">INNER</div> </div> <br /> <div class="tags">Bubbling</div> <div class="tags">Capturing</div> <div class="result"></div> <script> let outerDiv = document.querySelectorAll(".outer"); let innerDiv = document.querySelectorAll(".inner"); let resEle = document.querySelector(".result"); outerDiv[0].addEventListener("click", () => { resEle.innerHTML += "Outer div has been clicked" + "<br>"; }); innerDiv[0].addEventListener("click", () => { resEle.innerHTML = ""; resEle.innerHTML += "Inner div has been clicked" + "<br>"; }); outerDiv[1].addEventListener("click",() => { resEle.innerHTML = ""; resEle.innerHTML += "Outer div has been clicked" + "<br>"; },true); innerDiv[1].addEventListener("click",() => { resEle.innerHTML += "Inner div has been clicked" + "<br>"; }, true); </script> </body> </html> On clicking the inner div having the event bubbling − On clicking the inner div having the event capturing −
[ { "code": null, "e": 1234, "s": 1062, "text": "Event Bubbling − Whenever an event happens on an element, the event handlers will first run on it and then on its parent and finally all the way up to its other ancestors." }, { "code": null, "e": 1373, "s": 1234, "text": "Event Capturing − It is the reverse of the event bubbling and here the event starts from the parent element and then to its child element." }, { "code": null, "e": 1449, "s": 1373, "text": "Following is the code for event bubbling vs event capturing in JavaScript −" }, { "code": null, "e": 1460, "s": 1449, "text": " Live Demo" }, { "code": null, "e": 3268, "s": 1460, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\" />\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n<title>Document</title>\n<style>\n body {\n font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif;\n }\n .result {\n font-size: 18px;\n font-weight: 500;\n color: blueviolet;\n }\n .outer {\n display: inline-block;\n width: 400px;\n height: 200px;\n font-size: 20px;\n background-color: chartreuse;\n }\n .inner {\n width: 200px;\n height: 100px;\n font-size: 20px;\n background-color: blueviolet;\n text-align: center;\n margin: 20px;\n }\n .tags {\n display: inline-block;\n width: 400px;\n font-weight: bold;\n font-size: 18px;\n }\n</style>\n</head>\n<body>\n<h1>Event bubbling vs event capturing</h1>\n<div class=\"outer\">\nOUTER\n<div class=\"inner\">INNER</div>\n</div>\n<div class=\"outer\">\nOUTER\n<div class=\"inner\">INNER</div>\n</div>\n<br />\n<div class=\"tags\">Bubbling</div>\n<div class=\"tags\">Capturing</div>\n<div class=\"result\"></div>\n<script>\n let outerDiv = document.querySelectorAll(\".outer\");\n let innerDiv = document.querySelectorAll(\".inner\");\n let resEle = document.querySelector(\".result\");\n outerDiv[0].addEventListener(\"click\", () => {\n resEle.innerHTML += \"Outer div has been clicked\" + \"<br>\";\n });\n innerDiv[0].addEventListener(\"click\", () => {\n resEle.innerHTML = \"\";\n resEle.innerHTML += \"Inner div has been clicked\" + \"<br>\";\n });\n outerDiv[1].addEventListener(\"click\",() => {\n resEle.innerHTML = \"\";\n resEle.innerHTML += \"Outer div has been clicked\" + \"<br>\";\n },true);\n innerDiv[1].addEventListener(\"click\",() => {\n resEle.innerHTML += \"Inner div has been clicked\" + \"<br>\";\n }, true);\n</script>\n</body>\n</html>" }, { "code": null, "e": 3322, "s": 3268, "text": "On clicking the inner div having the event bubbling −" }, { "code": null, "e": 3377, "s": 3322, "text": "On clicking the inner div having the event capturing −" } ]
How To Manipulate Data With DataFrames.jl | by Emmett Boudreau | Towards Data Science
While Julia might be a programming language that has exploded in popularity recently, a great test of a data science ecosystem in a particular language is usually seeing how well data can be handled and manipulated. One contribution that certainly makes approaching such a problem objectively easier is DataFrames.jl. notebook DataFrames.jl is JuliaData’s take on a functional, easy-to-use, and SQL-like data frame management inside of the Julia programming language. Although DataFrames.jl is a rather young package, it frequently gets the job done far better than many of its competitors. That being said, it certainly might take some getting used to. If you also enjoy Python, I wrote another article that will get you familiar with a package called Pandas that is as essential to Python DS as DataFrames.jl is to Julia DS: towardsdatascience.com As with Pandas, the most important thing that you might want to familiarize yourself with from DataFrames.jl is the DataFrame type. The DataFrame type can be used with several different methods from Julia’s base, as well as some IJulia methods and unique methods for DataFrames. That being said, let’s get started using it! The first step is of course to import DataFrames.jl: using DataFrames Whenever the DataFrames package is loaded, the DataFrame type will be exported. We can view the documentation for this type by using the ?() method: Here we see another cool thing about Julia in the works, as well, abstraction. If you would like to read more about Julia’s handling of abstraction and the inheritance of methods, I wrote an entire article you can check out here!: Back on topic, we can now construct a DataFrame with any of the constructors listed above, for example with a tuple of pairs: tuples = (:H => [5, 10], :J => [10, 15])df = DataFrame(tuples) Alternatively, we could do the same with a dictionary: df = DataFrame(dict) You can also use the DataFrames module with a sink argument to read DataFrames in from various different data sources, such as comma separated values (CSV.) using DataFrames; df = CSV.read("car data.csv", DataFrame) If you’d like to read more about sink arguments, I also have an article written all about those, as well that might interest you! : towardsdatascience.com Our new dataframe can use many base methods, most useful of which is probably push!(), which can be used for concatenation. This will concatenate the observations provided separately, and can be used for logging initial observations. df = DataFrame(:X => [5,10,15,20], :Y => [5,10,15,20])push!(df, [10, 15]) We can access columns on our new DataFrame by either using the child of the struct, or calling the data’s corresponding key. # Child of struct:df.X# Key:df[!, :X] We can also get all of the available keys by using the names() function for strings, and propertynames() if we want the same data format used to hold the keys: names(df)propertynames(df) Finally, we can create a new column by simply assigning a new column equal to something: df[!, :Z] = [1, 2, 3, 4, 5] Now that we are familiar with the DataFrame type, we might want to look at all of the cool functions that we now have access to use on our type. In order to show a DataFrame, you can use the show() method. You might notice that this might not print a full DataFrame, for that you can use the allcols key-word argument: show(df)show(df, allcols = true) We can also do the equivalent of df.head() and df.tail() from Pandas. The equivalent methods are first() and last() respectively: first(df, 2)last(df, 3) Another thing to note is that DataFrames.jl has array-like indexing. This means that often DataFrame calls can be treated like matrix calls, for example: df[2:4, :] We can also use Not() to negate any data that we don’t want to include: df[Not(2:4), :] We can think of the [:]’s above as *’s in computer language. The colon signifies a selection of all. The first dimension is rows and the second dimension is columns. Taking a look at our data, calling our df at [2, 2] should yield 10. df[2, 2]10 Often when working with Data Science and data manipulating operations, simple matrix math might not be the only tool required to achieve a good result. DataFrames.jl has SQL-style inner and outer joins, and can typically accomplish most operations with great results. df2 = DataFrame(:A => [5, 10, 15, 20, 25], :Y => [5, 10, 15, 20, 15])innerjoin(df, df2, on = :Y) Of course, you can always identify the usable methods on the DataFrame documentation and utilize the ?() method. There are also left, right, semi, and anti-joins in DataFrames.jl. These are a great way to creatively and functionally manipulate our data. DataFrames also have another attribute called shape. Shape is a set of two numbers that represent the dimensions of the DataFrame. We can see a DataFrame’s by showing it just as we usually would, with the show() method: show(df) The shape of this DataFrame is 5 x 3, indicated by the 5 rows and three columns. We can manipulate DataFrames using cross-tabulations, pivot-tables, and stacking in order to dramatically alter their shape effectively. stack(df)unstack(df) Some of the most important skills for working with large datasets as a Data Scientist is data cleaning skills. These are a little less polished in Julia compared to many of its counterparts such as Pandas, but Julia has some great base methods and data types that will help us get through it! Firstly, we can use the sort() and sort!() methods respectively in order to sort our data for algorithm optimization and analysis. This is especially valuable in linear analysis situations. In Julia, “ missing” is the data-type that represents a value of data that hasn’t been found and “ nothing” is the data-type used to represent constructors that have not been found. The best way to remove missing values in Base Julia is to use the skipmissing() method from Julia’s base. This will return a data-efficient iterator that will remove missing data effectively. In Julia, we would then wrap this in the collect method to collect the return of the iterator: collect(skipmissing(x)) Using DataFrames, we can drop missings with the dropmissing() method. This is a simple and effective way to eliminate missing values from a DataFrame very quickly and effectively over many different features and observations. It also has dispatch for DataFrame columns, so we could work with columns individually if desired: df = DataFrame(:A => [5, missing, 6], :B => [5, 10, 2])dropmissing(df)dropmissing(df, :A) To conclude, while Julia might not have the most mature package ecosystem underneath its belt, DataFrames.jl is certainly a fantastic package that is well worth using in the Julia language. DataFrames.jl is a valuable asset in a multitude of ways such as allowing SQL-like joins, data visualization, sorting, and most certainly allowing the effective removal of missing data from entire DataFrames. Beyond this, learning how to work with categorical and continuous arrays using methods like push!(), append!(), sort!(), and filter!() and just about anything should easily be handled with DataFrames.jl and Julia together!
[ { "code": null, "e": 490, "s": 172, "text": "While Julia might be a programming language that has exploded in popularity recently, a great test of a data science ecosystem in a particular language is usually seeing how well data can be handled and manipulated. One contribution that certainly makes approaching such a problem objectively easier is DataFrames.jl." }, { "code": null, "e": 499, "s": 490, "text": "notebook" }, { "code": null, "e": 999, "s": 499, "text": "DataFrames.jl is JuliaData’s take on a functional, easy-to-use, and SQL-like data frame management inside of the Julia programming language. Although DataFrames.jl is a rather young package, it frequently gets the job done far better than many of its competitors. That being said, it certainly might take some getting used to. If you also enjoy Python, I wrote another article that will get you familiar with a package called Pandas that is as essential to Python DS as DataFrames.jl is to Julia DS:" }, { "code": null, "e": 1022, "s": 999, "text": "towardsdatascience.com" }, { "code": null, "e": 1399, "s": 1022, "text": "As with Pandas, the most important thing that you might want to familiarize yourself with from DataFrames.jl is the DataFrame type. The DataFrame type can be used with several different methods from Julia’s base, as well as some IJulia methods and unique methods for DataFrames. That being said, let’s get started using it! The first step is of course to import DataFrames.jl:" }, { "code": null, "e": 1416, "s": 1399, "text": "using DataFrames" }, { "code": null, "e": 1565, "s": 1416, "text": "Whenever the DataFrames package is loaded, the DataFrame type will be exported. We can view the documentation for this type by using the ?() method:" }, { "code": null, "e": 1796, "s": 1565, "text": "Here we see another cool thing about Julia in the works, as well, abstraction. If you would like to read more about Julia’s handling of abstraction and the inheritance of methods, I wrote an entire article you can check out here!:" }, { "code": null, "e": 1922, "s": 1796, "text": "Back on topic, we can now construct a DataFrame with any of the constructors listed above, for example with a tuple of pairs:" }, { "code": null, "e": 1985, "s": 1922, "text": "tuples = (:H => [5, 10], :J => [10, 15])df = DataFrame(tuples)" }, { "code": null, "e": 2040, "s": 1985, "text": "Alternatively, we could do the same with a dictionary:" }, { "code": null, "e": 2061, "s": 2040, "text": "df = DataFrame(dict)" }, { "code": null, "e": 2218, "s": 2061, "text": "You can also use the DataFrames module with a sink argument to read DataFrames in from various different data sources, such as comma separated values (CSV.)" }, { "code": null, "e": 2277, "s": 2218, "text": "using DataFrames; df = CSV.read(\"car data.csv\", DataFrame)" }, { "code": null, "e": 2409, "s": 2277, "text": "If you’d like to read more about sink arguments, I also have an article written all about those, as well that might interest you! :" }, { "code": null, "e": 2432, "s": 2409, "text": "towardsdatascience.com" }, { "code": null, "e": 2666, "s": 2432, "text": "Our new dataframe can use many base methods, most useful of which is probably push!(), which can be used for concatenation. This will concatenate the observations provided separately, and can be used for logging initial observations." }, { "code": null, "e": 2740, "s": 2666, "text": "df = DataFrame(:X => [5,10,15,20], :Y => [5,10,15,20])push!(df, [10, 15])" }, { "code": null, "e": 2865, "s": 2740, "text": "We can access columns on our new DataFrame by either using the child of the struct, or calling the data’s corresponding key." }, { "code": null, "e": 2903, "s": 2865, "text": "# Child of struct:df.X# Key:df[!, :X]" }, { "code": null, "e": 3063, "s": 2903, "text": "We can also get all of the available keys by using the names() function for strings, and propertynames() if we want the same data format used to hold the keys:" }, { "code": null, "e": 3091, "s": 3063, "text": "names(df)propertynames(df) " }, { "code": null, "e": 3180, "s": 3091, "text": "Finally, we can create a new column by simply assigning a new column equal to something:" }, { "code": null, "e": 3208, "s": 3180, "text": "df[!, :Z] = [1, 2, 3, 4, 5]" }, { "code": null, "e": 3527, "s": 3208, "text": "Now that we are familiar with the DataFrame type, we might want to look at all of the cool functions that we now have access to use on our type. In order to show a DataFrame, you can use the show() method. You might notice that this might not print a full DataFrame, for that you can use the allcols key-word argument:" }, { "code": null, "e": 3560, "s": 3527, "text": "show(df)show(df, allcols = true)" }, { "code": null, "e": 3690, "s": 3560, "text": "We can also do the equivalent of df.head() and df.tail() from Pandas. The equivalent methods are first() and last() respectively:" }, { "code": null, "e": 3714, "s": 3690, "text": "first(df, 2)last(df, 3)" }, { "code": null, "e": 3868, "s": 3714, "text": "Another thing to note is that DataFrames.jl has array-like indexing. This means that often DataFrame calls can be treated like matrix calls, for example:" }, { "code": null, "e": 3879, "s": 3868, "text": "df[2:4, :]" }, { "code": null, "e": 3951, "s": 3879, "text": "We can also use Not() to negate any data that we don’t want to include:" }, { "code": null, "e": 3967, "s": 3951, "text": "df[Not(2:4), :]" }, { "code": null, "e": 4202, "s": 3967, "text": "We can think of the [:]’s above as *’s in computer language. The colon signifies a selection of all. The first dimension is rows and the second dimension is columns. Taking a look at our data, calling our df at [2, 2] should yield 10." }, { "code": null, "e": 4213, "s": 4202, "text": "df[2, 2]10" }, { "code": null, "e": 4481, "s": 4213, "text": "Often when working with Data Science and data manipulating operations, simple matrix math might not be the only tool required to achieve a good result. DataFrames.jl has SQL-style inner and outer joins, and can typically accomplish most operations with great results." }, { "code": null, "e": 4578, "s": 4481, "text": "df2 = DataFrame(:A => [5, 10, 15, 20, 25], :Y => [5, 10, 15, 20, 15])innerjoin(df, df2, on = :Y)" }, { "code": null, "e": 4832, "s": 4578, "text": "Of course, you can always identify the usable methods on the DataFrame documentation and utilize the ?() method. There are also left, right, semi, and anti-joins in DataFrames.jl. These are a great way to creatively and functionally manipulate our data." }, { "code": null, "e": 5052, "s": 4832, "text": "DataFrames also have another attribute called shape. Shape is a set of two numbers that represent the dimensions of the DataFrame. We can see a DataFrame’s by showing it just as we usually would, with the show() method:" }, { "code": null, "e": 5061, "s": 5052, "text": "show(df)" }, { "code": null, "e": 5279, "s": 5061, "text": "The shape of this DataFrame is 5 x 3, indicated by the 5 rows and three columns. We can manipulate DataFrames using cross-tabulations, pivot-tables, and stacking in order to dramatically alter their shape effectively." }, { "code": null, "e": 5300, "s": 5279, "text": "stack(df)unstack(df)" }, { "code": null, "e": 5593, "s": 5300, "text": "Some of the most important skills for working with large datasets as a Data Scientist is data cleaning skills. These are a little less polished in Julia compared to many of its counterparts such as Pandas, but Julia has some great base methods and data types that will help us get through it!" }, { "code": null, "e": 5965, "s": 5593, "text": "Firstly, we can use the sort() and sort!() methods respectively in order to sort our data for algorithm optimization and analysis. This is especially valuable in linear analysis situations. In Julia, “ missing” is the data-type that represents a value of data that hasn’t been found and “ nothing” is the data-type used to represent constructors that have not been found." }, { "code": null, "e": 6252, "s": 5965, "text": "The best way to remove missing values in Base Julia is to use the skipmissing() method from Julia’s base. This will return a data-efficient iterator that will remove missing data effectively. In Julia, we would then wrap this in the collect method to collect the return of the iterator:" }, { "code": null, "e": 6276, "s": 6252, "text": "collect(skipmissing(x))" }, { "code": null, "e": 6601, "s": 6276, "text": "Using DataFrames, we can drop missings with the dropmissing() method. This is a simple and effective way to eliminate missing values from a DataFrame very quickly and effectively over many different features and observations. It also has dispatch for DataFrame columns, so we could work with columns individually if desired:" }, { "code": null, "e": 6691, "s": 6601, "text": "df = DataFrame(:A => [5, missing, 6], :B => [5, 10, 2])dropmissing(df)dropmissing(df, :A)" } ]
Pneumonia Diagnosis using Deep Learning | by Richard Han | Towards Data Science
Introduction In the world of healthcare, one of the major issues that medical professionals face is the correct diagnosis of conditions and diseases of patients. Not being able to correctly diagnose a condition is a problem for both the patient and the doctor. The doctor is not benefitting the patient in the appropriate way if the doctor misdiagnoses the patient. This could lead to malpractice lawsuits and overall hurt the doctor’s business. The patient suffers by not receiving the proper treatment and risking greater harm to health by the condition that goes undetected; further, the patient undergoes unnecessary treatment and takes unnecessary medications, costing the patient time and money. If we can correctly diagnose a patient’s condition, we have the potential to solve the above-mentioned problems. If we can produce deep learning models that can classify whether a patient has a condition or not, that can determine which particular condition the patient has, and that can determine the severity of the condition, then medical professionals will be able to use these models to better diagnose their patients. Accurate diagnosis can also be useful by allowing for timely treatment of a patient; being misdiagnosed can cause a delay in receiving the proper treatment. In this paper, we will perform deep learning to a dataset representing the chest x-rays of pediatric patients from Guangzhou Women and Children’s Medical Center, Guangzhou. I would like to apply a convolutional neural network (CNN) and try to classify a patient as either having pneumonia or not having pneumonia. This is a binary classification problem. I would also like to apply CNN’s to classify a patient as either having bacterial pneumonia, viral pneumonia, or no pneumonia. This is a 3-class classification problem. Here is a sample of what the x-rays look like: [The normal chest X-ray (left panel) depicts clear lungs without any areas of abnormal opacification in the image. Bacterial pneumonia (middle) typically exhibits a focal lobar consolidation, in this case in the right upper lobe (white arrows), whereas viral pneumonia (right) manifests with a more diffuse “interstitial” pattern in both lungs. (Kermany et al, 2018)] Apparently, bacterial pneumonia has areas of opaqueness that are more concentrated in one lobe whereas viral pneumonia has opaque areas more spread out on both lungs. The right lung is divided into three lobes, and the left lung is divided into two lobes. It’s certainly not obvious to me how to tell the difference. Hopefully, deep learning can help us tell the difference. Data Preparation The dataset can be found here: https://www.kaggle.com/paultimothymooney/chest-xray-pneumonia#IM-0007-0001.jpeg The data comes in two folders, one for the training set and one for the test set. The training set folder contains a folder of images for pneumonia cases and a folder of images for normal cases. The training set consists of 5216 images total. The test set folder contains a folder of images for pneumonia cases and a folder of images for normal cases. The test set consists of 624 images total, approximately 10.68% of the total set of images. Unlike the case in classical machine learning, we don’t have to worry about the various attributes of the dataset; in the case of convolutional neural networks, we just have a set of images. Convolutional Neural Networks There is, however, some preparation of the images that is necessary before applying an artificial neural network. The images need to be prepared using convolutional layers in a process called convolution. There are several stages in this process — convolution operation, ReLU operation, pooling, and flattening; the end result is a vector that we can feed into an artificial neural network. Here is an image of a general CNN architecture: During the convolution operation, various feature detectors are applied to the image, creating a stack of feature maps — this stack of feature maps is called a convolutional layer. ReLU is applied to each feature map to enhance non-linearity. During the pooling stage, also known as subsampling, we apply max-pooling (or some other type of pooling) to each feature map, creating smaller feature maps that preserve the relevant features of the image. The resulting stack of pooled featured maps forms the pooling layer. Once we get to the pooling layer, consisting of pooled feature maps, each pooled feature map is flattened into a vector and the resulting vectors are combined sequentially into one vector. The entries of this vector are fed into the input units of the artificial neural network. Thus, the entries of the flattened vector corresponding to one image are fed into the input units of the ANN. (This is in contrast to ANN’s used on a classical dataset where the attributes of a single instance are fed into the input units of the ANN). The artificial neural network is then trained on the training set and tested on the test set. Here is an image of a general ANN: The ANN begins where it says ‘Fully connected’ in the diagram for the CNN architecture. As you can see, a convolutional neural network is the combination of convolution and an ANN. Building a CNN with Python In order to build the CNN, we import Keras libraries and packages: #Importing the Keras libraries and packagesfrom keras.models import Sequentialfrom keras.layers import Convolution2Dfrom keras.layers import MaxPooling2Dfrom keras.layers import Flattenfrom keras.layers import Dense The Sequential package is used to initialise the CNN. The Convolution2D package is used to create the convolutional layers. The MaxPooling2D package is used to created the pooled feature maps. The Flatten package is used to flatten the stack of pooled feature maps into one vector that can be fed into the ANN. The Dense package is used to add layers to the ANN. Next, we initialize the CNN by creating an object of the Sequential class. This object we will call ‘classifier’: #Initialising the CNNclassifier = Sequential() We’re going to add one convolutional layer of 32 filter maps by applying 32 filters (feature detectors) of dimension 3 by 3 to the input image. We want our input images to have dimension 64 by 64 and treated as color images with 3 channels. We also apply ReLU to each feature map using the activation function ‘relu’: #Step 1 - Convolutionclassifier.add(Convolution2D(32,(3,3),input_shape=(64,64,3),activation = 'relu')) Now that we have our feature maps in the convolutional layer, we apply max-pooling to each feature map using a 2 by 2 grid. #Step 2 - Poolingclassifier.add(MaxPooling2D((2,2))) Now that we have a pooling layer consisting of pooled feature maps, we flatten each pooled feature map into a vector and combine all the resulting vectors sequentially into one giant vector. #Step 3 - Flatteningclassifier.add(Flatten()) Next, we’re going to add our artificial neural network. First, we add a hidden layer of 128 units and use the activation function ‘relu’. Second, we add the output layer consisting of one output unit and use the sigmoid function as the activation function; we use one output unit because our output is binary (either normal or pneumonia). #Step 4 - Full connectionclassifier.add(Dense(units=128,activation='relu'))classifier.add(Dense(units=1, activation='sigmoid')) Now, we need to compile the CNN. We’re going to use ‘adam’ as the optimizer in stochastic gradient descent, binary cross-entropy for the loss function, and accuracy as the performance metric. #Compiling the CNNclassifier.compile(optimizer = 'adam',loss='binary_crossentropy',metrics=['accuracy']) Our training set and test set combined has a total of 5840 images; so, we’re going to apply image augmentation to increase the size of our training set and test set while reducing overfitting. We then fit the CNN to our augmented training set and test it on our augmented test set: #Fitting the CNN to the imagesfrom keras.preprocessing.image import ImageDataGeneratortrain_datagen = ImageDataGenerator(rescale=1./255,shear_range=0.2,zoom_range=0.2,horizontal_flip=True)test_datagen = ImageDataGenerator(rescale=1./255)training_set = train_datagen.flow_from_directory('chest_xraybinary/train',target_size=(64, 64),batch_size=32,class_mode='binary')test_set = test_datagen.flow_from_directory('chest_xraybinary/test',target_size=(64,64),batch_size=32,class_mode='binary')classifier.fit_generator(training_set,epochs=25,validation_data=test_set) After 25 epochs, I got an accuracy of 95% on the training set and 89% on the test set. Evaluating, Improving, and Tuning the CNN Previously, we built a CNN with one convolutional layer and one hidden layer. This time, we’re going to add a second convolutional layer and see if it improves performance. We simply add the following code after step 2 — pooling: #Adding a second convolutional layerclassifier.add(Convolution2D(32,(3,3),activation = 'relu'))classifier.add(MaxPooling2D((2,2))) After 25 epochs, we get an accuracy of 96% on the training set and 91.5% on the test set. Next, in addition to having a second convolutional layer, we’re going to add a second hidden layer and see if it improves performance. To add a second hidden layer, we simply duplicate the code for adding one hidden layer: #Step 4 - Full connectionclassifier.add(Dense(units=128,activation='relu'))classifier.add(Dense(units=128,activation='relu'))classifier.add(Dense(units=1, activation='sigmoid')) After 25 epochs, we get an accuracy of 96% on the training set and 91.5% on the test set. Adding a second hidden layer did not improve performance. Distinguishing between Bacterial and Viral Pneumonia Not only do we want to distinguish between normal and pneumonia x-rays but we want to distinguish between the bacterial and viral pneumonia x-rays. To do this, we split up the folder containing pneumonia cases into two folders, one for bacteria cases and one for virus cases. Now, we have a three-class classification problem where the classes are normal, bacteria, and virus. Just as we used a CNN to solve the binary classification problem, we can use a CNN to solve the three-class classification problem. The code stays the same with a few exceptions. In the artificial neural network phase of the CNN, we change the number of output units from 1 to 3 and the output activation function from ‘sigmoid’ to ‘softmax’. When compiling the CNN, the loss function is changed from ‘binary_crossentropy’ to ‘categorical_crossentropy’. When fitting the CNN to the images, instead of using the folder ‘chest_xraybinary’, we use the folder ‘chest_xray’ which contains the training and test set folders that each have three folders corresponding to the three classes. The class_mode is changed from ‘binary’ to ‘categorical’. After 25 epochs, I got an accuracy of 80.64% on the training set and 83.33% on the test set. A second convolutional layer was added; and, after 25 epochs, I got an accuracy of 81.33% on the training set and 85.9% on the test set. This is a slight improvement in performance. In addition to the second convolutional layer, a second hidden layer was added; and, after 25 epochs, I got an accuracy of 80.25% on the training set and 86.7% on the test set. This is a slight improvement in performance on the test set. In addition to the second convolutional layer and the second hidden layer, I changed the number of feature detectors in the second convolutional layer from 32 to 64. After 25 epochs, I got an accuracy of 81% on the training set and 87% on the test set. This is a slight improvement in test set performance from the CNN with two convolutional layers and two hidden layers. However, it’s a decent improvement in test set performance from the CNN with one convolutional layer and one hidden layer. I then increased the dimensions of the images fed into the CNN from 64 by 64 to 128 by 128; this resulted in an accuracy of 80.85% on the training set and 85.74% on the test set, a worse performance than what we’ve reached so far. I brought the dimensions of the input images back down to 64 by 64 and added a third convolutional layer of 128 feature detectors. This resulted in an accuracy of 81.54% on the training set and 87.34% on the test set, a very small improvement on what we’ve got so far. Given the current settings, I ran the CNN for 200 epochs; the training set accuracy steadily increased to 96.32% while the training set accuracy fluctuated between the low 80’s and mid-80’s, ending at 86.54%. Keeping three convolutional layers, I added more hidden layers for a total of 10 hidden layers; after 25 epochs, I got a training set accuracy of 79.54% and a test set accuracy of 83.33%. So, adding more hidden layers didn’t lead to an improvement. Conclusion In this paper, we applied convolutional neural networks to the binary classification problem of determining which of two classes — normal or pneumonia — a chest x-ray falls under. We found that a CNN with one convolutional layer and one hidden layer achieved an accuracy of 95% on the training set and an accuracy of 89% on the test set. We then added a second convolutional layer to the CNN and achieved an accuracy of 96% on the training set and an accuracy of 91.5% on the test set; this improved performance by a little bit. Next, in addition to having a second convolutional layer, we added a second hidden layer and achieved an accuracy of 96% on the training set and an accuracy of 91.5% on the test set; this did not improve performance. We also applied convolutional neural networks to the three-class classification problem of determining which of three classes — normal, bacterial, or viral — a chest x-ray falls under. We found that a CNN with one convolutional layer and one hidden layer achieved an accuracy of 80.64% on the training set and an accuracy of 83.33% on the test set. We then added a second convolutional layer to the CNN and achieved an accuracy of 81.33% on the training set and an accuracy of 85.9% on the test set, which was a slight improvement. Next, in addition to having a second convolutional layer, we added a second hidden layer and achieved an accuracy of 80.25% on the training set and an accuracy of 86.7% on the test set, which was a slight improvement in performance on the test set but a decline in improvement on the training set. In addition to the second convolutional layer and the second hidden layer, changing the number of feature detectors in the second convolutional layer from 32 to 64 resulted, after 25 epochs, in an accuracy of 81% on the training set and 87% on the test set. Adding a third convolutional layer of 128 feature detectors resulted in an accuracy of 81.54% on the training set and 87.34% on the test set. Because we had a limited number of images in our total dataset, it was important to use image augmentation to provide more images to train our CNN; this lack of sufficient numbers of medical images seems to be a common problem for other medical issues besides pneumonia. Therefore, image augmentation promises to be a useful tool in any case in which there aren’t sufficient numbers of images. Given that, in certain parts of the world, there may be a shortage of trained professionals who can read and interpret x-rays, there is the potential for automated diagnosis based on a patient’s x-ray. In the case of classical machine learning techniques, sometimes we are able to identify particular attributes that are significant in determining the output of the machine learning model. In the case of convolutional neural networks, on the other hand, there is no set of attributes that we can identify as significant in determining the output of the CNN model; all we have are the images and their pixels. Further, it’s difficult to understand, in an intuitive way, how the CNN model is making its classifications. The CNN we’ve trained used chest x-rays of pediatric patients aged 1–5 from Guangzhou, China. Can our CNN be applied to children of other ages, to children outside of China, or even to adults? How might deep learning be used to detect the severity of a given case of pneumonia? These are open questions worth pursuing to further understand how image classification can be used to make medical diagnoses. The dataset can be found here: https://www.kaggle.com/paultimothymooney/chest-xray-pneumonia#IM-0007-0001.jpeg Data: https://data.mendeley.com/datasets/rscbjbr9sj/2 License: CC BY 4.0 Citation: http://www.cell.com/cell/fulltext/S0092-8674(18)30154-5 References Kermany et al. Illustrative Examples of Chest X-Rays in Patients with Pneumonia. Identifying Medical Diagnoses and Treatable Diseases by Image-Based Deep Learning, Cell 172, 1122–1131, 22 Feb. 2018, Elsevier Inc., https://doi.org/10.1016/j.cell.2018.02.010
[ { "code": null, "e": 60, "s": 47, "text": "Introduction" }, { "code": null, "e": 749, "s": 60, "text": "In the world of healthcare, one of the major issues that medical professionals face is the correct diagnosis of conditions and diseases of patients. Not being able to correctly diagnose a condition is a problem for both the patient and the doctor. The doctor is not benefitting the patient in the appropriate way if the doctor misdiagnoses the patient. This could lead to malpractice lawsuits and overall hurt the doctor’s business. The patient suffers by not receiving the proper treatment and risking greater harm to health by the condition that goes undetected; further, the patient undergoes unnecessary treatment and takes unnecessary medications, costing the patient time and money." }, { "code": null, "e": 1330, "s": 749, "text": "If we can correctly diagnose a patient’s condition, we have the potential to solve the above-mentioned problems. If we can produce deep learning models that can classify whether a patient has a condition or not, that can determine which particular condition the patient has, and that can determine the severity of the condition, then medical professionals will be able to use these models to better diagnose their patients. Accurate diagnosis can also be useful by allowing for timely treatment of a patient; being misdiagnosed can cause a delay in receiving the proper treatment." }, { "code": null, "e": 1503, "s": 1330, "text": "In this paper, we will perform deep learning to a dataset representing the chest x-rays of pediatric patients from Guangzhou Women and Children’s Medical Center, Guangzhou." }, { "code": null, "e": 1854, "s": 1503, "text": "I would like to apply a convolutional neural network (CNN) and try to classify a patient as either having pneumonia or not having pneumonia. This is a binary classification problem. I would also like to apply CNN’s to classify a patient as either having bacterial pneumonia, viral pneumonia, or no pneumonia. This is a 3-class classification problem." }, { "code": null, "e": 1901, "s": 1854, "text": "Here is a sample of what the x-rays look like:" }, { "code": null, "e": 2269, "s": 1901, "text": "[The normal chest X-ray (left panel) depicts clear lungs without any areas of abnormal opacification in the image. Bacterial pneumonia (middle) typically exhibits a focal lobar consolidation, in this case in the right upper lobe (white arrows), whereas viral pneumonia (right) manifests with a more diffuse “interstitial” pattern in both lungs. (Kermany et al, 2018)]" }, { "code": null, "e": 2644, "s": 2269, "text": "Apparently, bacterial pneumonia has areas of opaqueness that are more concentrated in one lobe whereas viral pneumonia has opaque areas more spread out on both lungs. The right lung is divided into three lobes, and the left lung is divided into two lobes. It’s certainly not obvious to me how to tell the difference. Hopefully, deep learning can help us tell the difference." }, { "code": null, "e": 2661, "s": 2644, "text": "Data Preparation" }, { "code": null, "e": 2772, "s": 2661, "text": "The dataset can be found here: https://www.kaggle.com/paultimothymooney/chest-xray-pneumonia#IM-0007-0001.jpeg" }, { "code": null, "e": 3407, "s": 2772, "text": "The data comes in two folders, one for the training set and one for the test set. The training set folder contains a folder of images for pneumonia cases and a folder of images for normal cases. The training set consists of 5216 images total. The test set folder contains a folder of images for pneumonia cases and a folder of images for normal cases. The test set consists of 624 images total, approximately 10.68% of the total set of images. Unlike the case in classical machine learning, we don’t have to worry about the various attributes of the dataset; in the case of convolutional neural networks, we just have a set of images." }, { "code": null, "e": 3437, "s": 3407, "text": "Convolutional Neural Networks" }, { "code": null, "e": 3828, "s": 3437, "text": "There is, however, some preparation of the images that is necessary before applying an artificial neural network. The images need to be prepared using convolutional layers in a process called convolution. There are several stages in this process — convolution operation, ReLU operation, pooling, and flattening; the end result is a vector that we can feed into an artificial neural network." }, { "code": null, "e": 3876, "s": 3828, "text": "Here is an image of a general CNN architecture:" }, { "code": null, "e": 4395, "s": 3876, "text": "During the convolution operation, various feature detectors are applied to the image, creating a stack of feature maps — this stack of feature maps is called a convolutional layer. ReLU is applied to each feature map to enhance non-linearity. During the pooling stage, also known as subsampling, we apply max-pooling (or some other type of pooling) to each feature map, creating smaller feature maps that preserve the relevant features of the image. The resulting stack of pooled featured maps forms the pooling layer." }, { "code": null, "e": 5055, "s": 4395, "text": "Once we get to the pooling layer, consisting of pooled feature maps, each pooled feature map is flattened into a vector and the resulting vectors are combined sequentially into one vector. The entries of this vector are fed into the input units of the artificial neural network. Thus, the entries of the flattened vector corresponding to one image are fed into the input units of the ANN. (This is in contrast to ANN’s used on a classical dataset where the attributes of a single instance are fed into the input units of the ANN). The artificial neural network is then trained on the training set and tested on the test set. Here is an image of a general ANN:" }, { "code": null, "e": 5236, "s": 5055, "text": "The ANN begins where it says ‘Fully connected’ in the diagram for the CNN architecture. As you can see, a convolutional neural network is the combination of convolution and an ANN." }, { "code": null, "e": 5263, "s": 5236, "text": "Building a CNN with Python" }, { "code": null, "e": 5330, "s": 5263, "text": "In order to build the CNN, we import Keras libraries and packages:" }, { "code": null, "e": 5546, "s": 5330, "text": "#Importing the Keras libraries and packagesfrom keras.models import Sequentialfrom keras.layers import Convolution2Dfrom keras.layers import MaxPooling2Dfrom keras.layers import Flattenfrom keras.layers import Dense" }, { "code": null, "e": 5909, "s": 5546, "text": "The Sequential package is used to initialise the CNN. The Convolution2D package is used to create the convolutional layers. The MaxPooling2D package is used to created the pooled feature maps. The Flatten package is used to flatten the stack of pooled feature maps into one vector that can be fed into the ANN. The Dense package is used to add layers to the ANN." }, { "code": null, "e": 6023, "s": 5909, "text": "Next, we initialize the CNN by creating an object of the Sequential class. This object we will call ‘classifier’:" }, { "code": null, "e": 6070, "s": 6023, "text": "#Initialising the CNNclassifier = Sequential()" }, { "code": null, "e": 6388, "s": 6070, "text": "We’re going to add one convolutional layer of 32 filter maps by applying 32 filters (feature detectors) of dimension 3 by 3 to the input image. We want our input images to have dimension 64 by 64 and treated as color images with 3 channels. We also apply ReLU to each feature map using the activation function ‘relu’:" }, { "code": null, "e": 6491, "s": 6388, "text": "#Step 1 - Convolutionclassifier.add(Convolution2D(32,(3,3),input_shape=(64,64,3),activation = 'relu'))" }, { "code": null, "e": 6615, "s": 6491, "text": "Now that we have our feature maps in the convolutional layer, we apply max-pooling to each feature map using a 2 by 2 grid." }, { "code": null, "e": 6668, "s": 6615, "text": "#Step 2 - Poolingclassifier.add(MaxPooling2D((2,2)))" }, { "code": null, "e": 6859, "s": 6668, "text": "Now that we have a pooling layer consisting of pooled feature maps, we flatten each pooled feature map into a vector and combine all the resulting vectors sequentially into one giant vector." }, { "code": null, "e": 6905, "s": 6859, "text": "#Step 3 - Flatteningclassifier.add(Flatten())" }, { "code": null, "e": 7244, "s": 6905, "text": "Next, we’re going to add our artificial neural network. First, we add a hidden layer of 128 units and use the activation function ‘relu’. Second, we add the output layer consisting of one output unit and use the sigmoid function as the activation function; we use one output unit because our output is binary (either normal or pneumonia)." }, { "code": null, "e": 7372, "s": 7244, "text": "#Step 4 - Full connectionclassifier.add(Dense(units=128,activation='relu'))classifier.add(Dense(units=1, activation='sigmoid'))" }, { "code": null, "e": 7564, "s": 7372, "text": "Now, we need to compile the CNN. We’re going to use ‘adam’ as the optimizer in stochastic gradient descent, binary cross-entropy for the loss function, and accuracy as the performance metric." }, { "code": null, "e": 7669, "s": 7564, "text": "#Compiling the CNNclassifier.compile(optimizer = 'adam',loss='binary_crossentropy',metrics=['accuracy'])" }, { "code": null, "e": 7951, "s": 7669, "text": "Our training set and test set combined has a total of 5840 images; so, we’re going to apply image augmentation to increase the size of our training set and test set while reducing overfitting. We then fit the CNN to our augmented training set and test it on our augmented test set:" }, { "code": null, "e": 8513, "s": 7951, "text": "#Fitting the CNN to the imagesfrom keras.preprocessing.image import ImageDataGeneratortrain_datagen = ImageDataGenerator(rescale=1./255,shear_range=0.2,zoom_range=0.2,horizontal_flip=True)test_datagen = ImageDataGenerator(rescale=1./255)training_set = train_datagen.flow_from_directory('chest_xraybinary/train',target_size=(64, 64),batch_size=32,class_mode='binary')test_set = test_datagen.flow_from_directory('chest_xraybinary/test',target_size=(64,64),batch_size=32,class_mode='binary')classifier.fit_generator(training_set,epochs=25,validation_data=test_set)" }, { "code": null, "e": 8600, "s": 8513, "text": "After 25 epochs, I got an accuracy of 95% on the training set and 89% on the test set." }, { "code": null, "e": 8642, "s": 8600, "text": "Evaluating, Improving, and Tuning the CNN" }, { "code": null, "e": 8872, "s": 8642, "text": "Previously, we built a CNN with one convolutional layer and one hidden layer. This time, we’re going to add a second convolutional layer and see if it improves performance. We simply add the following code after step 2 — pooling:" }, { "code": null, "e": 9003, "s": 8872, "text": "#Adding a second convolutional layerclassifier.add(Convolution2D(32,(3,3),activation = 'relu'))classifier.add(MaxPooling2D((2,2)))" }, { "code": null, "e": 9093, "s": 9003, "text": "After 25 epochs, we get an accuracy of 96% on the training set and 91.5% on the test set." }, { "code": null, "e": 9316, "s": 9093, "text": "Next, in addition to having a second convolutional layer, we’re going to add a second hidden layer and see if it improves performance. To add a second hidden layer, we simply duplicate the code for adding one hidden layer:" }, { "code": null, "e": 9494, "s": 9316, "text": "#Step 4 - Full connectionclassifier.add(Dense(units=128,activation='relu'))classifier.add(Dense(units=128,activation='relu'))classifier.add(Dense(units=1, activation='sigmoid'))" }, { "code": null, "e": 9642, "s": 9494, "text": "After 25 epochs, we get an accuracy of 96% on the training set and 91.5% on the test set. Adding a second hidden layer did not improve performance." }, { "code": null, "e": 9695, "s": 9642, "text": "Distinguishing between Bacterial and Viral Pneumonia" }, { "code": null, "e": 10813, "s": 9695, "text": "Not only do we want to distinguish between normal and pneumonia x-rays but we want to distinguish between the bacterial and viral pneumonia x-rays. To do this, we split up the folder containing pneumonia cases into two folders, one for bacteria cases and one for virus cases. Now, we have a three-class classification problem where the classes are normal, bacteria, and virus. Just as we used a CNN to solve the binary classification problem, we can use a CNN to solve the three-class classification problem. The code stays the same with a few exceptions. In the artificial neural network phase of the CNN, we change the number of output units from 1 to 3 and the output activation function from ‘sigmoid’ to ‘softmax’. When compiling the CNN, the loss function is changed from ‘binary_crossentropy’ to ‘categorical_crossentropy’. When fitting the CNN to the images, instead of using the folder ‘chest_xraybinary’, we use the folder ‘chest_xray’ which contains the training and test set folders that each have three folders corresponding to the three classes. The class_mode is changed from ‘binary’ to ‘categorical’." }, { "code": null, "e": 10906, "s": 10813, "text": "After 25 epochs, I got an accuracy of 80.64% on the training set and 83.33% on the test set." }, { "code": null, "e": 11088, "s": 10906, "text": "A second convolutional layer was added; and, after 25 epochs, I got an accuracy of 81.33% on the training set and 85.9% on the test set. This is a slight improvement in performance." }, { "code": null, "e": 11326, "s": 11088, "text": "In addition to the second convolutional layer, a second hidden layer was added; and, after 25 epochs, I got an accuracy of 80.25% on the training set and 86.7% on the test set. This is a slight improvement in performance on the test set." }, { "code": null, "e": 12052, "s": 11326, "text": "In addition to the second convolutional layer and the second hidden layer, I changed the number of feature detectors in the second convolutional layer from 32 to 64. After 25 epochs, I got an accuracy of 81% on the training set and 87% on the test set. This is a slight improvement in test set performance from the CNN with two convolutional layers and two hidden layers. However, it’s a decent improvement in test set performance from the CNN with one convolutional layer and one hidden layer. I then increased the dimensions of the images fed into the CNN from 64 by 64 to 128 by 128; this resulted in an accuracy of 80.85% on the training set and 85.74% on the test set, a worse performance than what we’ve reached so far." }, { "code": null, "e": 12530, "s": 12052, "text": "I brought the dimensions of the input images back down to 64 by 64 and added a third convolutional layer of 128 feature detectors. This resulted in an accuracy of 81.54% on the training set and 87.34% on the test set, a very small improvement on what we’ve got so far. Given the current settings, I ran the CNN for 200 epochs; the training set accuracy steadily increased to 96.32% while the training set accuracy fluctuated between the low 80’s and mid-80’s, ending at 86.54%." }, { "code": null, "e": 12779, "s": 12530, "text": "Keeping three convolutional layers, I added more hidden layers for a total of 10 hidden layers; after 25 epochs, I got a training set accuracy of 79.54% and a test set accuracy of 83.33%. So, adding more hidden layers didn’t lead to an improvement." }, { "code": null, "e": 12790, "s": 12779, "text": "Conclusion" }, { "code": null, "e": 13536, "s": 12790, "text": "In this paper, we applied convolutional neural networks to the binary classification problem of determining which of two classes — normal or pneumonia — a chest x-ray falls under. We found that a CNN with one convolutional layer and one hidden layer achieved an accuracy of 95% on the training set and an accuracy of 89% on the test set. We then added a second convolutional layer to the CNN and achieved an accuracy of 96% on the training set and an accuracy of 91.5% on the test set; this improved performance by a little bit. Next, in addition to having a second convolutional layer, we added a second hidden layer and achieved an accuracy of 96% on the training set and an accuracy of 91.5% on the test set; this did not improve performance." }, { "code": null, "e": 14766, "s": 13536, "text": "We also applied convolutional neural networks to the three-class classification problem of determining which of three classes — normal, bacterial, or viral — a chest x-ray falls under. We found that a CNN with one convolutional layer and one hidden layer achieved an accuracy of 80.64% on the training set and an accuracy of 83.33% on the test set. We then added a second convolutional layer to the CNN and achieved an accuracy of 81.33% on the training set and an accuracy of 85.9% on the test set, which was a slight improvement. Next, in addition to having a second convolutional layer, we added a second hidden layer and achieved an accuracy of 80.25% on the training set and an accuracy of 86.7% on the test set, which was a slight improvement in performance on the test set but a decline in improvement on the training set. In addition to the second convolutional layer and the second hidden layer, changing the number of feature detectors in the second convolutional layer from 32 to 64 resulted, after 25 epochs, in an accuracy of 81% on the training set and 87% on the test set. Adding a third convolutional layer of 128 feature detectors resulted in an accuracy of 81.54% on the training set and 87.34% on the test set." }, { "code": null, "e": 15160, "s": 14766, "text": "Because we had a limited number of images in our total dataset, it was important to use image augmentation to provide more images to train our CNN; this lack of sufficient numbers of medical images seems to be a common problem for other medical issues besides pneumonia. Therefore, image augmentation promises to be a useful tool in any case in which there aren’t sufficient numbers of images." }, { "code": null, "e": 15362, "s": 15160, "text": "Given that, in certain parts of the world, there may be a shortage of trained professionals who can read and interpret x-rays, there is the potential for automated diagnosis based on a patient’s x-ray." }, { "code": null, "e": 15879, "s": 15362, "text": "In the case of classical machine learning techniques, sometimes we are able to identify particular attributes that are significant in determining the output of the machine learning model. In the case of convolutional neural networks, on the other hand, there is no set of attributes that we can identify as significant in determining the output of the CNN model; all we have are the images and their pixels. Further, it’s difficult to understand, in an intuitive way, how the CNN model is making its classifications." }, { "code": null, "e": 16283, "s": 15879, "text": "The CNN we’ve trained used chest x-rays of pediatric patients aged 1–5 from Guangzhou, China. Can our CNN be applied to children of other ages, to children outside of China, or even to adults? How might deep learning be used to detect the severity of a given case of pneumonia? These are open questions worth pursuing to further understand how image classification can be used to make medical diagnoses." }, { "code": null, "e": 16314, "s": 16283, "text": "The dataset can be found here:" }, { "code": null, "e": 16394, "s": 16314, "text": "https://www.kaggle.com/paultimothymooney/chest-xray-pneumonia#IM-0007-0001.jpeg" }, { "code": null, "e": 16448, "s": 16394, "text": "Data: https://data.mendeley.com/datasets/rscbjbr9sj/2" }, { "code": null, "e": 16467, "s": 16448, "text": "License: CC BY 4.0" }, { "code": null, "e": 16533, "s": 16467, "text": "Citation: http://www.cell.com/cell/fulltext/S0092-8674(18)30154-5" }, { "code": null, "e": 16544, "s": 16533, "text": "References" }, { "code": null, "e": 16669, "s": 16544, "text": "Kermany et al. Illustrative Examples of Chest X-Rays in Patients with Pneumonia. Identifying Medical Diagnoses and Treatable" } ]
AWT CardLayout Class
The class CardLayout arranges each component in the container as a card. Only one card is visible at a time, and the container acts as a stack of cards. Following is the declaration for java.awt.CardLayout class: public class CardLayout extends Object implements LayoutManager2, Serializable CardLayout() Creates a new card layout with gaps of size zero. CardLayout(int hgap, int vgap) Creates a new card layout with the specified horizontal and vertical gaps. void addLayoutComponent(Component comp, Object constraints) Adds the specified component to this card layout's internal table of names. void addLayoutComponent(String name, Component comp) If the layout manager uses a per-component string, adds the component comp to the layout, associating it with the string specified by name. void first(Container parent) Flips to the first card of the container. int getHgap() Gets the horizontal gap between components. float getLayoutAlignmentX(Container parent) Returns the alignment along the x axis. float getLayoutAlignmentY(Container parent) Returns the alignment along the y axis. int getVgap() Gets the vertical gap between components. void invalidateLayout(Container target) Invalidates the layout, indicating that if the layout manager has cached information it should be discarded. void last(Container parent) Flips to the last card of the container. void layoutContainer(Container parent) Lays out the specified container using this card layout. Dimension maximumLayoutSize(Container target) Returns the maximum dimensions for this layout given the components in the specified target container. Dimension minimumLayoutSize(Container parent) Calculates the minimum size for the specified panel. void next(Container parent) Flips to the next card of the specified container. Dimension preferredLayoutSize(Container parent) Determines the preferred size of the container argument using this card layout. void previous(Container parent) Flips to the previous card of the specified container. void removeLayoutComponent(Component comp) Removes the specified component from the layout. void setHgap(int hgap) Sets the horizontal gap between components. void setVgap(int vgap) Sets the vertical gap between components. void show(Container parent, String name) Flips to the component that was added to this layout with the specified name, using addLayoutComponent. String toString() Returns a string representation of the state of this card layout. This class inherits methods from the following classes: java.lang.Object java.lang.Object Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui > package com.tutorialspoint.gui; import java.awt.*; import java.awt.event.*; public class AwtLayoutDemo { private Frame mainFrame; private Label headerLabel; private Label statusLabel; private Panel controlPanel; private Label msglabel; public AwtLayoutDemo(){ prepareGUI(); } public static void main(String[] args){ AwtLayoutDemo awtLayoutDemo = new AwtLayoutDemo(); awtLayoutDemo.showCardLayoutDemo(); } private void prepareGUI(){ mainFrame = new Frame("Java AWT Examples"); mainFrame.setSize(400,400); mainFrame.setLayout(new GridLayout(3, 1)); mainFrame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent windowEvent){ System.exit(0); } }); headerLabel = new Label(); headerLabel.setAlignment(Label.CENTER); statusLabel = new Label(); statusLabel.setAlignment(Label.CENTER); statusLabel.setSize(350,100); msglabel = new Label(); msglabel.setAlignment(Label.CENTER); msglabel.setText("Welcome to TutorialsPoint AWT Tutorial."); controlPanel = new Panel(); controlPanel.setLayout(new FlowLayout()); mainFrame.add(headerLabel); mainFrame.add(controlPanel); mainFrame.add(statusLabel); mainFrame.setVisible(true); } private void showCardLayoutDemo(){ headerLabel.setText("Layout in action: CardLayout"); final Panel panel = new Panel(); panel.setBackground(Color.CYAN); panel.setSize(300,300); CardLayout layout = new CardLayout(); layout.setHgap(10); layout.setVgap(10); panel.setLayout(layout); Panel buttonPanel = new Panel(new FlowLayout()); buttonPanel.add(new Button("OK")); buttonPanel.add(new Button("Cancel")); Panel textBoxPanel = new Panel(new FlowLayout()); textBoxPanel.add(new Label("Name:")); textBoxPanel.add(new TextField(20)); panel.add("Button", buttonPanel); panel.add("Text", textBoxPanel); Choice choice = new Choice(); choice.add("Button"); choice.add("Text"); choice.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { CardLayout cardLayout = (CardLayout)(panel.getLayout()); cardLayout.show(panel, (String)e.getItem()); } }); controlPanel.add(choice); controlPanel.add(panel); mainFrame.setVisible(true); } } Compile the program using command prompt. Go to D:/ > AWT and type the following command. D:\AWT>javac com\tutorialspoint\gui\AwtlayoutDemo.java If no error comes that means compilation is successful. Run the program using following command. D:\AWT>java com.tutorialspoint.gui.AwtlayoutDemo Verify the following output 13 Lectures 2 hours EduOLC Print Add Notes Bookmark this page
[ { "code": null, "e": 1900, "s": 1747, "text": "The class CardLayout arranges each component in the container as a card. Only one card is visible at a time, and the container acts as a stack of cards." }, { "code": null, "e": 1960, "s": 1900, "text": "Following is the declaration for java.awt.CardLayout class:" }, { "code": null, "e": 2048, "s": 1960, "text": "public class CardLayout\n extends Object\n implements LayoutManager2, Serializable" }, { "code": null, "e": 2062, "s": 2048, "text": "CardLayout() " }, { "code": null, "e": 2112, "s": 2062, "text": "Creates a new card layout with gaps of size zero." }, { "code": null, "e": 2144, "s": 2112, "text": "CardLayout(int hgap, int vgap) " }, { "code": null, "e": 2219, "s": 2144, "text": "Creates a new card layout with the specified horizontal and vertical gaps." }, { "code": null, "e": 2280, "s": 2219, "text": "void addLayoutComponent(Component comp, Object constraints) " }, { "code": null, "e": 2356, "s": 2280, "text": "Adds the specified component to this card layout's internal table of names." }, { "code": null, "e": 2410, "s": 2356, "text": "void addLayoutComponent(String name, Component comp) " }, { "code": null, "e": 2550, "s": 2410, "text": "If the layout manager uses a per-component string, adds the component comp to the layout, associating it with the string specified by name." }, { "code": null, "e": 2580, "s": 2550, "text": "void first(Container parent) " }, { "code": null, "e": 2622, "s": 2580, "text": "Flips to the first card of the container." }, { "code": null, "e": 2637, "s": 2622, "text": "int getHgap() " }, { "code": null, "e": 2681, "s": 2637, "text": "Gets the horizontal gap between components." }, { "code": null, "e": 2726, "s": 2681, "text": "float getLayoutAlignmentX(Container parent) " }, { "code": null, "e": 2766, "s": 2726, "text": "Returns the alignment along the x axis." }, { "code": null, "e": 2811, "s": 2766, "text": "float getLayoutAlignmentY(Container parent) " }, { "code": null, "e": 2851, "s": 2811, "text": "Returns the alignment along the y axis." }, { "code": null, "e": 2866, "s": 2851, "text": "int getVgap() " }, { "code": null, "e": 2908, "s": 2866, "text": "Gets the vertical gap between components." }, { "code": null, "e": 2949, "s": 2908, "text": "void invalidateLayout(Container target) " }, { "code": null, "e": 3058, "s": 2949, "text": "Invalidates the layout, indicating that if the layout manager has cached information it should be discarded." }, { "code": null, "e": 3087, "s": 3058, "text": "void last(Container parent) " }, { "code": null, "e": 3128, "s": 3087, "text": "Flips to the last card of the container." }, { "code": null, "e": 3168, "s": 3128, "text": "void layoutContainer(Container parent) " }, { "code": null, "e": 3225, "s": 3168, "text": "Lays out the specified container using this card layout." }, { "code": null, "e": 3272, "s": 3225, "text": "Dimension maximumLayoutSize(Container target) " }, { "code": null, "e": 3375, "s": 3272, "text": "Returns the maximum dimensions for this layout given the components in the specified target container." }, { "code": null, "e": 3422, "s": 3375, "text": "Dimension minimumLayoutSize(Container parent) " }, { "code": null, "e": 3475, "s": 3422, "text": "Calculates the minimum size for the specified panel." }, { "code": null, "e": 3504, "s": 3475, "text": "void next(Container parent) " }, { "code": null, "e": 3555, "s": 3504, "text": "Flips to the next card of the specified container." }, { "code": null, "e": 3604, "s": 3555, "text": "Dimension preferredLayoutSize(Container parent) " }, { "code": null, "e": 3684, "s": 3604, "text": "Determines the preferred size of the container argument using this card layout." }, { "code": null, "e": 3717, "s": 3684, "text": "void previous(Container parent) " }, { "code": null, "e": 3772, "s": 3717, "text": "Flips to the previous card of the specified container." }, { "code": null, "e": 3816, "s": 3772, "text": "void removeLayoutComponent(Component comp) " }, { "code": null, "e": 3865, "s": 3816, "text": "Removes the specified component from the layout." }, { "code": null, "e": 3889, "s": 3865, "text": "void setHgap(int hgap) " }, { "code": null, "e": 3933, "s": 3889, "text": "Sets the horizontal gap between components." }, { "code": null, "e": 3957, "s": 3933, "text": "void setVgap(int vgap) " }, { "code": null, "e": 3999, "s": 3957, "text": "Sets the vertical gap between components." }, { "code": null, "e": 4041, "s": 3999, "text": "void show(Container parent, String name) " }, { "code": null, "e": 4145, "s": 4041, "text": "Flips to the component that was added to this layout with the specified name, using addLayoutComponent." }, { "code": null, "e": 4164, "s": 4145, "text": "String toString() " }, { "code": null, "e": 4230, "s": 4164, "text": "Returns a string representation of the state of this card layout." }, { "code": null, "e": 4286, "s": 4230, "text": "This class inherits methods from the following classes:" }, { "code": null, "e": 4303, "s": 4286, "text": "java.lang.Object" }, { "code": null, "e": 4320, "s": 4303, "text": "java.lang.Object" }, { "code": null, "e": 4434, "s": 4320, "text": "Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >" }, { "code": null, "e": 6987, "s": 4434, "text": "package com.tutorialspoint.gui;\n\nimport java.awt.*;\nimport java.awt.event.*;\n\npublic class AwtLayoutDemo {\n private Frame mainFrame;\n private Label headerLabel;\n private Label statusLabel;\n private Panel controlPanel;\n private Label msglabel;\n\n public AwtLayoutDemo(){\n prepareGUI();\n }\n\n public static void main(String[] args){\n AwtLayoutDemo awtLayoutDemo = new AwtLayoutDemo(); \n awtLayoutDemo.showCardLayoutDemo(); \n }\n \n private void prepareGUI(){\n mainFrame = new Frame(\"Java AWT Examples\");\n mainFrame.setSize(400,400);\n mainFrame.setLayout(new GridLayout(3, 1));\n mainFrame.addWindowListener(new WindowAdapter() {\n public void windowClosing(WindowEvent windowEvent){\n System.exit(0);\n } \n }); \n headerLabel = new Label();\n headerLabel.setAlignment(Label.CENTER);\n statusLabel = new Label(); \n statusLabel.setAlignment(Label.CENTER);\n statusLabel.setSize(350,100);\n\n msglabel = new Label();\n msglabel.setAlignment(Label.CENTER);\n msglabel.setText(\"Welcome to TutorialsPoint AWT Tutorial.\");\n\n controlPanel = new Panel();\n controlPanel.setLayout(new FlowLayout());\n\n mainFrame.add(headerLabel);\n mainFrame.add(controlPanel);\n mainFrame.add(statusLabel);\n mainFrame.setVisible(true); \n }\n\n private void showCardLayoutDemo(){\n headerLabel.setText(\"Layout in action: CardLayout\"); \n\n final Panel panel = new Panel();\n panel.setBackground(Color.CYAN);\n panel.setSize(300,300);\n\n CardLayout layout = new CardLayout();\n layout.setHgap(10);\n layout.setVgap(10);\n panel.setLayout(layout); \n\n Panel buttonPanel = new Panel(new FlowLayout());\n\n buttonPanel.add(new Button(\"OK\"));\n buttonPanel.add(new Button(\"Cancel\")); \n\n Panel textBoxPanel = new Panel(new FlowLayout());\n\n textBoxPanel.add(new Label(\"Name:\"));\n textBoxPanel.add(new TextField(20));\n\n panel.add(\"Button\", buttonPanel);\n panel.add(\"Text\", textBoxPanel);\n\n Choice choice = new Choice();\n choice.add(\"Button\");\n choice.add(\"Text\");\n\n choice.addItemListener(new ItemListener() {\n public void itemStateChanged(ItemEvent e) {\n CardLayout cardLayout = (CardLayout)(panel.getLayout());\n cardLayout.show(panel, (String)e.getItem());\n }\n });\n controlPanel.add(choice);\n controlPanel.add(panel);\n\n mainFrame.setVisible(true); \n }\n}" }, { "code": null, "e": 7078, "s": 6987, "text": "Compile the program using command prompt. Go to D:/ > AWT and type the following command." }, { "code": null, "e": 7133, "s": 7078, "text": "D:\\AWT>javac com\\tutorialspoint\\gui\\AwtlayoutDemo.java" }, { "code": null, "e": 7230, "s": 7133, "text": "If no error comes that means compilation is successful. Run the program using following command." }, { "code": null, "e": 7279, "s": 7230, "text": "D:\\AWT>java com.tutorialspoint.gui.AwtlayoutDemo" }, { "code": null, "e": 7307, "s": 7279, "text": "Verify the following output" }, { "code": null, "e": 7340, "s": 7307, "text": "\n 13 Lectures \n 2 hours \n" }, { "code": null, "e": 7348, "s": 7340, "text": " EduOLC" }, { "code": null, "e": 7355, "s": 7348, "text": " Print" }, { "code": null, "e": 7366, "s": 7355, "text": " Add Notes" } ]
How to order by timestamp in MySQL?
To order by timestamp, use the ORDER BY as in the following syntax − select *from yourTableName ORDER BY STR_TO_DATE(`yourColumnName`,'%m/%d/%Y%h:%i:%s %p'); Let us first create a table − mysql> create table DemoTable -> ( -> `timestamp` varchar(100) -> ); Query OK, 0 rows affected (0.56 sec) Insert some records in the table using insert command − mysql> insert into DemoTable values('06/22/2019 01:10:20 PM'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable values('06/22/2019 12:00:27 PM'); Query OK, 1 row affected (0.26 sec) mysql> insert into DemoTable values('06/22/2019 06:56:20 AM'); Query OK, 1 row affected (0.23 sec) mysql> insert into DemoTable values('06/22/2019 07:10:11 AM'); Query OK, 1 row affected (0.15 sec) Display all records from the table using select statement − mysql> select *from DemoTable; This will produce the following output − +------------------------+ | timestamp | +------------------------+ | 06/22/2019 01:10:20 PM | | 06/22/2019 12:00:27 PM | | 06/22/2019 06:56:20 AM | | 06/22/2019 07:10:11 AM | +------------------------+ 4 rows in set (0.00 sec) Following is the query to order by timestamp in MySQL − mysql> select *from DemoTable ORDER BY STR_TO_DATE(`timestamp`,'%m/%d/%Y%h:%i:%s %p'); This will produce the following output − +------------------------+ | timestamp | +------------------------+ | 06/22/2019 06:56:20 AM | | 06/22/2019 07:10:11 AM | | 06/22/2019 12:00:27 PM | | 06/22/2019 01:10:20 PM | +------------------------+ 4 rows in set (0.00 sec)
[ { "code": null, "e": 1131, "s": 1062, "text": "To order by timestamp, use the ORDER BY as in the following syntax −" }, { "code": null, "e": 1220, "s": 1131, "text": "select *from yourTableName ORDER BY STR_TO_DATE(`yourColumnName`,'%m/%d/%Y%h:%i:%s %p');" }, { "code": null, "e": 1250, "s": 1220, "text": "Let us first create a table −" }, { "code": null, "e": 1365, "s": 1250, "text": "mysql> create table DemoTable\n -> (\n -> `timestamp` varchar(100)\n -> );\nQuery OK, 0 rows affected (0.56 sec)" }, { "code": null, "e": 1421, "s": 1365, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1820, "s": 1421, "text": "mysql> insert into DemoTable values('06/22/2019 01:10:20 PM');\nQuery OK, 1 row affected (0.13 sec)\n\nmysql> insert into DemoTable values('06/22/2019 12:00:27 PM');\nQuery OK, 1 row affected (0.26 sec)\n\nmysql> insert into DemoTable values('06/22/2019 06:56:20 AM');\nQuery OK, 1 row affected (0.23 sec)\n\nmysql> insert into DemoTable values('06/22/2019 07:10:11 AM');\nQuery OK, 1 row affected (0.15 sec)" }, { "code": null, "e": 1880, "s": 1820, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1911, "s": 1880, "text": "mysql> select *from DemoTable;" }, { "code": null, "e": 1952, "s": 1911, "text": "This will produce the following output −" }, { "code": null, "e": 2193, "s": 1952, "text": "+------------------------+\n| timestamp |\n+------------------------+\n| 06/22/2019 01:10:20 PM |\n| 06/22/2019 12:00:27 PM |\n| 06/22/2019 06:56:20 AM |\n| 06/22/2019 07:10:11 AM |\n+------------------------+\n4 rows in set (0.00 sec)" }, { "code": null, "e": 2249, "s": 2193, "text": "Following is the query to order by timestamp in MySQL −" }, { "code": null, "e": 2336, "s": 2249, "text": "mysql> select *from DemoTable ORDER BY STR_TO_DATE(`timestamp`,'%m/%d/%Y%h:%i:%s %p');" }, { "code": null, "e": 2377, "s": 2336, "text": "This will produce the following output −" }, { "code": null, "e": 2618, "s": 2377, "text": "+------------------------+\n| timestamp |\n+------------------------+\n| 06/22/2019 06:56:20 AM |\n| 06/22/2019 07:10:11 AM |\n| 06/22/2019 12:00:27 PM |\n| 06/22/2019 01:10:20 PM |\n+------------------------+\n4 rows in set (0.00 sec)" } ]
What is the meaning of <> in MySQL query?
The symbol <> in MySQL is same as not equal to operator (!=). Both gives the result in boolean or tinyint(1). If the condition becomes true, then the result will be 1 otherwise 0. Case 1 − Using != operator. The query is as follows − mysql> select 3!=5; The following is the output. +------+ | 3!=5 | +------+ | 1 | +------+ 1 row in set (0.00 sec) Case 2 − Using <> operator. The query is as follows − mysql> select 3 <> 5; The following is the output. +--------+ | 3 <> 5 | +--------+ | 1 | +--------+ 1 row in set (0.00 sec) The <> operator can be used to return a set of rows from the table. The <> is a standard ANSI SQL. Let us first create a table. The query to create a table is as follows − mysql> create table NotEqualOperator -> ( -> StudentId int, -> StudentName varchar(100), -> StudentSection varchar(10) -> ); Query OK, 0 rows affected (0.78 sec) Insert some records in the table using insert command. The query is as follows. mysql> insert into NotEqualOperator values(1,'John','A'); Query OK, 1 row affected (0.19 sec) mysql> insert into NotEqualOperator values(2,'Carol','B'); Query OK, 1 row affected (0.19 sec) mysql> insert into NotEqualOperator values(3,'Sam','A'); Query OK, 1 row affected (0.15 sec) mysql> insert into NotEqualOperator values(4,'Mike','B'); Query OK, 1 row affected (0.23 sec) mysql> insert into NotEqualOperator values(5,'Bob','B'); Query OK, 1 row affected (0.19 sec) mysql> insert into NotEqualOperator values(6,'David','B'); Query OK, 1 row affected (0.14 sec) mysql> insert into NotEqualOperator values(7,'Ramit','A'); Query OK, 1 row affected (0.18 sec) Display all records from the table using select statement. The query is as follows. mysql> select *from NotEqualOperator; The following is the output. +-----------+-------------+----------------+ | StudentId | StudentName | StudentSection | +-----------+-------------+----------------+ | 1 | John | A | | 2 | Carol | B | | 3 | Sam | A | | 4 | Mike | B | | 5 | Bob | B | | 6 | David | B | | 7 | Ramit | A | +-----------+-------------+----------------+ 7 rows in set (0.00 sec) As discussed above, the <> operator can be used to return a set of rows. Now filter the above table to get those students only that does not belong to section A. The query is as follows. mysql> select *from NotEqualOperator where StudentSection <>'A'; The following is the output. +-----------+-------------+----------------+ | StudentId | StudentName | StudentSection | +-----------+-------------+----------------+ | 2 | Carol | B | | 4 | Mike | B | | 5 | Bob | B | | 6 | David | B | +-----------+-------------+----------------+ 4 rows in set (0.00 sec)
[ { "code": null, "e": 1242, "s": 1062, "text": "The symbol <> in MySQL is same as not equal to operator (!=). Both gives the result in boolean or tinyint(1). If the condition becomes true, then the result will be 1 otherwise 0." }, { "code": null, "e": 1270, "s": 1242, "text": "Case 1 − Using != operator." }, { "code": null, "e": 1296, "s": 1270, "text": "The query is as follows −" }, { "code": null, "e": 1316, "s": 1296, "text": "mysql> select 3!=5;" }, { "code": null, "e": 1345, "s": 1316, "text": "The following is the output." }, { "code": null, "e": 1414, "s": 1345, "text": "+------+\n| 3!=5 |\n+------+\n| 1 |\n+------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 1442, "s": 1414, "text": "Case 2 − Using <> operator." }, { "code": null, "e": 1468, "s": 1442, "text": "The query is as follows −" }, { "code": null, "e": 1490, "s": 1468, "text": "mysql> select 3 <> 5;" }, { "code": null, "e": 1519, "s": 1490, "text": "The following is the output." }, { "code": null, "e": 1598, "s": 1519, "text": "+--------+\n| 3 <> 5 |\n+--------+\n| 1 |\n+--------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 1697, "s": 1598, "text": "The <> operator can be used to return a set of rows from the table. The <> is a standard ANSI SQL." }, { "code": null, "e": 1770, "s": 1697, "text": "Let us first create a table. The query to create a table is as follows −" }, { "code": null, "e": 1932, "s": 1770, "text": "mysql> create table NotEqualOperator\n-> (\n-> StudentId int,\n-> StudentName varchar(100),\n-> StudentSection varchar(10)\n-> );\nQuery OK, 0 rows affected (0.78 sec)" }, { "code": null, "e": 2012, "s": 1932, "text": "Insert some records in the table using insert command. The query is as follows." }, { "code": null, "e": 2677, "s": 2012, "text": "mysql> insert into NotEqualOperator values(1,'John','A');\nQuery OK, 1 row affected (0.19 sec)\n\nmysql> insert into NotEqualOperator values(2,'Carol','B');\nQuery OK, 1 row affected (0.19 sec)\n\nmysql> insert into NotEqualOperator values(3,'Sam','A');\nQuery OK, 1 row affected (0.15 sec)\n\nmysql> insert into NotEqualOperator values(4,'Mike','B');\nQuery OK, 1 row affected (0.23 sec)\n\nmysql> insert into NotEqualOperator values(5,'Bob','B');\nQuery OK, 1 row affected (0.19 sec)\n\nmysql> insert into NotEqualOperator values(6,'David','B');\nQuery OK, 1 row affected (0.14 sec)\n\nmysql> insert into NotEqualOperator values(7,'Ramit','A');\nQuery OK, 1 row affected (0.18 sec)" }, { "code": null, "e": 2761, "s": 2677, "text": "Display all records from the table using select statement. The query is as follows." }, { "code": null, "e": 2799, "s": 2761, "text": "mysql> select *from NotEqualOperator;" }, { "code": null, "e": 2828, "s": 2799, "text": "The following is the output." }, { "code": null, "e": 3350, "s": 2828, "text": "+-----------+-------------+----------------+\n| StudentId | StudentName | StudentSection |\n+-----------+-------------+----------------+\n| 1 | John | A |\n| 2 | Carol | B |\n| 3 | Sam | A |\n| 4 | Mike | B |\n| 5 | Bob | B |\n| 6 | David | B | \n| 7 | Ramit | A |\n+-----------+-------------+----------------+\n7 rows in set (0.00 sec)" }, { "code": null, "e": 3512, "s": 3350, "text": "As discussed above, the <> operator can be used to return a set of rows. Now filter the above table to get those students only that does not belong to section A." }, { "code": null, "e": 3537, "s": 3512, "text": "The query is as follows." }, { "code": null, "e": 3602, "s": 3537, "text": "mysql> select *from NotEqualOperator where StudentSection <>'A';" }, { "code": null, "e": 3631, "s": 3602, "text": "The following is the output." }, { "code": null, "e": 4016, "s": 3631, "text": "+-----------+-------------+----------------+\n| StudentId | StudentName | StudentSection |\n+-----------+-------------+----------------+\n| 2 | Carol | B |\n| 4 | Mike | B |\n| 5 | Bob | B |\n| 6 | David | B |\n+-----------+-------------+----------------+\n4 rows in set (0.00 sec)" } ]
Graph Machine Learning with Python Part 1: Basics, Metrics, and Algorithms | by Ani Madurkar | Towards Data Science
Graph-based methods are some of the most fascinating and powerful techniques in the Data Science world today. Even so, I believe we’re in the early stages of widespread adoption of these methods. In this series, I’ll provide an extensive walkthrough of Graph Machine Learning starting with an overview of metrics and algorithms. I’ll also provide implementation code via Python to keep things as applied as possible. Before we get started, let’s discuss the value of graph-based methods. Why Graphs?Network BasicsNetwork ConnectivityNetwork DistanceNetwork ClusteringNetwork Degree DistributionsNetwork CentralitySummary Why Graphs? Network Basics Network Connectivity Network Distance Network Clustering Network Degree Distributions Network Centrality Summary Graphs are a general language for describing and analyzing entities with relations/interactions Graphs are prevalent all around us from computer networks to social networks to disease pathways. Networks are often referred to as graphs that occur naturally, but the line is quite blurred and they do get used interchangeably. Dr. Jure Leskovec, in his Machine Learning for Graphs course, outlines a few examples such as: Graphs (as a representation): Information/knowledge are organized and linked Software can be represented as a graph Similarity networks: Connect similar data points Relational structures: Molecules, Scene graphs, 3D shapes, Particle-based physics simulations Networks (also known as Natural Graphs): Social networks: Society is a collection of 7+ billion individuals Communication and transactions: Electronic devices, phone calls, financial transactions Biomedicine: Interactions between genes/proteins regulate life Brain connections: Our thoughts are hidden in the connections between billions of neurons Representing data as a graph allows us to embed complex structural information as features. This yields higher performance in some domains as relational structure can provide a plethora of valuable information. In addition to a stronger feature representation, graph-based methods (specifically for Deep Learning) leverages representation learning to automatically learn features and represent them as an embedding. Due to this, a large amount of high dimensional information can be encoded in a sparse space without sacrificing speed/performance significantly. Another noteworthy benefit of leveraging graphs is the variety of tasks one can use them for. Dr. Leskovec provides insight into classic applications: Node classification: Predict a property of a node. Example: Categorize online users/items Link prediction: Predict whether there are missing links between two nodes. Example: Knowledge graph completion, recommender systems Graph classification: Categorize different graphs. Example: Molecule property prediction Clustering: Detect if nodes form a community. Example: Social circle detection Graph generation: Drug discovery Graph evolution: Physical simulation I kept it brief here, but I highly recommend reviewing the slides from Dr. Leskovec’s first lecture if you’d like a deeper review of applications of Graph Machine Learning. Although we are able to embed high-dimensional data to achieve higher performance models for a variety of tasks, networks can be incredibly complex. This is due to: Arbitrary size and complex topological structureNo fixed node ordering or reference pointOften dynamic and have multimodal features Arbitrary size and complex topological structure No fixed node ordering or reference point Often dynamic and have multimodal features We often need statistical analysis, models, and algorithms to assist our ability to understand and reason from networks. Network models assist to simulate dispersion and cascade of information through a network due to its inherent relational structure. This yields tremendous insight of how knowledge, information, etc. propagates instead of just what propagates. A network (or graph) is a representation of connections among a set of items. This representation is often written as G=(V,E) , where V={V1,...,Vn} is a set of nodes (also called vertices) and E={{Vk,Vw},..,{Vi,Vj}} is a set of two-sets (set of two elements) of edges (also called links), representing the connection between two nodes belonging to V. In a network visualization, distance and location carries no meaning. Networks can also take a series of different structures and attributes. Undirected: Have no direction, useful for cases where relationships are symmetric Directed: Have direction, useful for asymmetrical relationships Cyclic: Paths start and end at the same node, endless cycles may prevent termination without caution Acyclic: Paths start and end at different nodes, basis of many algorithms Weighted: Not all relationships are equal, some carry more weight Unweighted: All relationships are equal (according to network) shown by equal/non-existent weighting Sparse: Every node in the subset may not have a path to every other node Dense: Every node in the subset has a path to every other node Monopartite, bipartite, and k-partite: Whether nodes connect to only one other node type (e.g., users like movies) or many other node types (e.g., users like users who like movies) Neo4J provides a great summary visualization for each: Networks also have some basic properties that advanced methods and techniques build upon. The order of a graph is the number of its vertices |V|. The size of a graph is the number of its edges |E|. The degree of a vertex is the number of edges that are adjacent to it. The neighbors of a vertex v in a graph G is a subset of vertex Vi induced by all vertices adjacent to v. The neighborhood graph (also known as an ego graph) of a vertex v in a graph G is a subgraph of G, composed of the vertices adjacent to v and all edges connecting vertices adjacent to v. There are numerous datasets with a preloaded network structure available to do work on. This is due to the graciousness of the research and applied community sharing their work and datasets. To get started with our own network, we can load in one of these NetworkX’s datasets and as a sports fan I’ll choose the Football dataset (M. Girvan and M. E. J. Newman, Community structure in social and biological networks, Proc. Natl. Acad. Sci. USA 99, 7821–7826 (2002)). This dataset is open licensed by Girvan and Newman and shown on NetworkX Datasets. Graph Summary:Number of nodes : 115Number of edges : 613Maximum degree : 12Minimum degree : 7Average degree : 10.660869565217391Median degree : 11.0... A connected graph is a graph where every pair of nodes has a path between them. In a graph, there can be multiple connected components; these are subsets of nodes such that: 1. every node in the subset has a path to every other node, 2. no other node has a path to any node in the subset. Strongly connected components are considered subsets of nodes that: 1. every node in the subset has a path to every other node, 2. no other node has a path to and from every node in the subset. Weakly connected components are subsets of nodes such that replacing all of its directed edges with undirected edges produces a connected (undirected) graph, or all the components are connected by some path, ignoring direction. Graph Summary:Number of nodes : 115Number of edges : 613Maximum degree : 12Minimum degree : 7Average degree : 10.660869565217391Median degree : 11.0Graph ConnectivityConnected Components : 1... Distance between two nodes is the length of the shortest path between them. Path length is identified by the number of steps it contains from beginning to end to reach node y from x. Finding this distance, especially with large scale graphs, can be really computationally expensive. There are two algorithms that are at the core of graph theory here: Breadth-First Search (BFS): “discovers” nodes in layers based on connectivity. It starts at the root node and finds all nodes in the most immediate layer of connectivity before traversing the graph further. Depth-First Search (DFS): “visits” nodes by traversing the graph from the root node all the way to its first leaf node before going down a different route in the graph. When we want to aggregate this up to a graph level, there are two common ways to do so: Average Distance: average distance between every pair of nodes. This usually is restricted to largest component when network is unconnected.Diameter: max distance between any pair of nodes. Average Distance: average distance between every pair of nodes. This usually is restricted to largest component when network is unconnected. Diameter: max distance between any pair of nodes. They each should be used in pair with domain knowledge of the data you’re modeling as a graph. Graph Summary:Number of nodes : 115Number of edges : 613Maximum degree : 12Minimum degree : 7Average degree : 10.660869565217391Median degree : 11.0Graph ConnectivityConnected Components : 1Graph DistanceAverage Distance : 2.5081617086193746Diameter : 4... Clustering is an important assessment of networks to start decomposing and understanding their complexity. Triadic closure in a graph is the tendency for nodes who share edges to become connected. This is commonly done in social network graphs when person A is friends with person B and person B is friends with person C, so a recommendation to person A may be to befriend person C. This is founded is evidence that has shown in most real-world networks, mainly social networks, nodes tend to create tightly knit groups represented by a relatively high density of ties. A way to measure the tendency of clustering in a graph is the clustering coefficient. There are two common ways to measure the clustering coefficient: local and global. Local Clustering Coefficient: fraction of pairs of the node’s friends that are friends with each other. Formula: # of pairs of A’s friends who are friends / # of pairs of A’s friends Global Clustering Coefficient has two approaches: Average local clustering coefficient over all nodes in the graph.Transitivity: percentage of “open triads” that are triangles in a network. This weights nodes with large degree higher. Average local clustering coefficient over all nodes in the graph. Transitivity: percentage of “open triads” that are triangles in a network. This weights nodes with large degree higher. Graph Summary:Number of nodes : 115Number of edges : 613Maximum degree : 12Minimum degree : 7Average degree : 10.660869565217391Median degree : 11.0Graph ConnectivityConnected Components : 1Graph DistanceAverage Distance : 2.5081617086193746Diameter : 4Graph ClusteringTransitivity : 0.4072398190045249Average Clustering Coefficient : 0.40321601104209814 The degree of a node in an undirected graph is the number of neighbors it has. Degree distributions of a graph is the probability distribution of the degrees over the entire network. In Undirected graphs, it’s simply referred to as degree but for Directed graphs we get in-degree and out-degree distributions. In-Degree distributions represent the distribution of in-links each node in the graph has. It has been argued, in real-world networks (notably social networks), when we plot the degree/in-degree distributions on a log-log scale it represents a power-law distribution. It has been debated that these scale-free networks are actually quite rare when using statistically rigorous techniques, which others have argued are overly restrictive to measure against. In any case, assessing the degree distribution is important to understand your network but it does not give insight into how the network may evolve over time. Although we’re dealing with a very small and understandable network, these can easily scale up to uninterpretable complexity. When networks get that large it’s imperative to use centrality measures to guide us in understanding the data. Centrality is a way to think about importance of nodes/edges in a graph. Depending on your domain/data, you should use different assumptions and this will naturally lead you to assess different centrality measures. Some of the ways you can quantify “importance” in a network: amount of degree of connectivity, average proximity to other nodes, fraction of shortest paths that pass through node, etc. Some applications that centrality measures can be used for: finding influential nodes in a social network identifying nodes that disseminate information to many nodes or prevent epidemics hubs in a transportation network important pages on the web nodes that prevent the network from breaking up and many more! There are a ton of centrality you can use; I’ll cover a handful key ones here, but I highly recommend reading NetworkX documentation of Graph literature to find key metrics that fit your domain. For network visualizations, I’ll use nx-altair because it offers easy functionality for interaction and editing. Interaction can’t be seen in the images below, but if you run this code in your notebook you can add filters and hover pretty easily. Assumption: important nodes have many connections. This is the most basic measure of centrality: number of neighbors. It uses degree for Undirected networks and in-degree or out-degree for Directed networks. The degree centrality values are commonly normalized by dividing by the maximum possible degree in a simple graph n-1 where n is the number of nodes in G. Assumption: important nodes are close to other nodes. This is the reciprocal of the average shortest path distance to a node over all n-1 reachable nodes. If nodes are disconnected then you can either consider its closeness centrality based on only nodes that can reach it or you can consider only nodes that can reach it and normalize that value by the fraction of nodes it can reach. Assumption: important nodes are close to other nodes. Betweenness centrality of a node v is the sum of the fraction of all-pairs shortest paths that pass through v. The formula essentially looks at the number of shortest paths between nodes s and t that pass through node v and divides it by all number of shortest paths between s and t (and sums over all paths that don’t start or end with v). Betweenness centrality values will be larger in graphs with many nodes. To control for this, we divide centrality values by the number of pairs of nodes in the graph (excluding v). Complication for this metric arises when there’s multiple shortest paths in the network. Since computation of this can be very expensive, it can be common to calculate this metric for a sample of node pairs. This metric can also be used to find important edges as well. Assumption: important nodes are connected to central nodes. Eigenvector centrality computes the centrality for a node based on the centrality of its neighbors. It measures the influence of a node in a network. Relative scores are assigned to all nodes in the network based on the concept that connections to high-scoring nodes contribute more to the score of the node in question than equal connections to low-scoring nodes. A high eigenvector score means that a node is connected to many nodes who themselves have high scores. Assumption: important nodes are those with many in-links from other important nodes. Algorithm: Start on a random node.Assign all nodes a PageRank of 1/n.Choose an outgoing edge at random and follow it to the next node.Perform the Basic PageRank Update Rule: each node gives an equal share of its current PageRank to all the nodes it links to.The new PageRank of each node is the sum of all the PageRank it received from other nodes.Repeat k times. Start on a random node. Assign all nodes a PageRank of 1/n. Choose an outgoing edge at random and follow it to the next node. Perform the Basic PageRank Update Rule: each node gives an equal share of its current PageRank to all the nodes it links to. The new PageRank of each node is the sum of all the PageRank it received from other nodes. Repeat k times. This is the infamous Google’s PageRank algorithm. It measures the importance of webpages from the hyperlink network structure. It assigns a score of importance to each node depending on how many links it has coming in from other nodes. In large networks, scaled PageRank is preferred as it comes with a “dampening parameter” alpha. This is a probability that an outgoing edge will be chosen at random to follow to another node in the algorithm which is especially beneficial when there’s a closed loop of outgoing nodes in a network. Assumption: important nodes that have incoming edges from good hubs are good authorities, and nodes that have outgoing edges to good authorities are good hubs. Algorithm: Assign each node an authority and hub score of 1.Apply the Authority Update Rule: each node’s authority score is the sum of hub scores of each node that points to it.Apply the Hub Update Rule: each node’s hub score is the sum of the authority scores of each node that it points to.Normalize Authority and Hub scores of each node by the total score of each.Repeat k times. Assign each node an authority and hub score of 1. Apply the Authority Update Rule: each node’s authority score is the sum of hub scores of each node that points to it. Apply the Hub Update Rule: each node’s hub score is the sum of the authority scores of each node that it points to. Normalize Authority and Hub scores of each node by the total score of each. Repeat k times. The HITS algorithm starts with a root, or a set of highly relevant nodes (potential authorities). Then all nodes that link to a node in the root are potential hubs. The base is defined as root nodes and any node that links to a node in the root. All edges connecting nodes in the base set are considered, and this focuses on a specific subset of the network that is relevant to a particularly query. The fundamentals of graph machine learning are connections between entities. As graphs get immensely large, it’s imperative to use metrics and algorithms to understand and get graph features. Depending on your context as well, different metrics and algorithms will prove useful and, more importantly, meaningful to your use case. Furthermore, we can use these metrics as features in a supervised or unsupervised learning task but we have to be careful which we use because they can add as much noise as signal. Other than many more metrics and algorithms, the depths of Graph ML covers a wide array of supervised and unsupervised learning tasks. From naïve to advanced techniques, we can use graph structure and inference to go beyond structural data. In future sections I’ll cover these machine learning tasks (node, edge, and graph level) on real data. References [1] Football dataset (M. Girvan and M. E. J. Newman, Community structure in social and biological networks, Proc. Natl. Acad. Sci. USA 99, 7821–7826 (2002)) [2] Claudio Stamile, Aldo Marzullo, Enrico Deusebio, Graph Machine Learning [3] Mark Needham, Amy E. Hodler, Graph Algorithms [4] Estelle Scifo, Hands-On Graph Analytics with Neo4j
[ { "code": null, "e": 660, "s": 172, "text": "Graph-based methods are some of the most fascinating and powerful techniques in the Data Science world today. Even so, I believe we’re in the early stages of widespread adoption of these methods. In this series, I’ll provide an extensive walkthrough of Graph Machine Learning starting with an overview of metrics and algorithms. I’ll also provide implementation code via Python to keep things as applied as possible. Before we get started, let’s discuss the value of graph-based methods." }, { "code": null, "e": 793, "s": 660, "text": "Why Graphs?Network BasicsNetwork ConnectivityNetwork DistanceNetwork ClusteringNetwork Degree DistributionsNetwork CentralitySummary" }, { "code": null, "e": 805, "s": 793, "text": "Why Graphs?" }, { "code": null, "e": 820, "s": 805, "text": "Network Basics" }, { "code": null, "e": 841, "s": 820, "text": "Network Connectivity" }, { "code": null, "e": 858, "s": 841, "text": "Network Distance" }, { "code": null, "e": 877, "s": 858, "text": "Network Clustering" }, { "code": null, "e": 906, "s": 877, "text": "Network Degree Distributions" }, { "code": null, "e": 925, "s": 906, "text": "Network Centrality" }, { "code": null, "e": 933, "s": 925, "text": "Summary" }, { "code": null, "e": 1029, "s": 933, "text": "Graphs are a general language for describing and analyzing entities with relations/interactions" }, { "code": null, "e": 1258, "s": 1029, "text": "Graphs are prevalent all around us from computer networks to social networks to disease pathways. Networks are often referred to as graphs that occur naturally, but the line is quite blurred and they do get used interchangeably." }, { "code": null, "e": 1353, "s": 1258, "text": "Dr. Jure Leskovec, in his Machine Learning for Graphs course, outlines a few examples such as:" }, { "code": null, "e": 1383, "s": 1353, "text": "Graphs (as a representation):" }, { "code": null, "e": 1430, "s": 1383, "text": "Information/knowledge are organized and linked" }, { "code": null, "e": 1469, "s": 1430, "text": "Software can be represented as a graph" }, { "code": null, "e": 1518, "s": 1469, "text": "Similarity networks: Connect similar data points" }, { "code": null, "e": 1612, "s": 1518, "text": "Relational structures: Molecules, Scene graphs, 3D shapes, Particle-based physics simulations" }, { "code": null, "e": 1653, "s": 1612, "text": "Networks (also known as Natural Graphs):" }, { "code": null, "e": 1720, "s": 1653, "text": "Social networks: Society is a collection of 7+ billion individuals" }, { "code": null, "e": 1808, "s": 1720, "text": "Communication and transactions: Electronic devices, phone calls, financial transactions" }, { "code": null, "e": 1871, "s": 1808, "text": "Biomedicine: Interactions between genes/proteins regulate life" }, { "code": null, "e": 1961, "s": 1871, "text": "Brain connections: Our thoughts are hidden in the connections between billions of neurons" }, { "code": null, "e": 2674, "s": 1961, "text": "Representing data as a graph allows us to embed complex structural information as features. This yields higher performance in some domains as relational structure can provide a plethora of valuable information. In addition to a stronger feature representation, graph-based methods (specifically for Deep Learning) leverages representation learning to automatically learn features and represent them as an embedding. Due to this, a large amount of high dimensional information can be encoded in a sparse space without sacrificing speed/performance significantly. Another noteworthy benefit of leveraging graphs is the variety of tasks one can use them for. Dr. Leskovec provides insight into classic applications:" }, { "code": null, "e": 2764, "s": 2674, "text": "Node classification: Predict a property of a node. Example: Categorize online users/items" }, { "code": null, "e": 2897, "s": 2764, "text": "Link prediction: Predict whether there are missing links between two nodes. Example: Knowledge graph completion, recommender systems" }, { "code": null, "e": 2986, "s": 2897, "text": "Graph classification: Categorize different graphs. Example: Molecule property prediction" }, { "code": null, "e": 3065, "s": 2986, "text": "Clustering: Detect if nodes form a community. Example: Social circle detection" }, { "code": null, "e": 3098, "s": 3065, "text": "Graph generation: Drug discovery" }, { "code": null, "e": 3135, "s": 3098, "text": "Graph evolution: Physical simulation" }, { "code": null, "e": 3308, "s": 3135, "text": "I kept it brief here, but I highly recommend reviewing the slides from Dr. Leskovec’s first lecture if you’d like a deeper review of applications of Graph Machine Learning." }, { "code": null, "e": 3473, "s": 3308, "text": "Although we are able to embed high-dimensional data to achieve higher performance models for a variety of tasks, networks can be incredibly complex. This is due to:" }, { "code": null, "e": 3605, "s": 3473, "text": "Arbitrary size and complex topological structureNo fixed node ordering or reference pointOften dynamic and have multimodal features" }, { "code": null, "e": 3654, "s": 3605, "text": "Arbitrary size and complex topological structure" }, { "code": null, "e": 3696, "s": 3654, "text": "No fixed node ordering or reference point" }, { "code": null, "e": 3739, "s": 3696, "text": "Often dynamic and have multimodal features" }, { "code": null, "e": 4103, "s": 3739, "text": "We often need statistical analysis, models, and algorithms to assist our ability to understand and reason from networks. Network models assist to simulate dispersion and cascade of information through a network due to its inherent relational structure. This yields tremendous insight of how knowledge, information, etc. propagates instead of just what propagates." }, { "code": null, "e": 4524, "s": 4103, "text": "A network (or graph) is a representation of connections among a set of items. This representation is often written as G=(V,E) , where V={V1,...,Vn} is a set of nodes (also called vertices) and E={{Vk,Vw},..,{Vi,Vj}} is a set of two-sets (set of two elements) of edges (also called links), representing the connection between two nodes belonging to V. In a network visualization, distance and location carries no meaning." }, { "code": null, "e": 4596, "s": 4524, "text": "Networks can also take a series of different structures and attributes." }, { "code": null, "e": 4678, "s": 4596, "text": "Undirected: Have no direction, useful for cases where relationships are symmetric" }, { "code": null, "e": 4742, "s": 4678, "text": "Directed: Have direction, useful for asymmetrical relationships" }, { "code": null, "e": 4843, "s": 4742, "text": "Cyclic: Paths start and end at the same node, endless cycles may prevent termination without caution" }, { "code": null, "e": 4917, "s": 4843, "text": "Acyclic: Paths start and end at different nodes, basis of many algorithms" }, { "code": null, "e": 4983, "s": 4917, "text": "Weighted: Not all relationships are equal, some carry more weight" }, { "code": null, "e": 5084, "s": 4983, "text": "Unweighted: All relationships are equal (according to network) shown by equal/non-existent weighting" }, { "code": null, "e": 5157, "s": 5084, "text": "Sparse: Every node in the subset may not have a path to every other node" }, { "code": null, "e": 5220, "s": 5157, "text": "Dense: Every node in the subset has a path to every other node" }, { "code": null, "e": 5401, "s": 5220, "text": "Monopartite, bipartite, and k-partite: Whether nodes connect to only one other node type (e.g., users like movies) or many other node types (e.g., users like users who like movies)" }, { "code": null, "e": 5456, "s": 5401, "text": "Neo4J provides a great summary visualization for each:" }, { "code": null, "e": 5546, "s": 5456, "text": "Networks also have some basic properties that advanced methods and techniques build upon." }, { "code": null, "e": 5654, "s": 5546, "text": "The order of a graph is the number of its vertices |V|. The size of a graph is the number of its edges |E|." }, { "code": null, "e": 5830, "s": 5654, "text": "The degree of a vertex is the number of edges that are adjacent to it. The neighbors of a vertex v in a graph G is a subset of vertex Vi induced by all vertices adjacent to v." }, { "code": null, "e": 6017, "s": 5830, "text": "The neighborhood graph (also known as an ego graph) of a vertex v in a graph G is a subgraph of G, composed of the vertices adjacent to v and all edges connecting vertices adjacent to v." }, { "code": null, "e": 6566, "s": 6017, "text": "There are numerous datasets with a preloaded network structure available to do work on. This is due to the graciousness of the research and applied community sharing their work and datasets. To get started with our own network, we can load in one of these NetworkX’s datasets and as a sports fan I’ll choose the Football dataset (M. Girvan and M. E. J. Newman, Community structure in social and biological networks, Proc. Natl. Acad. Sci. USA 99, 7821–7826 (2002)). This dataset is open licensed by Girvan and Newman and shown on NetworkX Datasets." }, { "code": null, "e": 6718, "s": 6566, "text": "Graph Summary:Number of nodes : 115Number of edges : 613Maximum degree : 12Minimum degree : 7Average degree : 10.660869565217391Median degree : 11.0..." }, { "code": null, "e": 7007, "s": 6718, "text": "A connected graph is a graph where every pair of nodes has a path between them. In a graph, there can be multiple connected components; these are subsets of nodes such that: 1. every node in the subset has a path to every other node, 2. no other node has a path to any node in the subset." }, { "code": null, "e": 7201, "s": 7007, "text": "Strongly connected components are considered subsets of nodes that: 1. every node in the subset has a path to every other node, 2. no other node has a path to and from every node in the subset." }, { "code": null, "e": 7429, "s": 7201, "text": "Weakly connected components are subsets of nodes such that replacing all of its directed edges with undirected edges produces a connected (undirected) graph, or all the components are connected by some path, ignoring direction." }, { "code": null, "e": 7623, "s": 7429, "text": "Graph Summary:Number of nodes : 115Number of edges : 613Maximum degree : 12Minimum degree : 7Average degree : 10.660869565217391Median degree : 11.0Graph ConnectivityConnected Components : 1..." }, { "code": null, "e": 7806, "s": 7623, "text": "Distance between two nodes is the length of the shortest path between them. Path length is identified by the number of steps it contains from beginning to end to reach node y from x." }, { "code": null, "e": 7974, "s": 7806, "text": "Finding this distance, especially with large scale graphs, can be really computationally expensive. There are two algorithms that are at the core of graph theory here:" }, { "code": null, "e": 8181, "s": 7974, "text": "Breadth-First Search (BFS): “discovers” nodes in layers based on connectivity. It starts at the root node and finds all nodes in the most immediate layer of connectivity before traversing the graph further." }, { "code": null, "e": 8350, "s": 8181, "text": "Depth-First Search (DFS): “visits” nodes by traversing the graph from the root node all the way to its first leaf node before going down a different route in the graph." }, { "code": null, "e": 8438, "s": 8350, "text": "When we want to aggregate this up to a graph level, there are two common ways to do so:" }, { "code": null, "e": 8628, "s": 8438, "text": "Average Distance: average distance between every pair of nodes. This usually is restricted to largest component when network is unconnected.Diameter: max distance between any pair of nodes." }, { "code": null, "e": 8769, "s": 8628, "text": "Average Distance: average distance between every pair of nodes. This usually is restricted to largest component when network is unconnected." }, { "code": null, "e": 8819, "s": 8769, "text": "Diameter: max distance between any pair of nodes." }, { "code": null, "e": 8914, "s": 8819, "text": "They each should be used in pair with domain knowledge of the data you’re modeling as a graph." }, { "code": null, "e": 9171, "s": 8914, "text": "Graph Summary:Number of nodes : 115Number of edges : 613Maximum degree : 12Minimum degree : 7Average degree : 10.660869565217391Median degree : 11.0Graph ConnectivityConnected Components : 1Graph DistanceAverage Distance : 2.5081617086193746Diameter : 4..." }, { "code": null, "e": 9741, "s": 9171, "text": "Clustering is an important assessment of networks to start decomposing and understanding their complexity. Triadic closure in a graph is the tendency for nodes who share edges to become connected. This is commonly done in social network graphs when person A is friends with person B and person B is friends with person C, so a recommendation to person A may be to befriend person C. This is founded is evidence that has shown in most real-world networks, mainly social networks, nodes tend to create tightly knit groups represented by a relatively high density of ties." }, { "code": null, "e": 9910, "s": 9741, "text": "A way to measure the tendency of clustering in a graph is the clustering coefficient. There are two common ways to measure the clustering coefficient: local and global." }, { "code": null, "e": 10014, "s": 9910, "text": "Local Clustering Coefficient: fraction of pairs of the node’s friends that are friends with each other." }, { "code": null, "e": 10093, "s": 10014, "text": "Formula: # of pairs of A’s friends who are friends / # of pairs of A’s friends" }, { "code": null, "e": 10143, "s": 10093, "text": "Global Clustering Coefficient has two approaches:" }, { "code": null, "e": 10328, "s": 10143, "text": "Average local clustering coefficient over all nodes in the graph.Transitivity: percentage of “open triads” that are triangles in a network. This weights nodes with large degree higher." }, { "code": null, "e": 10394, "s": 10328, "text": "Average local clustering coefficient over all nodes in the graph." }, { "code": null, "e": 10514, "s": 10394, "text": "Transitivity: percentage of “open triads” that are triangles in a network. This weights nodes with large degree higher." }, { "code": null, "e": 10869, "s": 10514, "text": "Graph Summary:Number of nodes : 115Number of edges : 613Maximum degree : 12Minimum degree : 7Average degree : 10.660869565217391Median degree : 11.0Graph ConnectivityConnected Components : 1Graph DistanceAverage Distance : 2.5081617086193746Diameter : 4Graph ClusteringTransitivity : 0.4072398190045249Average Clustering Coefficient : 0.40321601104209814" }, { "code": null, "e": 11052, "s": 10869, "text": "The degree of a node in an undirected graph is the number of neighbors it has. Degree distributions of a graph is the probability distribution of the degrees over the entire network." }, { "code": null, "e": 11795, "s": 11052, "text": "In Undirected graphs, it’s simply referred to as degree but for Directed graphs we get in-degree and out-degree distributions. In-Degree distributions represent the distribution of in-links each node in the graph has. It has been argued, in real-world networks (notably social networks), when we plot the degree/in-degree distributions on a log-log scale it represents a power-law distribution. It has been debated that these scale-free networks are actually quite rare when using statistically rigorous techniques, which others have argued are overly restrictive to measure against. In any case, assessing the degree distribution is important to understand your network but it does not give insight into how the network may evolve over time." }, { "code": null, "e": 12032, "s": 11795, "text": "Although we’re dealing with a very small and understandable network, these can easily scale up to uninterpretable complexity. When networks get that large it’s imperative to use centrality measures to guide us in understanding the data." }, { "code": null, "e": 12432, "s": 12032, "text": "Centrality is a way to think about importance of nodes/edges in a graph. Depending on your domain/data, you should use different assumptions and this will naturally lead you to assess different centrality measures. Some of the ways you can quantify “importance” in a network: amount of degree of connectivity, average proximity to other nodes, fraction of shortest paths that pass through node, etc." }, { "code": null, "e": 12492, "s": 12432, "text": "Some applications that centrality measures can be used for:" }, { "code": null, "e": 12538, "s": 12492, "text": "finding influential nodes in a social network" }, { "code": null, "e": 12620, "s": 12538, "text": "identifying nodes that disseminate information to many nodes or prevent epidemics" }, { "code": null, "e": 12653, "s": 12620, "text": "hubs in a transportation network" }, { "code": null, "e": 12680, "s": 12653, "text": "important pages on the web" }, { "code": null, "e": 12728, "s": 12680, "text": "nodes that prevent the network from breaking up" }, { "code": null, "e": 12743, "s": 12728, "text": "and many more!" }, { "code": null, "e": 12938, "s": 12743, "text": "There are a ton of centrality you can use; I’ll cover a handful key ones here, but I highly recommend reading NetworkX documentation of Graph literature to find key metrics that fit your domain." }, { "code": null, "e": 13185, "s": 12938, "text": "For network visualizations, I’ll use nx-altair because it offers easy functionality for interaction and editing. Interaction can’t be seen in the images below, but if you run this code in your notebook you can add filters and hover pretty easily." }, { "code": null, "e": 13236, "s": 13185, "text": "Assumption: important nodes have many connections." }, { "code": null, "e": 13548, "s": 13236, "text": "This is the most basic measure of centrality: number of neighbors. It uses degree for Undirected networks and in-degree or out-degree for Directed networks. The degree centrality values are commonly normalized by dividing by the maximum possible degree in a simple graph n-1 where n is the number of nodes in G." }, { "code": null, "e": 13602, "s": 13548, "text": "Assumption: important nodes are close to other nodes." }, { "code": null, "e": 13934, "s": 13602, "text": "This is the reciprocal of the average shortest path distance to a node over all n-1 reachable nodes. If nodes are disconnected then you can either consider its closeness centrality based on only nodes that can reach it or you can consider only nodes that can reach it and normalize that value by the fraction of nodes it can reach." }, { "code": null, "e": 13988, "s": 13934, "text": "Assumption: important nodes are close to other nodes." }, { "code": null, "e": 14599, "s": 13988, "text": "Betweenness centrality of a node v is the sum of the fraction of all-pairs shortest paths that pass through v. The formula essentially looks at the number of shortest paths between nodes s and t that pass through node v and divides it by all number of shortest paths between s and t (and sums over all paths that don’t start or end with v). Betweenness centrality values will be larger in graphs with many nodes. To control for this, we divide centrality values by the number of pairs of nodes in the graph (excluding v). Complication for this metric arises when there’s multiple shortest paths in the network." }, { "code": null, "e": 14780, "s": 14599, "text": "Since computation of this can be very expensive, it can be common to calculate this metric for a sample of node pairs. This metric can also be used to find important edges as well." }, { "code": null, "e": 14840, "s": 14780, "text": "Assumption: important nodes are connected to central nodes." }, { "code": null, "e": 15308, "s": 14840, "text": "Eigenvector centrality computes the centrality for a node based on the centrality of its neighbors. It measures the influence of a node in a network. Relative scores are assigned to all nodes in the network based on the concept that connections to high-scoring nodes contribute more to the score of the node in question than equal connections to low-scoring nodes. A high eigenvector score means that a node is connected to many nodes who themselves have high scores." }, { "code": null, "e": 15393, "s": 15308, "text": "Assumption: important nodes are those with many in-links from other important nodes." }, { "code": null, "e": 15404, "s": 15393, "text": "Algorithm:" }, { "code": null, "e": 15757, "s": 15404, "text": "Start on a random node.Assign all nodes a PageRank of 1/n.Choose an outgoing edge at random and follow it to the next node.Perform the Basic PageRank Update Rule: each node gives an equal share of its current PageRank to all the nodes it links to.The new PageRank of each node is the sum of all the PageRank it received from other nodes.Repeat k times." }, { "code": null, "e": 15781, "s": 15757, "text": "Start on a random node." }, { "code": null, "e": 15817, "s": 15781, "text": "Assign all nodes a PageRank of 1/n." }, { "code": null, "e": 15883, "s": 15817, "text": "Choose an outgoing edge at random and follow it to the next node." }, { "code": null, "e": 16008, "s": 15883, "text": "Perform the Basic PageRank Update Rule: each node gives an equal share of its current PageRank to all the nodes it links to." }, { "code": null, "e": 16099, "s": 16008, "text": "The new PageRank of each node is the sum of all the PageRank it received from other nodes." }, { "code": null, "e": 16115, "s": 16099, "text": "Repeat k times." }, { "code": null, "e": 16649, "s": 16115, "text": "This is the infamous Google’s PageRank algorithm. It measures the importance of webpages from the hyperlink network structure. It assigns a score of importance to each node depending on how many links it has coming in from other nodes. In large networks, scaled PageRank is preferred as it comes with a “dampening parameter” alpha. This is a probability that an outgoing edge will be chosen at random to follow to another node in the algorithm which is especially beneficial when there’s a closed loop of outgoing nodes in a network." }, { "code": null, "e": 16809, "s": 16649, "text": "Assumption: important nodes that have incoming edges from good hubs are good authorities, and nodes that have outgoing edges to good authorities are good hubs." }, { "code": null, "e": 16820, "s": 16809, "text": "Algorithm:" }, { "code": null, "e": 17192, "s": 16820, "text": "Assign each node an authority and hub score of 1.Apply the Authority Update Rule: each node’s authority score is the sum of hub scores of each node that points to it.Apply the Hub Update Rule: each node’s hub score is the sum of the authority scores of each node that it points to.Normalize Authority and Hub scores of each node by the total score of each.Repeat k times." }, { "code": null, "e": 17242, "s": 17192, "text": "Assign each node an authority and hub score of 1." }, { "code": null, "e": 17360, "s": 17242, "text": "Apply the Authority Update Rule: each node’s authority score is the sum of hub scores of each node that points to it." }, { "code": null, "e": 17476, "s": 17360, "text": "Apply the Hub Update Rule: each node’s hub score is the sum of the authority scores of each node that it points to." }, { "code": null, "e": 17552, "s": 17476, "text": "Normalize Authority and Hub scores of each node by the total score of each." }, { "code": null, "e": 17568, "s": 17552, "text": "Repeat k times." }, { "code": null, "e": 17968, "s": 17568, "text": "The HITS algorithm starts with a root, or a set of highly relevant nodes (potential authorities). Then all nodes that link to a node in the root are potential hubs. The base is defined as root nodes and any node that links to a node in the root. All edges connecting nodes in the base set are considered, and this focuses on a specific subset of the network that is relevant to a particularly query." }, { "code": null, "e": 18298, "s": 17968, "text": "The fundamentals of graph machine learning are connections between entities. As graphs get immensely large, it’s imperative to use metrics and algorithms to understand and get graph features. Depending on your context as well, different metrics and algorithms will prove useful and, more importantly, meaningful to your use case." }, { "code": null, "e": 18479, "s": 18298, "text": "Furthermore, we can use these metrics as features in a supervised or unsupervised learning task but we have to be careful which we use because they can add as much noise as signal." }, { "code": null, "e": 18824, "s": 18479, "text": "Other than many more metrics and algorithms, the depths of Graph ML covers a wide array of supervised and unsupervised learning tasks. From naïve to advanced techniques, we can use graph structure and inference to go beyond structural data. In future sections I’ll cover these machine learning tasks (node, edge, and graph level) on real data." }, { "code": null, "e": 18835, "s": 18824, "text": "References" }, { "code": null, "e": 18992, "s": 18835, "text": "[1] Football dataset (M. Girvan and M. E. J. Newman, Community structure in social and biological networks, Proc. Natl. Acad. Sci. USA 99, 7821–7826 (2002))" }, { "code": null, "e": 19068, "s": 18992, "text": "[2] Claudio Stamile, Aldo Marzullo, Enrico Deusebio, Graph Machine Learning" }, { "code": null, "e": 19118, "s": 19068, "text": "[3] Mark Needham, Amy E. Hodler, Graph Algorithms" } ]
Distributed Neural Network Training In Pytorch | by Nilesh Vijayrania | Towards Data Science
With several advancements in Deep Learning, complex networks such as giant transformer networks, wider and deeper Resnets, etc. have evolved which keeps a larger memory footprint. More often than not, while training these networks, deep learning practitioners need to use multiple GPUs to train them efficiently. In this post, I am going to walk you through, how distributed neural network training could be set up over a GPU cluster using PyTorch. Usually, distributed training comes into the picture in two use-cases. Model Splitting across GPUs: When the model is so large that it cannot fit into a single GPU’s memory, you need to split parts of the model across different GPUs.Batch Splitting across GPUs.When the mini-batch is so large that it cannot fit into a single GPU’s memory, you need to split the mini-batch across different GPUs. Model Splitting across GPUs: When the model is so large that it cannot fit into a single GPU’s memory, you need to split parts of the model across different GPUs. Batch Splitting across GPUs.When the mini-batch is so large that it cannot fit into a single GPU’s memory, you need to split the mini-batch across different GPUs. Splitting the model across GPUs is straightforward and doesn’t require much code change. While setting up the network itself, parts of the model could be moved to specific GPUs. Afterwards while forward propagating the data through the network, the data needs to be moved to the corresponding GPU as well. Below is the PyTorch snippet doing the same. There are 3 ways to split batch across GPUs. Accumulating GradientsUsing nn.DataParallelUsing nn.DistributedDataParallel Accumulating Gradients Using nn.DataParallel Using nn.DistributedDataParallel The easiest way to split batches across GPUs is to accumulate gradients. Suppose, the batch size that we want to train with is 256, but only 32 batch size could fit into one GPU memory. We could perform 8(=256/32) gradient descend iterations without performing the optimization step and keep on adding the calculated gradients via loss.backward() step. Once we accumulate gradients of 256 data points, we perform the optimization step i.e. calling optimizer.step(). Below is the PyTorch snippet for implementing accumulating gradients. Pros: Doesn’t require multiple GPUs for large batch training. This method enables large batch training even with a single GPU. Cons: Takes significantly more time than training parallelly on multiple GPUs. If you have access to multiple GPUs, it would make sense to hand different batch splits to different GPUs, do gradient calculation on different GPUs, and then accumulate the gradients to perform gradient descend. Basically, the given input is split across the GPUs by chunking in the batch dimension. In the forward pass, the model is replicated on each device, and each replica handles a portion of the batch. During the backward pass, gradients from each replica are summed to produce the resultant gradient and applied on the master gpu(GPU-1 in the image above) to update the model weights. In the next iteration, this updated model on master GPU, is again replicated on each GPU device. In PyTorch, it takes one line to enable distributed training using nn.DataParallel. The model just needs to be wrapped in nn.DataParallel. model = torch.nn.DataParallel(model)......loss = ...loss.backward() Pros: Parallelizes NN training over multiple GPUs and hence it reduces the training time in comparison with accumulating gradients. Good for quick prototyping because the code change is minimal. Cons: nn.DataParallel uses a single process multi-threading method to train the same model on different GPUs. It keeps the main process on one GPU and runs a different thread on other GPUs. Since multi-threading in python suffers from GIL(Global Interpreter Lock) issues, this restricts fully parallelized distributed training setup. Unlike nn.DataParallel, DistributedDataParallel uses multi-processing to spawn separate processes on separate GPUs and leverage the full parallelism across GPUs. But setting up DistributedDataParallel pipeline is more complex than nn.DataParallel and requires the following steps(but not necessarily in this order). Wrap the model in torch.nn.Parallel.DistributedDataParallel .Setup the Dataloader to use distributedSampler to distribute samples efficiently across all GPUs. Pytorch provides torch.utils.data.Distributed.DistributedSampler for it.Setup the distributed backend to manage the synchronization of GPUs. torch.distributed.init_process_group(backend='nccl'). There are different backends(nccl, gloo, mpi, tcp) provided by pytorch for distributed training. As a rule of thumb, use nccl for distributed training over GPUs and gloo for distributed training over CPUs. Read more about them here https://pytorch.org/tutorials/intermediate/dist_tuto.html#advanced-topicsLaunch the separate processes on each GPU. use torch.distributed.launch utility function for the same. Suppose we have 4 GPUs on the cluster node over which we would like to use for setting up distributed training. Following shell command could be used to do that. Wrap the model in torch.nn.Parallel.DistributedDataParallel . Setup the Dataloader to use distributedSampler to distribute samples efficiently across all GPUs. Pytorch provides torch.utils.data.Distributed.DistributedSampler for it. Setup the distributed backend to manage the synchronization of GPUs. torch.distributed.init_process_group(backend='nccl'). There are different backends(nccl, gloo, mpi, tcp) provided by pytorch for distributed training. As a rule of thumb, use nccl for distributed training over GPUs and gloo for distributed training over CPUs. Read more about them here https://pytorch.org/tutorials/intermediate/dist_tuto.html#advanced-topics Launch the separate processes on each GPU. use torch.distributed.launch utility function for the same. Suppose we have 4 GPUs on the cluster node over which we would like to use for setting up distributed training. Following shell command could be used to do that. python -m torch.distributed.launch --nproc_per_node=4 --nnodes=1 --node_rank=0--master_port=1234 train.py <OTHER TRAINING ARGS> While setting up the launch script, we have to provide a free port(1234 in this case) over the node where the master process would be running and used to communicate with other GPUs. Below is the complete PyTorch gist covering all the steps. Notice that the above-mentioned utility call(last commented line in the above gist) is for a single node over a GPU cluster. In case you want to use a multi-node setup, additionally, you have to choose a node as the master node and provide the master_addr argument while setting up the launch utility as follows. Suppose we have 2 nodes with 4 GPU each and the first node with the ip address “192.168.1.1” is the master node. We have to start the launch script on each node separately as follows. On first node, run python -m torch.distributed.launch --nproc_per_node=4 --nnodes=1 --node_rank=0--master_addr="192.168.1.1" --master_port=1234 train.py <OTHER TRAINING ARGS> On second node, run python -m torch.distributed.launch --nproc_per_node=4 --nnodes=1 --node_rank=1--master_addr="192.168.1.1" --master_port=1234 train.py <OTHER TRAINING ARGS> Other Utility Functions: While evaluating the model or generating the logs, it is required to collect current batch statistics such as losses, accuracy, etc. from all GPUs and collate them at one machine to log. Following methods are provided by PyTorch for syncing variables across all the GPUs. torch.distributed.gather(input_tensor, gather_list, dst) : Collect the specified input_tensor from all devices and place them on the dst device in gather_list. torch.distributed.all_gather(tensor_list, input_tensor) : Collect the specified input_tensor from all devices and place them in tensor_list variable on all devices. torch.distributed.reduce(input_tensor, dst, reduce_op=ReduceOp.SUM): Collect the input_tensor from all devices and reduce them using the specified reduce operation such as sum, mean, etc. The final result is placed on the dst device. torch.distributed.all_reduce(input_tensor, reduce_op=ReduceOp.SUM) : Same as reduce operation but the final result is copied to all devices. For more details about parameters and methods, read the torch.distributed package. https://pytorch.org/docs/stable/distributed.html As an example, the below code takes the loss values from all GPUs and reduces them to the master device(cuda:0). #In continuation with distributedDataParallel.py abovedef get_reduced_loss(loss, dest_device): loss_tensor = loss.clone() torch.distributed.reduce(loss_tensor, dst=dest_device) return loss_tensorif args.local_rank==0: loss_tensor = get_reduced_loss(loss.detach(), 0) print(f'Current batch Loss = {loss_tensor.item()}' Pros: The same code setup could be used for a single GPU without any code change. A single GPU setting would require only the launch script with the appropriate setting. cons: Layers such as BatchNorm which uses whole batch statistics in their computations, can’t carry out the operation independently on each GPU using only a split of the batch. PyTorch provides SyncBatchNorm as a replacement/wrapper module for BatchNorm which calculates the batch statistics using the whole batch divided across GPUs. See the sample code below for usage of SyncBatchNorm . network = .... #some network with BatchNorm layers in itsync_bn_network = nn.SyncBatchNorm.convert_sync_batchnorm(network)ddp_network = nn.parallel.DistributedDataParallel( sync_bn_network, device_ids=[args.local_rank], output_device=args.local_rank) For splitting the model across GPUs, split the model into sub_modules and push each sub_module to separate GPU. For splitting the batch across GPUs, use either of accumulating gradients, nn.DataParallel or nn.DistributedDataParallel. For quick prototyping, nn.DataParallel could be preferred. For training a large model and to leverage full parallel training across multiple GPUs, nn.DistributedDataParallel should be used. While using nn.DistributedDataParallel, replace, or wrap nn.BatchNorm layer with nn.SyncBatchNorm. Below is the list of references used for writing this post.
[ { "code": null, "e": 621, "s": 172, "text": "With several advancements in Deep Learning, complex networks such as giant transformer networks, wider and deeper Resnets, etc. have evolved which keeps a larger memory footprint. More often than not, while training these networks, deep learning practitioners need to use multiple GPUs to train them efficiently. In this post, I am going to walk you through, how distributed neural network training could be set up over a GPU cluster using PyTorch." }, { "code": null, "e": 692, "s": 621, "text": "Usually, distributed training comes into the picture in two use-cases." }, { "code": null, "e": 1017, "s": 692, "text": "Model Splitting across GPUs: When the model is so large that it cannot fit into a single GPU’s memory, you need to split parts of the model across different GPUs.Batch Splitting across GPUs.When the mini-batch is so large that it cannot fit into a single GPU’s memory, you need to split the mini-batch across different GPUs." }, { "code": null, "e": 1180, "s": 1017, "text": "Model Splitting across GPUs: When the model is so large that it cannot fit into a single GPU’s memory, you need to split parts of the model across different GPUs." }, { "code": null, "e": 1343, "s": 1180, "text": "Batch Splitting across GPUs.When the mini-batch is so large that it cannot fit into a single GPU’s memory, you need to split the mini-batch across different GPUs." }, { "code": null, "e": 1694, "s": 1343, "text": "Splitting the model across GPUs is straightforward and doesn’t require much code change. While setting up the network itself, parts of the model could be moved to specific GPUs. Afterwards while forward propagating the data through the network, the data needs to be moved to the corresponding GPU as well. Below is the PyTorch snippet doing the same." }, { "code": null, "e": 1739, "s": 1694, "text": "There are 3 ways to split batch across GPUs." }, { "code": null, "e": 1815, "s": 1739, "text": "Accumulating GradientsUsing nn.DataParallelUsing nn.DistributedDataParallel" }, { "code": null, "e": 1838, "s": 1815, "text": "Accumulating Gradients" }, { "code": null, "e": 1860, "s": 1838, "text": "Using nn.DataParallel" }, { "code": null, "e": 1893, "s": 1860, "text": "Using nn.DistributedDataParallel" }, { "code": null, "e": 2429, "s": 1893, "text": "The easiest way to split batches across GPUs is to accumulate gradients. Suppose, the batch size that we want to train with is 256, but only 32 batch size could fit into one GPU memory. We could perform 8(=256/32) gradient descend iterations without performing the optimization step and keep on adding the calculated gradients via loss.backward() step. Once we accumulate gradients of 256 data points, we perform the optimization step i.e. calling optimizer.step(). Below is the PyTorch snippet for implementing accumulating gradients." }, { "code": null, "e": 2435, "s": 2429, "text": "Pros:" }, { "code": null, "e": 2556, "s": 2435, "text": "Doesn’t require multiple GPUs for large batch training. This method enables large batch training even with a single GPU." }, { "code": null, "e": 2562, "s": 2556, "text": "Cons:" }, { "code": null, "e": 2635, "s": 2562, "text": "Takes significantly more time than training parallelly on multiple GPUs." }, { "code": null, "e": 2848, "s": 2635, "text": "If you have access to multiple GPUs, it would make sense to hand different batch splits to different GPUs, do gradient calculation on different GPUs, and then accumulate the gradients to perform gradient descend." }, { "code": null, "e": 3327, "s": 2848, "text": "Basically, the given input is split across the GPUs by chunking in the batch dimension. In the forward pass, the model is replicated on each device, and each replica handles a portion of the batch. During the backward pass, gradients from each replica are summed to produce the resultant gradient and applied on the master gpu(GPU-1 in the image above) to update the model weights. In the next iteration, this updated model on master GPU, is again replicated on each GPU device." }, { "code": null, "e": 3466, "s": 3327, "text": "In PyTorch, it takes one line to enable distributed training using nn.DataParallel. The model just needs to be wrapped in nn.DataParallel." }, { "code": null, "e": 3534, "s": 3466, "text": "model = torch.nn.DataParallel(model)......loss = ...loss.backward()" }, { "code": null, "e": 3540, "s": 3534, "text": "Pros:" }, { "code": null, "e": 3666, "s": 3540, "text": "Parallelizes NN training over multiple GPUs and hence it reduces the training time in comparison with accumulating gradients." }, { "code": null, "e": 3729, "s": 3666, "text": "Good for quick prototyping because the code change is minimal." }, { "code": null, "e": 3735, "s": 3729, "text": "Cons:" }, { "code": null, "e": 4063, "s": 3735, "text": "nn.DataParallel uses a single process multi-threading method to train the same model on different GPUs. It keeps the main process on one GPU and runs a different thread on other GPUs. Since multi-threading in python suffers from GIL(Global Interpreter Lock) issues, this restricts fully parallelized distributed training setup." }, { "code": null, "e": 4379, "s": 4063, "text": "Unlike nn.DataParallel, DistributedDataParallel uses multi-processing to spawn separate processes on separate GPUs and leverage the full parallelism across GPUs. But setting up DistributedDataParallel pipeline is more complex than nn.DataParallel and requires the following steps(but not necessarily in this order)." }, { "code": null, "e": 5303, "s": 4379, "text": "Wrap the model in torch.nn.Parallel.DistributedDataParallel .Setup the Dataloader to use distributedSampler to distribute samples efficiently across all GPUs. Pytorch provides torch.utils.data.Distributed.DistributedSampler for it.Setup the distributed backend to manage the synchronization of GPUs. torch.distributed.init_process_group(backend='nccl'). There are different backends(nccl, gloo, mpi, tcp) provided by pytorch for distributed training. As a rule of thumb, use nccl for distributed training over GPUs and gloo for distributed training over CPUs. Read more about them here https://pytorch.org/tutorials/intermediate/dist_tuto.html#advanced-topicsLaunch the separate processes on each GPU. use torch.distributed.launch utility function for the same. Suppose we have 4 GPUs on the cluster node over which we would like to use for setting up distributed training. Following shell command could be used to do that." }, { "code": null, "e": 5365, "s": 5303, "text": "Wrap the model in torch.nn.Parallel.DistributedDataParallel ." }, { "code": null, "e": 5536, "s": 5365, "text": "Setup the Dataloader to use distributedSampler to distribute samples efficiently across all GPUs. Pytorch provides torch.utils.data.Distributed.DistributedSampler for it." }, { "code": null, "e": 5965, "s": 5536, "text": "Setup the distributed backend to manage the synchronization of GPUs. torch.distributed.init_process_group(backend='nccl'). There are different backends(nccl, gloo, mpi, tcp) provided by pytorch for distributed training. As a rule of thumb, use nccl for distributed training over GPUs and gloo for distributed training over CPUs. Read more about them here https://pytorch.org/tutorials/intermediate/dist_tuto.html#advanced-topics" }, { "code": null, "e": 6230, "s": 5965, "text": "Launch the separate processes on each GPU. use torch.distributed.launch utility function for the same. Suppose we have 4 GPUs on the cluster node over which we would like to use for setting up distributed training. Following shell command could be used to do that." }, { "code": null, "e": 6358, "s": 6230, "text": "python -m torch.distributed.launch --nproc_per_node=4 --nnodes=1 --node_rank=0--master_port=1234 train.py <OTHER TRAINING ARGS>" }, { "code": null, "e": 6541, "s": 6358, "text": "While setting up the launch script, we have to provide a free port(1234 in this case) over the node where the master process would be running and used to communicate with other GPUs." }, { "code": null, "e": 6600, "s": 6541, "text": "Below is the complete PyTorch gist covering all the steps." }, { "code": null, "e": 7097, "s": 6600, "text": "Notice that the above-mentioned utility call(last commented line in the above gist) is for a single node over a GPU cluster. In case you want to use a multi-node setup, additionally, you have to choose a node as the master node and provide the master_addr argument while setting up the launch utility as follows. Suppose we have 2 nodes with 4 GPU each and the first node with the ip address “192.168.1.1” is the master node. We have to start the launch script on each node separately as follows." }, { "code": null, "e": 7116, "s": 7097, "text": "On first node, run" }, { "code": null, "e": 7272, "s": 7116, "text": "python -m torch.distributed.launch --nproc_per_node=4 --nnodes=1 --node_rank=0--master_addr=\"192.168.1.1\" --master_port=1234 train.py <OTHER TRAINING ARGS>" }, { "code": null, "e": 7292, "s": 7272, "text": "On second node, run" }, { "code": null, "e": 7448, "s": 7292, "text": "python -m torch.distributed.launch --nproc_per_node=4 --nnodes=1 --node_rank=1--master_addr=\"192.168.1.1\" --master_port=1234 train.py <OTHER TRAINING ARGS>" }, { "code": null, "e": 7473, "s": 7448, "text": "Other Utility Functions:" }, { "code": null, "e": 7745, "s": 7473, "text": "While evaluating the model or generating the logs, it is required to collect current batch statistics such as losses, accuracy, etc. from all GPUs and collate them at one machine to log. Following methods are provided by PyTorch for syncing variables across all the GPUs." }, { "code": null, "e": 7905, "s": 7745, "text": "torch.distributed.gather(input_tensor, gather_list, dst) : Collect the specified input_tensor from all devices and place them on the dst device in gather_list." }, { "code": null, "e": 8070, "s": 7905, "text": "torch.distributed.all_gather(tensor_list, input_tensor) : Collect the specified input_tensor from all devices and place them in tensor_list variable on all devices." }, { "code": null, "e": 8304, "s": 8070, "text": "torch.distributed.reduce(input_tensor, dst, reduce_op=ReduceOp.SUM): Collect the input_tensor from all devices and reduce them using the specified reduce operation such as sum, mean, etc. The final result is placed on the dst device." }, { "code": null, "e": 8445, "s": 8304, "text": "torch.distributed.all_reduce(input_tensor, reduce_op=ReduceOp.SUM) : Same as reduce operation but the final result is copied to all devices." }, { "code": null, "e": 8577, "s": 8445, "text": "For more details about parameters and methods, read the torch.distributed package. https://pytorch.org/docs/stable/distributed.html" }, { "code": null, "e": 8690, "s": 8577, "text": "As an example, the below code takes the loss values from all GPUs and reduces them to the master device(cuda:0)." }, { "code": null, "e": 9013, "s": 8690, "text": "#In continuation with distributedDataParallel.py abovedef get_reduced_loss(loss, dest_device): loss_tensor = loss.clone() torch.distributed.reduce(loss_tensor, dst=dest_device) return loss_tensorif args.local_rank==0: loss_tensor = get_reduced_loss(loss.detach(), 0) print(f'Current batch Loss = {loss_tensor.item()}'" }, { "code": null, "e": 9019, "s": 9013, "text": "Pros:" }, { "code": null, "e": 9183, "s": 9019, "text": "The same code setup could be used for a single GPU without any code change. A single GPU setting would require only the launch script with the appropriate setting." }, { "code": null, "e": 9189, "s": 9183, "text": "cons:" }, { "code": null, "e": 9573, "s": 9189, "text": "Layers such as BatchNorm which uses whole batch statistics in their computations, can’t carry out the operation independently on each GPU using only a split of the batch. PyTorch provides SyncBatchNorm as a replacement/wrapper module for BatchNorm which calculates the batch statistics using the whole batch divided across GPUs. See the sample code below for usage of SyncBatchNorm ." }, { "code": null, "e": 9903, "s": 9573, "text": "network = .... #some network with BatchNorm layers in itsync_bn_network = nn.SyncBatchNorm.convert_sync_batchnorm(network)ddp_network = nn.parallel.DistributedDataParallel( sync_bn_network, device_ids=[args.local_rank], output_device=args.local_rank)" }, { "code": null, "e": 10015, "s": 9903, "text": "For splitting the model across GPUs, split the model into sub_modules and push each sub_module to separate GPU." }, { "code": null, "e": 10137, "s": 10015, "text": "For splitting the batch across GPUs, use either of accumulating gradients, nn.DataParallel or nn.DistributedDataParallel." }, { "code": null, "e": 10196, "s": 10137, "text": "For quick prototyping, nn.DataParallel could be preferred." }, { "code": null, "e": 10327, "s": 10196, "text": "For training a large model and to leverage full parallel training across multiple GPUs, nn.DistributedDataParallel should be used." }, { "code": null, "e": 10426, "s": 10327, "text": "While using nn.DistributedDataParallel, replace, or wrap nn.BatchNorm layer with nn.SyncBatchNorm." } ]
Guava - IntMath Class
IntMath provides utility methods on int. Following is the declaration for com.google.common.math.IntMath class − @GwtCompatible(emulated = true) public final class IntMath extends Object static int binomial(int n, int k) Returns n choose k, also known as the binomial coefficient of n and k, or Integer.MAX_VALUE if the result does not fit in an int. static int checkedAdd(int a, int b) Returns the sum of a and b, provided it does not overflow. static int checkedMultiply(int a, int b) Returns the product of a and b, provided it does not overflow. static int checkedPow(int b, int k) Returns the b to the kth power, provided it does not overflow. static int checkedSubtract(int a, int b) Returns the difference of a and b, provided it does not overflow. static int divide(int p, int q, RoundingMode mode) Returns the result of dividing p by q, rounding using the specified RoundingMode. static int factorial(int n) Returns n!, that is, the product of the first n positive integers, 1 if n == 0, or Integer.MAX_VALUE if the result does not fit in a int. static int gcd(int a, int b) Returns the greatest common divisor of a, b. static boolean isPowerOfTwo(int x) Returns true if x represents a power of two. static int log10(int x, RoundingMode mode) Returns the base-10 logarithm of x, rounded according to the specified rounding mode. static int log2(int x, RoundingMode mode) Returns the base-2 logarithm of x, rounded according to the specified rounding mode. static int mean(int x, int y) Returns the arithmetic mean of x and y, rounded towards negative infinity. static int mod(int x, int m) Returns x mod m, a non-negative value less than m. static int pow(int b, int k) Returns b to the kth power. static int sqrt(int x, RoundingMode mode) Returns the square root of x, rounded with the specified rounding mode. This class inherits methods from the following class − java.lang.Object Create the following java program using any editor of your choice in say C:/> Guava. import java.math.RoundingMode; import com.google.common.math.IntMath; public class GuavaTester { public static void main(String args[]) { GuavaTester tester = new GuavaTester(); tester.testIntMath(); } private void testIntMath() { try { System.out.println(IntMath.checkedAdd(Integer.MAX_VALUE, Integer.MAX_VALUE)); } catch(ArithmeticException e) { System.out.println("Error: " + e.getMessage()); } System.out.println(IntMath.divide(100, 5, RoundingMode.UNNECESSARY)); try { //exception will be thrown as 100 is not completely divisible by 3 // thus rounding is required, and RoundingMode is set as UNNESSARY System.out.println(IntMath.divide(100, 3, RoundingMode.UNNECESSARY)); } catch(ArithmeticException e) { System.out.println("Error: " + e.getMessage()); } System.out.println("Log2(2): " + IntMath.log2(2, RoundingMode.HALF_EVEN)); System.out.println("Log10(10): " + IntMath.log10(10, RoundingMode.HALF_EVEN)); System.out.println("sqrt(100): " + IntMath.sqrt(IntMath.pow(10,2), RoundingMode.HALF_EVEN)); System.out.println("gcd(100,50): " + IntMath.gcd(100,50)); System.out.println("modulus(100,50): " + IntMath.mod(100,50)); System.out.println("factorial(5): " + IntMath.factorial(5)); } } Compile the class using javac compiler as follows − C:\Guava>javac GuavaTester.java Now run the GuavaTester to see the result. C:\Guava>java GuavaTester See the result. Error: overflow 20 Error: mode was UNNECESSARY, but rounding was necessary Log2(2): 1 Log10(10): 1 sqrt(100): 10 gcd(100,50): 50 modulus(100,50): 0 factorial(5): 120 Print Add Notes Bookmark this page
[ { "code": null, "e": 1926, "s": 1885, "text": "IntMath provides utility methods on int." }, { "code": null, "e": 1998, "s": 1926, "text": "Following is the declaration for com.google.common.math.IntMath class −" }, { "code": null, "e": 2075, "s": 1998, "text": "@GwtCompatible(emulated = true)\npublic final class IntMath\n extends Object" }, { "code": null, "e": 2109, "s": 2075, "text": "static int binomial(int n, int k)" }, { "code": null, "e": 2239, "s": 2109, "text": "Returns n choose k, also known as the binomial coefficient of n and k, or Integer.MAX_VALUE if the result does not fit in an int." }, { "code": null, "e": 2275, "s": 2239, "text": "static int checkedAdd(int a, int b)" }, { "code": null, "e": 2334, "s": 2275, "text": "Returns the sum of a and b, provided it does not overflow." }, { "code": null, "e": 2375, "s": 2334, "text": "static int checkedMultiply(int a, int b)" }, { "code": null, "e": 2438, "s": 2375, "text": "Returns the product of a and b, provided it does not overflow." }, { "code": null, "e": 2474, "s": 2438, "text": "static int checkedPow(int b, int k)" }, { "code": null, "e": 2537, "s": 2474, "text": "Returns the b to the kth power, provided it does not overflow." }, { "code": null, "e": 2578, "s": 2537, "text": "static int checkedSubtract(int a, int b)" }, { "code": null, "e": 2644, "s": 2578, "text": "Returns the difference of a and b, provided it does not overflow." }, { "code": null, "e": 2695, "s": 2644, "text": "static int divide(int p, int q, RoundingMode mode)" }, { "code": null, "e": 2777, "s": 2695, "text": "Returns the result of dividing p by q, rounding using the specified RoundingMode." }, { "code": null, "e": 2805, "s": 2777, "text": "static int factorial(int n)" }, { "code": null, "e": 2943, "s": 2805, "text": "Returns n!, that is, the product of the first n positive integers, 1 if n == 0, or Integer.MAX_VALUE if the result does not fit in a int." }, { "code": null, "e": 2972, "s": 2943, "text": "static int gcd(int a, int b)" }, { "code": null, "e": 3017, "s": 2972, "text": "Returns the greatest common divisor of a, b." }, { "code": null, "e": 3052, "s": 3017, "text": "static boolean isPowerOfTwo(int x)" }, { "code": null, "e": 3097, "s": 3052, "text": "Returns true if x represents a power of two." }, { "code": null, "e": 3140, "s": 3097, "text": "static int log10(int x, RoundingMode mode)" }, { "code": null, "e": 3226, "s": 3140, "text": "Returns the base-10 logarithm of x, rounded according to the specified rounding mode." }, { "code": null, "e": 3268, "s": 3226, "text": "static int log2(int x, RoundingMode mode)" }, { "code": null, "e": 3353, "s": 3268, "text": "Returns the base-2 logarithm of x, rounded according to the specified rounding mode." }, { "code": null, "e": 3383, "s": 3353, "text": "static int mean(int x, int y)" }, { "code": null, "e": 3458, "s": 3383, "text": "Returns the arithmetic mean of x and y, rounded towards negative infinity." }, { "code": null, "e": 3487, "s": 3458, "text": "static int mod(int x, int m)" }, { "code": null, "e": 3538, "s": 3487, "text": "Returns x mod m, a non-negative value less than m." }, { "code": null, "e": 3567, "s": 3538, "text": "static int pow(int b, int k)" }, { "code": null, "e": 3595, "s": 3567, "text": "Returns b to the kth power." }, { "code": null, "e": 3637, "s": 3595, "text": "static int sqrt(int x, RoundingMode mode)" }, { "code": null, "e": 3709, "s": 3637, "text": "Returns the square root of x, rounded with the specified rounding mode." }, { "code": null, "e": 3764, "s": 3709, "text": "This class inherits methods from the following class −" }, { "code": null, "e": 3781, "s": 3764, "text": "java.lang.Object" }, { "code": null, "e": 3866, "s": 3781, "text": "Create the following java program using any editor of your choice in say C:/> Guava." }, { "code": null, "e": 5247, "s": 3866, "text": "import java.math.RoundingMode;\nimport com.google.common.math.IntMath;\n\npublic class GuavaTester {\n\n public static void main(String args[]) {\n GuavaTester tester = new GuavaTester();\n tester.testIntMath();\n }\n\n private void testIntMath() {\n try {\n System.out.println(IntMath.checkedAdd(Integer.MAX_VALUE, Integer.MAX_VALUE));\n \n } catch(ArithmeticException e) {\n System.out.println(\"Error: \" + e.getMessage());\n }\n\n System.out.println(IntMath.divide(100, 5, RoundingMode.UNNECESSARY));\n try {\n //exception will be thrown as 100 is not completely divisible by 3\n // thus rounding is required, and RoundingMode is set as UNNESSARY\n System.out.println(IntMath.divide(100, 3, RoundingMode.UNNECESSARY));\n \n } catch(ArithmeticException e) {\n System.out.println(\"Error: \" + e.getMessage());\n }\n\n System.out.println(\"Log2(2): \" + IntMath.log2(2, RoundingMode.HALF_EVEN));\n\n System.out.println(\"Log10(10): \" + IntMath.log10(10, RoundingMode.HALF_EVEN));\n\n System.out.println(\"sqrt(100): \" + IntMath.sqrt(IntMath.pow(10,2), RoundingMode.HALF_EVEN));\n\n System.out.println(\"gcd(100,50): \" + IntMath.gcd(100,50));\n\n System.out.println(\"modulus(100,50): \" + IntMath.mod(100,50));\n\n System.out.println(\"factorial(5): \" + IntMath.factorial(5));\n }\n}" }, { "code": null, "e": 5299, "s": 5247, "text": "Compile the class using javac compiler as follows −" }, { "code": null, "e": 5332, "s": 5299, "text": "C:\\Guava>javac GuavaTester.java\n" }, { "code": null, "e": 5375, "s": 5332, "text": "Now run the GuavaTester to see the result." }, { "code": null, "e": 5402, "s": 5375, "text": "C:\\Guava>java GuavaTester\n" }, { "code": null, "e": 5418, "s": 5402, "text": "See the result." }, { "code": null, "e": 5585, "s": 5418, "text": "Error: overflow\n20\nError: mode was UNNECESSARY, but rounding was necessary\nLog2(2): 1\nLog10(10): 1\nsqrt(100): 10\ngcd(100,50): 50\nmodulus(100,50): 0\nfactorial(5): 120\n" }, { "code": null, "e": 5592, "s": 5585, "text": " Print" }, { "code": null, "e": 5603, "s": 5592, "text": " Add Notes" } ]
Importance of Understanding the Complexity of a Machine Learning Algorithm | by Baran Köseoğlu | Towards Data Science
Machine learning engineers often find themselves in situations to choose the right algorithm for the problem at hand. It is often the case that they first understand the structure of the problem they provide a solution to. They then explore the dataset at hand. After initial observations and key takeaways, they finally choose the right algorithm for the task. Deciding on the best algorithm to apply to the dataset at hand may seem a trivial job. Engineers often create shortcuts in these situations. If the task has 0–1 label, just apply logistic regression, right? Wrong! We should be aware of these shortcuts and always remind ourselves that although certain algorithms work good with specific problems, there is no “recipe” when selecting the best algorithm for the problem. However, complexity and runtime analysis of an algorithm should always be discussed and taken into account. Runtime analysis of an algorithm is not only crucial to comprehend the inner workings of the algorithm but it also yields a more successful implementation. In the rest of the article, I am going to depict a situation, where omitting to think about runtime analysis of an algorithm, k means clustering in this case, can cause an engineer to lose lots of time and energy. K-means clustering is one of the most popular and easy-to-implement unsupervised machine learning algorithms. It is also one of the easy-to-comprehend machine learning algorithms. Typically, unsupervised machine learning algorithms make inferences from the input dataset using only the feature vectors. Therefore these algorithms are good for datasets having no label data. They can also be quite useful when one wants to extract value or insight from large quantities of structured and unstructured data. K-means clustering is one of these exploratory data analysis techniques, where the goal is to extract subgroups of data points such that the data points in the same cluster are very similar in terms of the features defined. K-means clustering starts with the first group of randomly selected data points, which are used as the initial seed of the centroids. The algorithm then performs iterative calculations to assign the rest of the data points to the closest cluster. While performing these calculations according to the distance function defined, the positions of the centroids are updated. It halts the optimizing the center of the clusters when either: The positions of the centroids are stabilized, i.e the change in their values does not exceed a predefined threshold. The algorithm surpassed a maximum number of iterations. Therefore, the complexity of the algorithm is O(n * K * I * d)n : number of pointsK : number of clustersI : number of iterationsd : number of attributes I am going to share code snippets for a k-means clustering task. My only purpose is to demonstrate an example, where failing to comprehend runtime complexity results in a poor evaluation of the algorithm. The steps I took are not optimized for the algorithm, i.e you can preprocess the data better and get finer clusters. Outline of the steps involved is as follows: Import libraries, and read dataset. Here I import relevant libraries and read the dataset, which I already downloaded to a local folder.Preprocessing. In this step, I discard the columns of string type and only focus on numeric features. Since k-means clustering calculates the distance between data points, it works with numeric columns.Applying PCA to reduce dimension. It is usually good practice to reduce the dimension of the dataset before applying k-means clustering, as in high dimensional spaces, distance measures do not work very well.Calculating silhouette score. K-means clustering not applied directly. It involves the problem of finding an optimal number of clusters. Silhouette score is one of the techniques you can use to determine an optimal number of clusters. Failing to understand the complexity of the calculations involved in silhouette score analysis will yield poor implementation.Alternative solutions. Here I list some of the alternative solutions to find an optimal number of clusters. They are advantageous compared to the silhouette score in terms of runtime complexity. Import libraries, and read dataset. Here I import relevant libraries and read the dataset, which I already downloaded to a local folder. Preprocessing. In this step, I discard the columns of string type and only focus on numeric features. Since k-means clustering calculates the distance between data points, it works with numeric columns. Applying PCA to reduce dimension. It is usually good practice to reduce the dimension of the dataset before applying k-means clustering, as in high dimensional spaces, distance measures do not work very well. Calculating silhouette score. K-means clustering not applied directly. It involves the problem of finding an optimal number of clusters. Silhouette score is one of the techniques you can use to determine an optimal number of clusters. Failing to understand the complexity of the calculations involved in silhouette score analysis will yield poor implementation. Alternative solutions. Here I list some of the alternative solutions to find an optimal number of clusters. They are advantageous compared to the silhouette score in terms of runtime complexity. You can reproduce the problem to give it a try. The link to the dataset: https://www.kaggle.com/sobhanmoosavi/us-accidents. We only cluster data points according to road-related features for illustration purposes. It seems 3 is optimal. There are many indices and methods for identifying the optimal number of clusters. But I will focus a few of them. Silhouette score is one of these metrics. It is calculated using the mean intra-cluster distance and the mean nearest-cluster distance for each instance. It computes the distance between each sample and the rest of the samples in the respective clusters. Therefore its runtime complexity is O(n2). Failing to perform runtime analysis, you may need to wait hours if not days for the analysis to complete for a large dataset. Since the current dataset has millions of rows, a workaround can be using simpler metrics such as inertia or applying random sampling to the dataset. I will show these two alternatives. Elbow method This method uses inertia or within-cluster sum-of-squares as it’s input. It depicts the decrease in the inertia value in response to an increasing number of clusters. “Elbow” (the point of inflection on the curve) is a good indication of the point, where the decrease in the inertia value doesn’t change significantly. The advantage of using this technique is that the within-cluster sum-of-squares is not as computationally expensive as silhouette score and is already included in the algorithm as a metric. The wall-clock time of the code snippet above is: 27.9 s ± 247 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) Random downsampling Downsampling allows you to work with much smaller datasets. The advantage is that the time it takes for an algorithm to finish decreases drastically. This enables the analyst to work faster. A downside is that downsampling, if done randomly, may not represent the original dataset. Therefore, any analysis involving downsampled datasets may result in inaccurate results. However, you can always take precautions to make sure that the downsampled dataset represents the original dataset. The wall-clock time of the code snippet above is: 3min 25s ± 640 ms per loop (mean ± std. dev. of 2 runs, 1 loop each) Final Remarks In this post, I tried to emphasize the importance of understanding the complexity of a machine learning algorithm. Runtime analysis of an algorithm is not only crucial for algorithm selection in a specific task but is also important for successful implementation. It is also one of the key skills that most employers look for in the field of data science. Therefore, it is always a good practice to do runtime analysis and comprehend the complexity of an algorithm. If you have any questions regarding the post or any questions about data science in general, you can find me on Linkedin.
[ { "code": null, "e": 534, "s": 172, "text": "Machine learning engineers often find themselves in situations to choose the right algorithm for the problem at hand. It is often the case that they first understand the structure of the problem they provide a solution to. They then explore the dataset at hand. After initial observations and key takeaways, they finally choose the right algorithm for the task." }, { "code": null, "e": 1061, "s": 534, "text": "Deciding on the best algorithm to apply to the dataset at hand may seem a trivial job. Engineers often create shortcuts in these situations. If the task has 0–1 label, just apply logistic regression, right? Wrong! We should be aware of these shortcuts and always remind ourselves that although certain algorithms work good with specific problems, there is no “recipe” when selecting the best algorithm for the problem. However, complexity and runtime analysis of an algorithm should always be discussed and taken into account." }, { "code": null, "e": 1217, "s": 1061, "text": "Runtime analysis of an algorithm is not only crucial to comprehend the inner workings of the algorithm but it also yields a more successful implementation." }, { "code": null, "e": 1431, "s": 1217, "text": "In the rest of the article, I am going to depict a situation, where omitting to think about runtime analysis of an algorithm, k means clustering in this case, can cause an engineer to lose lots of time and energy." }, { "code": null, "e": 1611, "s": 1431, "text": "K-means clustering is one of the most popular and easy-to-implement unsupervised machine learning algorithms. It is also one of the easy-to-comprehend machine learning algorithms." }, { "code": null, "e": 2161, "s": 1611, "text": "Typically, unsupervised machine learning algorithms make inferences from the input dataset using only the feature vectors. Therefore these algorithms are good for datasets having no label data. They can also be quite useful when one wants to extract value or insight from large quantities of structured and unstructured data. K-means clustering is one of these exploratory data analysis techniques, where the goal is to extract subgroups of data points such that the data points in the same cluster are very similar in terms of the features defined." }, { "code": null, "e": 2596, "s": 2161, "text": "K-means clustering starts with the first group of randomly selected data points, which are used as the initial seed of the centroids. The algorithm then performs iterative calculations to assign the rest of the data points to the closest cluster. While performing these calculations according to the distance function defined, the positions of the centroids are updated. It halts the optimizing the center of the clusters when either:" }, { "code": null, "e": 2714, "s": 2596, "text": "The positions of the centroids are stabilized, i.e the change in their values does not exceed a predefined threshold." }, { "code": null, "e": 2770, "s": 2714, "text": "The algorithm surpassed a maximum number of iterations." }, { "code": null, "e": 2816, "s": 2770, "text": "Therefore, the complexity of the algorithm is" }, { "code": null, "e": 2923, "s": 2816, "text": "O(n * K * I * d)n : number of pointsK : number of clustersI : number of iterationsd : number of attributes" }, { "code": null, "e": 3290, "s": 2923, "text": "I am going to share code snippets for a k-means clustering task. My only purpose is to demonstrate an example, where failing to comprehend runtime complexity results in a poor evaluation of the algorithm. The steps I took are not optimized for the algorithm, i.e you can preprocess the data better and get finer clusters. Outline of the steps involved is as follows:" }, { "code": null, "e": 4392, "s": 3290, "text": "Import libraries, and read dataset. Here I import relevant libraries and read the dataset, which I already downloaded to a local folder.Preprocessing. In this step, I discard the columns of string type and only focus on numeric features. Since k-means clustering calculates the distance between data points, it works with numeric columns.Applying PCA to reduce dimension. It is usually good practice to reduce the dimension of the dataset before applying k-means clustering, as in high dimensional spaces, distance measures do not work very well.Calculating silhouette score. K-means clustering not applied directly. It involves the problem of finding an optimal number of clusters. Silhouette score is one of the techniques you can use to determine an optimal number of clusters. Failing to understand the complexity of the calculations involved in silhouette score analysis will yield poor implementation.Alternative solutions. Here I list some of the alternative solutions to find an optimal number of clusters. They are advantageous compared to the silhouette score in terms of runtime complexity." }, { "code": null, "e": 4529, "s": 4392, "text": "Import libraries, and read dataset. Here I import relevant libraries and read the dataset, which I already downloaded to a local folder." }, { "code": null, "e": 4732, "s": 4529, "text": "Preprocessing. In this step, I discard the columns of string type and only focus on numeric features. Since k-means clustering calculates the distance between data points, it works with numeric columns." }, { "code": null, "e": 4941, "s": 4732, "text": "Applying PCA to reduce dimension. It is usually good practice to reduce the dimension of the dataset before applying k-means clustering, as in high dimensional spaces, distance measures do not work very well." }, { "code": null, "e": 5303, "s": 4941, "text": "Calculating silhouette score. K-means clustering not applied directly. It involves the problem of finding an optimal number of clusters. Silhouette score is one of the techniques you can use to determine an optimal number of clusters. Failing to understand the complexity of the calculations involved in silhouette score analysis will yield poor implementation." }, { "code": null, "e": 5498, "s": 5303, "text": "Alternative solutions. Here I list some of the alternative solutions to find an optimal number of clusters. They are advantageous compared to the silhouette score in terms of runtime complexity." }, { "code": null, "e": 5622, "s": 5498, "text": "You can reproduce the problem to give it a try. The link to the dataset: https://www.kaggle.com/sobhanmoosavi/us-accidents." }, { "code": null, "e": 5712, "s": 5622, "text": "We only cluster data points according to road-related features for illustration purposes." }, { "code": null, "e": 5735, "s": 5712, "text": "It seems 3 is optimal." }, { "code": null, "e": 6460, "s": 5735, "text": "There are many indices and methods for identifying the optimal number of clusters. But I will focus a few of them. Silhouette score is one of these metrics. It is calculated using the mean intra-cluster distance and the mean nearest-cluster distance for each instance. It computes the distance between each sample and the rest of the samples in the respective clusters. Therefore its runtime complexity is O(n2). Failing to perform runtime analysis, you may need to wait hours if not days for the analysis to complete for a large dataset. Since the current dataset has millions of rows, a workaround can be using simpler metrics such as inertia or applying random sampling to the dataset. I will show these two alternatives." }, { "code": null, "e": 6473, "s": 6460, "text": "Elbow method" }, { "code": null, "e": 6982, "s": 6473, "text": "This method uses inertia or within-cluster sum-of-squares as it’s input. It depicts the decrease in the inertia value in response to an increasing number of clusters. “Elbow” (the point of inflection on the curve) is a good indication of the point, where the decrease in the inertia value doesn’t change significantly. The advantage of using this technique is that the within-cluster sum-of-squares is not as computationally expensive as silhouette score and is already included in the algorithm as a metric." }, { "code": null, "e": 7032, "s": 6982, "text": "The wall-clock time of the code snippet above is:" }, { "code": null, "e": 7099, "s": 7032, "text": "27.9 s ± 247 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)" }, { "code": null, "e": 7119, "s": 7099, "text": "Random downsampling" }, { "code": null, "e": 7606, "s": 7119, "text": "Downsampling allows you to work with much smaller datasets. The advantage is that the time it takes for an algorithm to finish decreases drastically. This enables the analyst to work faster. A downside is that downsampling, if done randomly, may not represent the original dataset. Therefore, any analysis involving downsampled datasets may result in inaccurate results. However, you can always take precautions to make sure that the downsampled dataset represents the original dataset." }, { "code": null, "e": 7656, "s": 7606, "text": "The wall-clock time of the code snippet above is:" }, { "code": null, "e": 7725, "s": 7656, "text": "3min 25s ± 640 ms per loop (mean ± std. dev. of 2 runs, 1 loop each)" }, { "code": null, "e": 7739, "s": 7725, "text": "Final Remarks" }, { "code": null, "e": 8205, "s": 7739, "text": "In this post, I tried to emphasize the importance of understanding the complexity of a machine learning algorithm. Runtime analysis of an algorithm is not only crucial for algorithm selection in a specific task but is also important for successful implementation. It is also one of the key skills that most employers look for in the field of data science. Therefore, it is always a good practice to do runtime analysis and comprehend the complexity of an algorithm." } ]
How to create boxplot of vectors having different lengths in R?
If we have multiple vectors of different lengths then the boxplot for such vectors can be created by creating a single data frame using those vectors with a categorical column showing the name of the vectors and a numerical column having the corresponding values. Then boxplot function will be used as shown in the below example. Consider the below vector x and y and create the data frame using them − Live Demo > x<-rpois(20,2) > y<-rpois(15,2) > df<-data.frame(X=c(x,y),Grp=rep(c("x","y"),times=c(20,15))) > df X Grp 1 4 x 2 2 x 3 1 x 4 2 x 5 0 x 6 2 x 7 3 x 8 1 x 9 0 x 10 1 x 11 3 x 12 4 x 13 2 x 14 3 x 15 4 x 16 1 x 17 1 x 18 1 x 19 1 x 20 1 x 21 1 y 22 0 y 23 1 y 24 4 y 25 1 y 26 1 y 27 2 y 28 3 y 29 1 y 30 5 y 31 2 y 32 0 y 33 1 y 34 4 y 35 1 y Creating the boxplot for groups in df − > boxplot(X~Grp,data=df)
[ { "code": null, "e": 1392, "s": 1062, "text": "If we have multiple vectors of different lengths then the boxplot for such vectors can be created by creating a single data frame using those vectors with a categorical column showing the name of the vectors and a numerical column having the corresponding values. Then boxplot function will be used as shown in the below example." }, { "code": null, "e": 1465, "s": 1392, "text": "Consider the below vector x and y and create the data frame using them −" }, { "code": null, "e": 1475, "s": 1465, "text": "Live Demo" }, { "code": null, "e": 1576, "s": 1475, "text": "> x<-rpois(20,2)\n> y<-rpois(15,2)\n> df<-data.frame(X=c(x,y),Grp=rep(c(\"x\",\"y\"),times=c(20,15)))\n> df" }, { "code": null, "e": 1900, "s": 1576, "text": " X Grp\n1 4 x\n2 2 x\n3 1 x\n4 2 x\n5 0 x\n6 2 x\n7 3 x\n8 1 x\n9 0 x\n10 1 x\n11 3 x\n12 4 x\n13 2 x\n14 3 x\n15 4 x\n16 1 x\n17 1 x\n18 1 x\n19 1 x\n20 1 x\n21 1 y\n22 0 y\n23 1 y\n24 4 y\n25 1 y\n26 1 y\n27 2 y\n28 3 y\n29 1 y\n30 5 y\n31 2 y\n32 0 y\n33 1 y\n34 4 y\n35 1 y" }, { "code": null, "e": 1940, "s": 1900, "text": "Creating the boxplot for groups in df −" }, { "code": null, "e": 1965, "s": 1940, "text": "> boxplot(X~Grp,data=df)" } ]
Calculate Factorial of a value in R Programming - factorial() Function - GeeksforGeeks
01 Jun, 2020 R Language offers a factorial() function that can compute the factorial of a number without writing the whole code for computing factorial. Syntax: factorial(x) Parameters:x: The number whose factorial has to be computed. Returns: The factorial of desired number. Example 1: # R program to calculate factorial value # Using factorial() method answer1 <- factorial(4) answer2 <- factorial(-3) answer3 <- factorial(0) print(answer1) print(answer2) print(answer3) Output: 24 NaN 1 Example 2: # R program to calculate factorial value # Using factorial() method answer1 <- factorial(c(0, 1, 2, 3, 4)) print(answer1) Output: 1 1 2 6 24 R Math-Function R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Replace specific values in column in R DataFrame ? Loops in R (for, while, repeat) Filter data by multiple conditions in R using Dplyr Change Color of Bars in Barchart using ggplot2 in R How to change Row Names of DataFrame in R ? Printing Output of an R Program How to Change Axis Scales in R Plots? Remove rows with NA in one column of R DataFrame Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame?
[ { "code": null, "e": 24694, "s": 24666, "text": "\n01 Jun, 2020" }, { "code": null, "e": 24834, "s": 24694, "text": "R Language offers a factorial() function that can compute the factorial of a number without writing the whole code for computing factorial." }, { "code": null, "e": 24855, "s": 24834, "text": "Syntax: factorial(x)" }, { "code": null, "e": 24916, "s": 24855, "text": "Parameters:x: The number whose factorial has to be computed." }, { "code": null, "e": 24958, "s": 24916, "text": "Returns: The factorial of desired number." }, { "code": null, "e": 24969, "s": 24958, "text": "Example 1:" }, { "code": "# R program to calculate factorial value # Using factorial() method answer1 <- factorial(4) answer2 <- factorial(-3) answer3 <- factorial(0) print(answer1) print(answer2) print(answer3) ", "e": 25163, "s": 24969, "text": null }, { "code": null, "e": 25171, "s": 25163, "text": "Output:" }, { "code": null, "e": 25181, "s": 25171, "text": "24\nNaN\n1\n" }, { "code": null, "e": 25192, "s": 25181, "text": "Example 2:" }, { "code": "# R program to calculate factorial value # Using factorial() method answer1 <- factorial(c(0, 1, 2, 3, 4)) print(answer1) ", "e": 25321, "s": 25192, "text": null }, { "code": null, "e": 25329, "s": 25321, "text": "Output:" }, { "code": null, "e": 25344, "s": 25329, "text": "1 1 2 6 24\n" }, { "code": null, "e": 25360, "s": 25344, "text": "R Math-Function" }, { "code": null, "e": 25371, "s": 25360, "text": "R Language" }, { "code": null, "e": 25469, "s": 25371, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25478, "s": 25469, "text": "Comments" }, { "code": null, "e": 25491, "s": 25478, "text": "Old Comments" }, { "code": null, "e": 25549, "s": 25491, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 25581, "s": 25549, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 25633, "s": 25581, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 25685, "s": 25633, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 25729, "s": 25685, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 25761, "s": 25729, "text": "Printing Output of an R Program" }, { "code": null, "e": 25799, "s": 25761, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 25848, "s": 25799, "text": "Remove rows with NA in one column of R DataFrame" }, { "code": null, "e": 25883, "s": 25848, "text": "Group by function in R using Dplyr" } ]
IMPORTING, EXPORTING and CHANGING Keywords in ABAP
IMPORTING transfers a value from the caller to the called method by passing an actual parameter EXPORTING is just opposite to what IMPORTING does. IT passes value from the method to Caller. CHANGING is transferring the value from caller to method by a variable which is processed or changed and the changed value is passed back to the Caller. Thus it combines both IMPORTING and EXPORTING function. There are a couple of ways in which CHANGING can be used: CHANGING myvar or CHANGING VALUE(myvar) By using, CHANGING myvar , the value of a variable is changed and passed back to the caller or main program. Using CHANGING VALUE(myvar) is a kind of exception handling. In case there is an exception or error in Subroutine, the value of a variable will be returned unchanged although it is possible that it has been changed in the subroutine.
[ { "code": null, "e": 1158, "s": 1062, "text": "IMPORTING transfers a value from the caller to the called method by passing an actual parameter" }, { "code": null, "e": 1252, "s": 1158, "text": "EXPORTING is just opposite to what IMPORTING does. IT passes value from the method to Caller." }, { "code": null, "e": 1461, "s": 1252, "text": "CHANGING is transferring the value from caller to method by a variable which is processed or changed and the changed value is passed back to the Caller. Thus it combines both IMPORTING and EXPORTING function." }, { "code": null, "e": 1519, "s": 1461, "text": "There are a couple of ways in which CHANGING can be used:" }, { "code": null, "e": 1559, "s": 1519, "text": "CHANGING myvar or CHANGING VALUE(myvar)" }, { "code": null, "e": 1668, "s": 1559, "text": "By using, CHANGING myvar , the value of a variable is changed and passed back to the caller or main program." }, { "code": null, "e": 1902, "s": 1668, "text": "Using CHANGING VALUE(myvar) is a kind of exception handling. In case there is an exception or error in Subroutine, the value of a variable will be returned unchanged although it is possible that it has been changed in the subroutine." } ]
How to clear a MongoDB database?
To clear, use dropDatabase. Following is the syntax − use yourDatabaseName; db.dropDatabase(); To clear a MongoDB database, first show all the databases − > show dbs This will produce the following output − MyDB 0.000GB admin 0.000GB config 0.000GB local 0.000GB onlinecustomertracker 0.000GB test 0.006GB Now, let us delete the database onlinecustomertracker − > use onlinecustomertracker switched to db onlinecustomertracker > db.dropDatabase(); { "dropped" : "onlinecustomertracker", "ok" : 1 } Following is the query to show all databases after deleting a database above − > show dbs This will produce the following output − MyDB 0.000GB admin 0.000GB config 0.000GB local 0.000GB test 0.006GB
[ { "code": null, "e": 1116, "s": 1062, "text": "To clear, use dropDatabase. Following is the syntax −" }, { "code": null, "e": 1157, "s": 1116, "text": "use yourDatabaseName;\ndb.dropDatabase();" }, { "code": null, "e": 1217, "s": 1157, "text": "To clear a MongoDB database, first show all the databases −" }, { "code": null, "e": 1228, "s": 1217, "text": "> show dbs" }, { "code": null, "e": 1269, "s": 1228, "text": "This will produce the following output −" }, { "code": null, "e": 1383, "s": 1269, "text": "MyDB 0.000GB\nadmin 0.000GB\nconfig 0.000GB\nlocal 0.000GB\nonlinecustomertracker 0.000GB\ntest 0.006GB" }, { "code": null, "e": 1439, "s": 1383, "text": "Now, let us delete the database onlinecustomertracker −" }, { "code": null, "e": 1575, "s": 1439, "text": "> use onlinecustomertracker\nswitched to db onlinecustomertracker\n> db.dropDatabase();\n{ \"dropped\" : \"onlinecustomertracker\", \"ok\" : 1 }" }, { "code": null, "e": 1654, "s": 1575, "text": "Following is the query to show all databases after deleting a database above −" }, { "code": null, "e": 1665, "s": 1654, "text": "> show dbs" }, { "code": null, "e": 1706, "s": 1665, "text": "This will produce the following output −" }, { "code": null, "e": 1790, "s": 1706, "text": "MyDB 0.000GB\nadmin 0.000GB\nconfig 0.000GB\nlocal 0.000GB\ntest 0.006GB" } ]
Angular PrimeNG ConfirmDialog Component - GeeksforGeeks
19 Oct, 2021 Angular PrimeNG is a framework used with angular to create components with great styling and this framework is very easy to use and is used to make responsive websites. In this article, we will know how to use ConfirmDialog component in angular primeNG. The ConfirmDialog component is used to make a dialog box containing confirm button to confirm the element. Properties: message: It is the message of the confirmation. It is of string data type, the default value is null. key: It is the Optional key to match the key of the confirm dialog. It is of string data type, the default value is null. icon: It is the Icon to display next to the message. It is of string data type, the default value is null. header: It is the Header text of the dialog. It is of string data type, the default value is null. accept: It is the Callback to execute when action is confirmed. reject: It is the Callback to execute when action is rejected acceptLabel: It is the Label of the accept button. It is of string data type, the default value is null. rejectLabel: It is the Label of the reject button. It is of string data type, the default value is null. acceptIcon: It is the Icon of the accept button. It is of string data type, the default value is null. rejectIcon: It is the Icon of the reject button. It is of string data type, the default value is null. acceptButtonStyleClass: It is used to set the Style class of the accept button. It is of string data type, the default value is null. rejectButtonStyleClass: It is used to set the Style class of the reject button. It is of string data type, the default value is null. acceptVisible: It is used to set the Visibility of the accept button. It is of boolean datatype & the default value is false. rejectVisible: It is used to set the Visibility of the reject button. It is of boolean datatype & the default value is false. style: It is the Inline style of the component. It is of object data type, the default value is null. styleClass: It is the Style class of the component. It is of string data type, the default value is null. maskStyleClass: It is the Style class of the mask. It is of string data type, the default value is null. blockScroll: It is used to specify Whether background scroll should be blocked when the dialog is visible. It is of boolean datatype & the default value is false. closeOnEscape: It Specifies if pressing the escape key should hide the dialog. It is of boolean datatype & the default value is false. dismissableMask: It Specifices if clicking the modal background should hide the dialog. It is of boolean datatype & the default value is false. defaultFocus: It is the Element to receive the focus when the dialog gets visible. Events: onHide: It is the callback that is fired when dialog is hidden. Creating Angular Application And Installing Module: Step 1: Create a Angular application using the following command. ng new appname Step 2: After creating your project folder i.e. appname, move to it using the following command. cd appname Step 3: Install PrimeNG in your given directory. npm install primeng --save npm install primeicons --save Project Structure: It will look like the following. Example: This is the basic example which shows how to use ConfirmDialog component app.component.html <h2>GeeksforGeeks</h2><h5>PrimeNG ConfirmDialog Component</h5><p-confirmDialog [style]="{width: '60vw'}"></p-confirmDialog><p-button (click)="GetConfirm()" label="Click Here"></p-button> app.module.ts import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import {BrowserAnimationsModule} from '@angular/platform-browser/animations'; import { AppComponent } from './app.component'; import { ButtonModule } from 'primeng/button';import { ConfirmDialogModule } from 'primeng/confirmdialog'; @NgModule({ imports: [ BrowserModule, BrowserAnimationsModule, ConfirmDialogModule, ButtonModule, ], declarations: [ AppComponent ], bootstrap: [ AppComponent ]}) export class AppModule { } app.component.ts import { Component } from '@angular/core';import {ConfirmationService} from 'primeng/api';import { PrimeNGConfig } from 'primeng/api'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styles: [], providers: [ConfirmationService]})export class AppComponent { constructor(private confirmationService: ConfirmationService, private primengConfig: PrimeNGConfig) {} GetConfirm() { this.confirmationService.confirm({ message: 'Angular PrimeNG ConfirmDialog Component', header: 'GeeksforGeeks', }); }} Output: Reference: https://primefaces.org/primeng/showcase/#/confirmdialog varshagumber28 Angular-PrimeNG AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Top 10 Angular Libraries For Web Developers Angular 10 (blur) Event Angular PrimeNG Dropdown Component How to make a Bootstrap Modal Popup in Angular 9/8 ? How to create module with Routing in Angular 9 ? Roadmap to Become a Web Developer in 2022 Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? Installation of Node.js on Linux Convert a string to an integer in JavaScript
[ { "code": null, "e": 25109, "s": 25081, "text": "\n19 Oct, 2021" }, { "code": null, "e": 25278, "s": 25109, "text": "Angular PrimeNG is a framework used with angular to create components with great styling and this framework is very easy to use and is used to make responsive websites." }, { "code": null, "e": 25470, "s": 25278, "text": "In this article, we will know how to use ConfirmDialog component in angular primeNG. The ConfirmDialog component is used to make a dialog box containing confirm button to confirm the element." }, { "code": null, "e": 25482, "s": 25470, "text": "Properties:" }, { "code": null, "e": 25584, "s": 25482, "text": "message: It is the message of the confirmation. It is of string data type, the default value is null." }, { "code": null, "e": 25706, "s": 25584, "text": "key: It is the Optional key to match the key of the confirm dialog. It is of string data type, the default value is null." }, { "code": null, "e": 25813, "s": 25706, "text": "icon: It is the Icon to display next to the message. It is of string data type, the default value is null." }, { "code": null, "e": 25912, "s": 25813, "text": "header: It is the Header text of the dialog. It is of string data type, the default value is null." }, { "code": null, "e": 25976, "s": 25912, "text": "accept: It is the Callback to execute when action is confirmed." }, { "code": null, "e": 26038, "s": 25976, "text": "reject: It is the Callback to execute when action is rejected" }, { "code": null, "e": 26143, "s": 26038, "text": "acceptLabel: It is the Label of the accept button. It is of string data type, the default value is null." }, { "code": null, "e": 26248, "s": 26143, "text": "rejectLabel: It is the Label of the reject button. It is of string data type, the default value is null." }, { "code": null, "e": 26351, "s": 26248, "text": "acceptIcon: It is the Icon of the accept button. It is of string data type, the default value is null." }, { "code": null, "e": 26454, "s": 26351, "text": "rejectIcon: It is the Icon of the reject button. It is of string data type, the default value is null." }, { "code": null, "e": 26588, "s": 26454, "text": "acceptButtonStyleClass: It is used to set the Style class of the accept button. It is of string data type, the default value is null." }, { "code": null, "e": 26722, "s": 26588, "text": "rejectButtonStyleClass: It is used to set the Style class of the reject button. It is of string data type, the default value is null." }, { "code": null, "e": 26848, "s": 26722, "text": "acceptVisible: It is used to set the Visibility of the accept button. It is of boolean datatype & the default value is false." }, { "code": null, "e": 26974, "s": 26848, "text": "rejectVisible: It is used to set the Visibility of the reject button. It is of boolean datatype & the default value is false." }, { "code": null, "e": 27076, "s": 26974, "text": "style: It is the Inline style of the component. It is of object data type, the default value is null." }, { "code": null, "e": 27182, "s": 27076, "text": "styleClass: It is the Style class of the component. It is of string data type, the default value is null." }, { "code": null, "e": 27287, "s": 27182, "text": "maskStyleClass: It is the Style class of the mask. It is of string data type, the default value is null." }, { "code": null, "e": 27450, "s": 27287, "text": "blockScroll: It is used to specify Whether background scroll should be blocked when the dialog is visible. It is of boolean datatype & the default value is false." }, { "code": null, "e": 27585, "s": 27450, "text": "closeOnEscape: It Specifies if pressing the escape key should hide the dialog. It is of boolean datatype & the default value is false." }, { "code": null, "e": 27729, "s": 27585, "text": "dismissableMask: It Specifices if clicking the modal background should hide the dialog. It is of boolean datatype & the default value is false." }, { "code": null, "e": 27812, "s": 27729, "text": "defaultFocus: It is the Element to receive the focus when the dialog gets visible." }, { "code": null, "e": 27820, "s": 27812, "text": "Events:" }, { "code": null, "e": 27884, "s": 27820, "text": "onHide: It is the callback that is fired when dialog is hidden." }, { "code": null, "e": 27938, "s": 27886, "text": "Creating Angular Application And Installing Module:" }, { "code": null, "e": 28004, "s": 27938, "text": "Step 1: Create a Angular application using the following command." }, { "code": null, "e": 28019, "s": 28004, "text": "ng new appname" }, { "code": null, "e": 28116, "s": 28019, "text": "Step 2: After creating your project folder i.e. appname, move to it using the following command." }, { "code": null, "e": 28127, "s": 28116, "text": "cd appname" }, { "code": null, "e": 28176, "s": 28127, "text": "Step 3: Install PrimeNG in your given directory." }, { "code": null, "e": 28233, "s": 28176, "text": "npm install primeng --save\nnpm install primeicons --save" }, { "code": null, "e": 28285, "s": 28233, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 28368, "s": 28285, "text": "Example: This is the basic example which shows how to use ConfirmDialog component " }, { "code": null, "e": 28387, "s": 28368, "text": "app.component.html" }, { "code": "<h2>GeeksforGeeks</h2><h5>PrimeNG ConfirmDialog Component</h5><p-confirmDialog [style]=\"{width: '60vw'}\"></p-confirmDialog><p-button (click)=\"GetConfirm()\" label=\"Click Here\"></p-button>", "e": 28574, "s": 28387, "text": null }, { "code": null, "e": 28588, "s": 28574, "text": "app.module.ts" }, { "code": "import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import {BrowserAnimationsModule} from '@angular/platform-browser/animations'; import { AppComponent } from './app.component'; import { ButtonModule } from 'primeng/button';import { ConfirmDialogModule } from 'primeng/confirmdialog'; @NgModule({ imports: [ BrowserModule, BrowserAnimationsModule, ConfirmDialogModule, ButtonModule, ], declarations: [ AppComponent ], bootstrap: [ AppComponent ]}) export class AppModule { }", "e": 29141, "s": 28588, "text": null }, { "code": null, "e": 29158, "s": 29141, "text": "app.component.ts" }, { "code": "import { Component } from '@angular/core';import {ConfirmationService} from 'primeng/api';import { PrimeNGConfig } from 'primeng/api'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styles: [], providers: [ConfirmationService]})export class AppComponent { constructor(private confirmationService: ConfirmationService, private primengConfig: PrimeNGConfig) {} GetConfirm() { this.confirmationService.confirm({ message: 'Angular PrimeNG ConfirmDialog Component', header: 'GeeksforGeeks', }); }}", "e": 29736, "s": 29158, "text": null }, { "code": null, "e": 29744, "s": 29736, "text": "Output:" }, { "code": null, "e": 29811, "s": 29744, "text": "Reference: https://primefaces.org/primeng/showcase/#/confirmdialog" }, { "code": null, "e": 29826, "s": 29811, "text": "varshagumber28" }, { "code": null, "e": 29842, "s": 29826, "text": "Angular-PrimeNG" }, { "code": null, "e": 29852, "s": 29842, "text": "AngularJS" }, { "code": null, "e": 29869, "s": 29852, "text": "Web Technologies" }, { "code": null, "e": 29967, "s": 29869, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30011, "s": 29967, "text": "Top 10 Angular Libraries For Web Developers" }, { "code": null, "e": 30035, "s": 30011, "text": "Angular 10 (blur) Event" }, { "code": null, "e": 30070, "s": 30035, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 30123, "s": 30070, "text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?" }, { "code": null, "e": 30172, "s": 30123, "text": "How to create module with Routing in Angular 9 ?" }, { "code": null, "e": 30214, "s": 30172, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 30276, "s": 30214, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 30319, "s": 30276, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 30352, "s": 30319, "text": "Installation of Node.js on Linux" } ]
Machine Learning With SQL — It’s Easier Than You Think | by Dario Radečić | Towards Data Science
If you’ve been studying data science, it’s likely you know how to perform machine learning tasks in languages like Python, R, and Julia. But what can you do when speed is the key, the hardware is limited, or the company you work for treats SQL as the only option for predictive analytics? In-database machine learning is the answer. We’ll use Oracle Cloud for this article. It’s free, so please register and create an instance of the OLTP database (Version 19c, has 0.2TB of storage). Once done, download the cloud wallet and establish a connection through SQL Developer — or any other tool. This will take you 10 minutes at least but is a fairly straightforward thing to do, so I won’t waste time on it. We’ll use Oracle Machine Learning (OML) to train a classification model on the well-known Iris dataset. I’ve chosen it because it doesn’t require any preparation — we only need to create the table and insert the data. Let’s do that next. As mentioned, we need to create a table for holding the Iris dataset, and then we need to load data to it. OML requires one column to be used as row ID (sequence), so let’s keep that in mind: CREATE SEQUENCE seq_iris;CREATE TABLE iris_data( iris_id NUMBER DEFAULT seq_iris.NEXTVAL, sepal_length NUMBER, sepal_width NUMBER, petal_length NUMBER, petal_width NUMBER, species VARCHAR2(16)); Awesome! Now we can download the data and load it: When a modal window pops-up simply provide a path to the downloaded CSV and click Next a couple of times. SQL Developer should get things right without your assistance. Once done, we have our dataset loaded and prepared: Let’s continue with the fun part now. Now we can get our hands dirty with the fun stuff, and that’s training the classification model. This is broken down into multiple steps, such as train/test split, model training, and model evaluation. Let’s start with the simplest one. Oracle likes this step done with two views — one for training data and one for testing data. We can easily create those with a bit of PL/SQL magic: BEGIN EXECUTE IMMEDIATE ‘CREATE OR REPLACE VIEW iris_train_data AS SELECT * FROM iris_data SAMPLE (75) SEED (42)’; EXECUTE IMMEDIATE ‘CREATE OR REPLACE VIEW iris_test_data AS SELECT * FROM iris_data MINUS SELECT * FROM iris_train_data’;END;/ This script does two things: Creates a train view — has 75% of data (SAMPLE (75)) split at the random seed 42 ( SEED (42))Creates a test view — as a difference of the entire dataset and the training view Creates a train view — has 75% of data (SAMPLE (75)) split at the random seed 42 ( SEED (42)) Creates a test view — as a difference of the entire dataset and the training view Our data is stored in views named iris_train_data and iris_test_data — you guess which one holds what. Let’s quickly check how many rows are in each: SELECT COUNT(*) FROM iris_train_data;>>> 111SELECT COUNT(*) FROM iris_test_data;>>> 39 We are ready to train the model, so let’s do that next. The easiest method for model training is through DBMS_DATA_MINING package, with a single procedure execution, and without the need for creating additional settings tables. We’ll use the Decision Tree algorithm to train our model. Here’s how: DECLARE v_setlst DBMS_DATA_MINING.SETTING_LIST;BEGIN v_setlst(‘PREP_AUTO’) := ‘ON’; v_setlst(‘ALGO_NAME’) := ‘ALGO_DECISION_TREE’; DBMS_DATA_MINING.CREATE_MODEL2( ‘iris_clf_model’, ‘CLASSIFICATION’, ‘SELECT * FROM iris_train_data’, v_setlst, ‘iris_id’, ‘species’ );END;/ The CREATE_MODEL2 procedure (curious why it wasn’t named CREATE_MODEL_FINAL_FINAL89) accepts a lot of parameters. Let’s explain the ones we entered: iris_clf_model — simply the name of your model. Can be anything CLASSIFICATION — type of machine learning task we’re doing. Must be uppercase for some reason SELECT * FROM iris_train_data — specifies where the training data is stored v_setlst — above declared settings list for our model iris_id — name of the sequence type column (each value is unique) species — name of the target variable (what we’re trying to predict) Executing this block will take a second or two, but once done it’s ready for evaluation! Let’s use this script to evaluate our model: BEGIN DBMS_DATA_MINING.APPLY( ‘iris_clf_model’, ‘iris_test_data’, ‘iris_id’, ‘iris_apply_result’ );END;/ It applies iris_clf_model to the unseen test data iris_test_data and stores evaluation results into a iris_apply_result table. Here’s how this table looks like: It has many more rows (39 x 3), but you get the point. This still isn’t the most straightforward thing to look at, so let’s show the results in a slightly different way: DECLARE CURSOR iris_ids IS SELECT DISTINCT(iris_id) iris_id FROM iris_apply_result ORDER BY iris_id; curr_y VARCHAR2(16); curr_yhat VARCHAR2(16); num_correct INTEGER := 0; num_total INTEGER := 0;BEGIN FOR r_id IN iris_ids LOOP BEGIN EXECUTE IMMEDIATE ‘SELECT species FROM iris_test_data WHERE iris_id = ‘ || r_id.iris_id INTO curr_y; EXECUTE IMMEDIATE ‘SELECT prediction FROM iris_apply_result WHERE iris_id = ‘ || r_id.iris_id || ‘AND probability = ( SELECT MAX(probability) FROM iris_apply_result WHERE iris_id = ‘ || r_id.iris_id || ‘)’ INTO curr_yhat; END; num_total := num_total + 1; IF curr_y = curr_yhat THEN num_correct := num_correct + 1; END IF; END LOOP; DBMS_OUTPUT.PUT_LINE(‘Num. test cases: ‘ || num_total); DBMS_OUTPUT.PUT_LINE(‘Num. correct : ‘ || num_correct); DBMS_OUTPUT.PUT_LINE(‘Accuracy : ‘ || ROUND((num_correct / num_total), 2));END;/ Yes, it’s a lot, but the script above can’t be any simpler. Let’s break it down: CURSOR — gets all distinct iris_ids (because we have them duplicated in iris_apply_results table curr_y, curr_yhat, num_correct, num_total are variables for storing actual species and predicted species at every iteration, number of correct classifications, and total number of test items For every unique iris_id we get the actual species (from iris_test_data, where ids match) and the predicted species (where prediction probability is the highest in iris_apply_results table) Then it’s easy to check if the actual and predicted values are identical — which indicates the classification is correct Variables num_total and num_correct are updated at every iteration Finally, we print the model’s performance to the console Here’s the output for this script: Awesome! To interpret: The test set has 39 cases Of these 39, 37 were classified correctly Which results in the 95% accuracy And that’s pretty much it for the model evaluation. And there you have it — machine learning project written from scratch in SQL. Not all of us have the privilege to work with something like Python on our job, and if a machine learning task comes on your desk you now know how to solve it via SQL. This was just a simple classification task, of course, and scripts can be improved further, but you get the point. I hope you’ve managed to follow along. For any questions and comments, please refer to the comment section. Thanks for reading. Loved the article? Become a Medium member to continue learning without limits. I’ll receive a portion of your membership fee if you use the following link, with no extra cost to you. medium.com Originally published at https://betterdatascience.com on September 6, 2020.
[ { "code": null, "e": 504, "s": 171, "text": "If you’ve been studying data science, it’s likely you know how to perform machine learning tasks in languages like Python, R, and Julia. But what can you do when speed is the key, the hardware is limited, or the company you work for treats SQL as the only option for predictive analytics? In-database machine learning is the answer." }, { "code": null, "e": 763, "s": 504, "text": "We’ll use Oracle Cloud for this article. It’s free, so please register and create an instance of the OLTP database (Version 19c, has 0.2TB of storage). Once done, download the cloud wallet and establish a connection through SQL Developer — or any other tool." }, { "code": null, "e": 876, "s": 763, "text": "This will take you 10 minutes at least but is a fairly straightforward thing to do, so I won’t waste time on it." }, { "code": null, "e": 1094, "s": 876, "text": "We’ll use Oracle Machine Learning (OML) to train a classification model on the well-known Iris dataset. I’ve chosen it because it doesn’t require any preparation — we only need to create the table and insert the data." }, { "code": null, "e": 1114, "s": 1094, "text": "Let’s do that next." }, { "code": null, "e": 1306, "s": 1114, "text": "As mentioned, we need to create a table for holding the Iris dataset, and then we need to load data to it. OML requires one column to be used as row ID (sequence), so let’s keep that in mind:" }, { "code": null, "e": 1531, "s": 1306, "text": "CREATE SEQUENCE seq_iris;CREATE TABLE iris_data( iris_id NUMBER DEFAULT seq_iris.NEXTVAL, sepal_length NUMBER, sepal_width NUMBER, petal_length NUMBER, petal_width NUMBER, species VARCHAR2(16));" }, { "code": null, "e": 1582, "s": 1531, "text": "Awesome! Now we can download the data and load it:" }, { "code": null, "e": 1751, "s": 1582, "text": "When a modal window pops-up simply provide a path to the downloaded CSV and click Next a couple of times. SQL Developer should get things right without your assistance." }, { "code": null, "e": 1803, "s": 1751, "text": "Once done, we have our dataset loaded and prepared:" }, { "code": null, "e": 1841, "s": 1803, "text": "Let’s continue with the fun part now." }, { "code": null, "e": 2078, "s": 1841, "text": "Now we can get our hands dirty with the fun stuff, and that’s training the classification model. This is broken down into multiple steps, such as train/test split, model training, and model evaluation. Let’s start with the simplest one." }, { "code": null, "e": 2226, "s": 2078, "text": "Oracle likes this step done with two views — one for training data and one for testing data. We can easily create those with a bit of PL/SQL magic:" }, { "code": null, "e": 2546, "s": 2226, "text": "BEGIN EXECUTE IMMEDIATE ‘CREATE OR REPLACE VIEW iris_train_data AS SELECT * FROM iris_data SAMPLE (75) SEED (42)’; EXECUTE IMMEDIATE ‘CREATE OR REPLACE VIEW iris_test_data AS SELECT * FROM iris_data MINUS SELECT * FROM iris_train_data’;END;/" }, { "code": null, "e": 2575, "s": 2546, "text": "This script does two things:" }, { "code": null, "e": 2750, "s": 2575, "text": "Creates a train view — has 75% of data (SAMPLE (75)) split at the random seed 42 ( SEED (42))Creates a test view — as a difference of the entire dataset and the training view" }, { "code": null, "e": 2844, "s": 2750, "text": "Creates a train view — has 75% of data (SAMPLE (75)) split at the random seed 42 ( SEED (42))" }, { "code": null, "e": 2926, "s": 2844, "text": "Creates a test view — as a difference of the entire dataset and the training view" }, { "code": null, "e": 3029, "s": 2926, "text": "Our data is stored in views named iris_train_data and iris_test_data — you guess which one holds what." }, { "code": null, "e": 3076, "s": 3029, "text": "Let’s quickly check how many rows are in each:" }, { "code": null, "e": 3163, "s": 3076, "text": "SELECT COUNT(*) FROM iris_train_data;>>> 111SELECT COUNT(*) FROM iris_test_data;>>> 39" }, { "code": null, "e": 3219, "s": 3163, "text": "We are ready to train the model, so let’s do that next." }, { "code": null, "e": 3391, "s": 3219, "text": "The easiest method for model training is through DBMS_DATA_MINING package, with a single procedure execution, and without the need for creating additional settings tables." }, { "code": null, "e": 3461, "s": 3391, "text": "We’ll use the Decision Tree algorithm to train our model. Here’s how:" }, { "code": null, "e": 3791, "s": 3461, "text": "DECLARE v_setlst DBMS_DATA_MINING.SETTING_LIST;BEGIN v_setlst(‘PREP_AUTO’) := ‘ON’; v_setlst(‘ALGO_NAME’) := ‘ALGO_DECISION_TREE’; DBMS_DATA_MINING.CREATE_MODEL2( ‘iris_clf_model’, ‘CLASSIFICATION’, ‘SELECT * FROM iris_train_data’, v_setlst, ‘iris_id’, ‘species’ );END;/" }, { "code": null, "e": 3940, "s": 3791, "text": "The CREATE_MODEL2 procedure (curious why it wasn’t named CREATE_MODEL_FINAL_FINAL89) accepts a lot of parameters. Let’s explain the ones we entered:" }, { "code": null, "e": 4004, "s": 3940, "text": "iris_clf_model — simply the name of your model. Can be anything" }, { "code": null, "e": 4098, "s": 4004, "text": "CLASSIFICATION — type of machine learning task we’re doing. Must be uppercase for some reason" }, { "code": null, "e": 4174, "s": 4098, "text": "SELECT * FROM iris_train_data — specifies where the training data is stored" }, { "code": null, "e": 4228, "s": 4174, "text": "v_setlst — above declared settings list for our model" }, { "code": null, "e": 4294, "s": 4228, "text": "iris_id — name of the sequence type column (each value is unique)" }, { "code": null, "e": 4363, "s": 4294, "text": "species — name of the target variable (what we’re trying to predict)" }, { "code": null, "e": 4452, "s": 4363, "text": "Executing this block will take a second or two, but once done it’s ready for evaluation!" }, { "code": null, "e": 4497, "s": 4452, "text": "Let’s use this script to evaluate our model:" }, { "code": null, "e": 4639, "s": 4497, "text": "BEGIN DBMS_DATA_MINING.APPLY( ‘iris_clf_model’, ‘iris_test_data’, ‘iris_id’, ‘iris_apply_result’ );END;/" }, { "code": null, "e": 4800, "s": 4639, "text": "It applies iris_clf_model to the unseen test data iris_test_data and stores evaluation results into a iris_apply_result table. Here’s how this table looks like:" }, { "code": null, "e": 4970, "s": 4800, "text": "It has many more rows (39 x 3), but you get the point. This still isn’t the most straightforward thing to look at, so let’s show the results in a slightly different way:" }, { "code": null, "e": 6206, "s": 4970, "text": "DECLARE CURSOR iris_ids IS SELECT DISTINCT(iris_id) iris_id FROM iris_apply_result ORDER BY iris_id; curr_y VARCHAR2(16); curr_yhat VARCHAR2(16); num_correct INTEGER := 0; num_total INTEGER := 0;BEGIN FOR r_id IN iris_ids LOOP BEGIN EXECUTE IMMEDIATE ‘SELECT species FROM iris_test_data WHERE iris_id = ‘ || r_id.iris_id INTO curr_y; EXECUTE IMMEDIATE ‘SELECT prediction FROM iris_apply_result WHERE iris_id = ‘ || r_id.iris_id || ‘AND probability = ( SELECT MAX(probability) FROM iris_apply_result WHERE iris_id = ‘ || r_id.iris_id || ‘)’ INTO curr_yhat; END; num_total := num_total + 1; IF curr_y = curr_yhat THEN num_correct := num_correct + 1; END IF; END LOOP; DBMS_OUTPUT.PUT_LINE(‘Num. test cases: ‘ || num_total); DBMS_OUTPUT.PUT_LINE(‘Num. correct : ‘ || num_correct); DBMS_OUTPUT.PUT_LINE(‘Accuracy : ‘ || ROUND((num_correct / num_total), 2));END;/" }, { "code": null, "e": 6287, "s": 6206, "text": "Yes, it’s a lot, but the script above can’t be any simpler. Let’s break it down:" }, { "code": null, "e": 6384, "s": 6287, "text": "CURSOR — gets all distinct iris_ids (because we have them duplicated in iris_apply_results table" }, { "code": null, "e": 6575, "s": 6384, "text": "curr_y, curr_yhat, num_correct, num_total are variables for storing actual species and predicted species at every iteration, number of correct classifications, and total number of test items" }, { "code": null, "e": 6765, "s": 6575, "text": "For every unique iris_id we get the actual species (from iris_test_data, where ids match) and the predicted species (where prediction probability is the highest in iris_apply_results table)" }, { "code": null, "e": 6886, "s": 6765, "text": "Then it’s easy to check if the actual and predicted values are identical — which indicates the classification is correct" }, { "code": null, "e": 6953, "s": 6886, "text": "Variables num_total and num_correct are updated at every iteration" }, { "code": null, "e": 7010, "s": 6953, "text": "Finally, we print the model’s performance to the console" }, { "code": null, "e": 7045, "s": 7010, "text": "Here’s the output for this script:" }, { "code": null, "e": 7068, "s": 7045, "text": "Awesome! To interpret:" }, { "code": null, "e": 7094, "s": 7068, "text": "The test set has 39 cases" }, { "code": null, "e": 7136, "s": 7094, "text": "Of these 39, 37 were classified correctly" }, { "code": null, "e": 7170, "s": 7136, "text": "Which results in the 95% accuracy" }, { "code": null, "e": 7222, "s": 7170, "text": "And that’s pretty much it for the model evaluation." }, { "code": null, "e": 7468, "s": 7222, "text": "And there you have it — machine learning project written from scratch in SQL. Not all of us have the privilege to work with something like Python on our job, and if a machine learning task comes on your desk you now know how to solve it via SQL." }, { "code": null, "e": 7691, "s": 7468, "text": "This was just a simple classification task, of course, and scripts can be improved further, but you get the point. I hope you’ve managed to follow along. For any questions and comments, please refer to the comment section." }, { "code": null, "e": 7711, "s": 7691, "text": "Thanks for reading." }, { "code": null, "e": 7894, "s": 7711, "text": "Loved the article? Become a Medium member to continue learning without limits. I’ll receive a portion of your membership fee if you use the following link, with no extra cost to you." }, { "code": null, "e": 7905, "s": 7894, "text": "medium.com" } ]
Python Input Methods for Competitive Programming?
In this we are going to see different ways of I/O methods for competitive programming in Python. In competitive programming it is important to read the input as fast as possible so as take advantage over others. Suppose you’re in a codeforces or similar online jude (like SPOJ) and you have to read numbers a, b, c, d and print their product. There are multiple ways to do, let’s explore them – one by one One way to doing it is either through list comprehension and map function. Method 1: Using a list comprehension a, b, c, d = [int(x) for x in input().split()] print(a*b*c*d) Method 2: Using the map function a, b, c, d = map(int, input().split()) print(a*b*c*d) Another way of doing above problem is using stdin and stdout which is much faster. Method 1a: List comprehension with stdin and stdout from sys import stdin, stdout a, b, c, d = [int(x) for x in stdin.readline().rstrip().split()] stdout.write(str(a*b*c*d) + "\n") Let’s look at another problem from the competitive programming where we can test our input and output methods on the problems. The problem is called INTEST-Enormous Input Test on SPOJ. Input The input begins with two positive integers n k (n, k<=107). The next n lines of input contain one positive integer ti, not greater than 109, each. Output Write a single integer to output, denoting how many integers ti are divisible by k. Where INPUT: The input begins with two positive integers n and k (where- n, k <=10). The next lines of input contain one positive integer t not greater than 10*9 each. INPUT: The input begins with two positive integers n and k (where- n, k <=10). The next lines of input contain one positive integer t not greater than 10*9 each. OUTPUT: A single integer denoting how many integers t are divisible by k. OUTPUT: A single integer denoting how many integers t are divisible by k. For example Input 7 3 1 51 966369 7 9 999996 11 Output 4 Method 1 One way to solve above problem is below though not the efficient one def main(): n, k = [int(c) for c in input().split()] cnt = 0 for _ in range(n): t = int(input()) if t % k == 0: cnt += 1 print(cnt) if __name__ == "__main__": main() Method 2 Another more efficient way of solving above problem is using stdin and stdout. Below program runs much faster compared to the previous one. from sys import stdin, stdout def main(): n, k = [int(c) for c in input().split()] cnt = 0 for _ in range(n): t = int(stdin.readline()) if t % k == 0: cnt += 1 stdout.write(str(cnt)) if __name__ == "__main__": main() Method 3 Another way to solve above problem which much faster than the previous two mentioned above is by using stdin and stdout (very similar to the way we used in method 2) however, read the whole input at once and load it into a list. def main(): for sys import stdin, stdout n, k = stdin.readline().split() n = int(n) k = int(k) cnt = 0 lines = stdin.readlines() for line in lines: if int(line) % k == 0: cnt += 1 stdout.write(str(cnt)) if __name__ == "__main__": main()
[ { "code": null, "e": 1274, "s": 1062, "text": "In this we are going to see different ways of I/O methods for competitive programming in Python. In competitive programming it is important to read the input as fast as possible so as take advantage over others." }, { "code": null, "e": 1468, "s": 1274, "text": "Suppose you’re in a codeforces or similar online jude (like SPOJ) and you have to read numbers a, b, c, d and print their product. There are multiple ways to do, let’s explore them – one by one" }, { "code": null, "e": 1543, "s": 1468, "text": "One way to doing it is either through list comprehension and map function." }, { "code": null, "e": 1580, "s": 1543, "text": "Method 1: Using a list comprehension" }, { "code": null, "e": 1642, "s": 1580, "text": "a, b, c, d = [int(x) for x in input().split()]\nprint(a*b*c*d)" }, { "code": null, "e": 1675, "s": 1642, "text": "Method 2: Using the map function" }, { "code": null, "e": 1729, "s": 1675, "text": "a, b, c, d = map(int, input().split())\nprint(a*b*c*d)" }, { "code": null, "e": 1812, "s": 1729, "text": "Another way of doing above problem is using stdin and stdout which is much faster." }, { "code": null, "e": 1864, "s": 1812, "text": "Method 1a: List comprehension with stdin and stdout" }, { "code": null, "e": 1993, "s": 1864, "text": "from sys import stdin, stdout\na, b, c, d = [int(x) for x in stdin.readline().rstrip().split()]\nstdout.write(str(a*b*c*d) + \"\\n\")" }, { "code": null, "e": 2178, "s": 1993, "text": "Let’s look at another problem from the competitive programming where we can test our input and output methods on the problems. The problem is called INTEST-Enormous Input Test on SPOJ." }, { "code": null, "e": 2184, "s": 2178, "text": "Input" }, { "code": null, "e": 2332, "s": 2184, "text": "The input begins with two positive integers n k (n, k<=107). The next n lines of input contain one positive integer ti, not greater than 109, each." }, { "code": null, "e": 2339, "s": 2332, "text": "Output" }, { "code": null, "e": 2423, "s": 2339, "text": "Write a single integer to output, denoting how many integers ti are divisible by k." }, { "code": null, "e": 2429, "s": 2423, "text": "Where" }, { "code": null, "e": 2591, "s": 2429, "text": "INPUT: The input begins with two positive integers n and k (where- n, k <=10). The next lines of input contain one positive integer t not greater than 10*9 each." }, { "code": null, "e": 2753, "s": 2591, "text": "INPUT: The input begins with two positive integers n and k (where- n, k <=10). The next lines of input contain one positive integer t not greater than 10*9 each." }, { "code": null, "e": 2827, "s": 2753, "text": "OUTPUT: A single integer denoting how many integers t are divisible by k." }, { "code": null, "e": 2901, "s": 2827, "text": "OUTPUT: A single integer denoting how many integers t are divisible by k." }, { "code": null, "e": 2913, "s": 2901, "text": "For example" }, { "code": null, "e": 2958, "s": 2913, "text": "Input\n7 3\n1\n51\n966369\n7\n9\n999996\n11\nOutput\n4" }, { "code": null, "e": 2967, "s": 2958, "text": "Method 1" }, { "code": null, "e": 3036, "s": 2967, "text": "One way to solve above problem is below though not the efficient one" }, { "code": null, "e": 3239, "s": 3036, "text": "def main():\n n, k = [int(c) for c in input().split()]\n cnt = 0\n for _ in range(n):\n t = int(input())\n if t % k == 0:\n cnt += 1\n print(cnt)\n\nif __name__ == \"__main__\":\n main()" }, { "code": null, "e": 3248, "s": 3239, "text": "Method 2" }, { "code": null, "e": 3388, "s": 3248, "text": "Another more efficient way of solving above problem is using stdin and stdout. Below program runs much faster compared to the previous one." }, { "code": null, "e": 3645, "s": 3388, "text": "from sys import stdin, stdout\n\ndef main():\n n, k = [int(c) for c in input().split()]\n cnt = 0\n for _ in range(n):\n t = int(stdin.readline())\n if t % k == 0:\n cnt += 1\n stdout.write(str(cnt))\n\nif __name__ == \"__main__\":\n main()\n\n" }, { "code": null, "e": 3654, "s": 3645, "text": "Method 3" }, { "code": null, "e": 3883, "s": 3654, "text": "Another way to solve above problem which much faster than the previous two mentioned above is by using stdin and stdout (very similar to the way we used in method 2) however, read the whole input at once and load it into a list." }, { "code": null, "e": 4164, "s": 3883, "text": "def main():\n for sys import stdin, stdout\n n, k = stdin.readline().split()\n n = int(n)\n k = int(k)\n\n cnt = 0\n lines = stdin.readlines()\n for line in lines:\n if int(line) % k == 0:\n cnt += 1\n stdout.write(str(cnt))\n\nif __name__ == \"__main__\":\n main()" } ]
How to Build a Simple Augmented Reality Android App? - GeeksforGeeks
22 Jun, 2021 Augmented Reality has crossed a long way from Sci-fi Stories to Scientific reality. With this speed of technical advancement, it’s probably not very far when we can also manipulate digital data in this real physical world as Tony Stark did in his lab. When we superimpose information like sound, text, image to our real-world and also can interact with it through a special medium, that is Augmented Reality. The world-famous “Pokemon GO” app is just another example of an Augmented Reality Application. Let’s make a very simple Augmented Reality App in Android Studio using JAVA. This app shows a custom made or downloaded 3d model using the phone camera. A sample GIF is given below to get an idea about what we are going to do in this article. ARCore: According to Google, ARCore is a platform for Augmented Reality. ARCore actually helps the phone to sense its environment and interact with the world. ARCore mainly uses 3 key principles – Motion Tracking, Understanding Environment, and Light Estimation. Here is a list provided by Google, of the phones that supports ARCore. Sceneform: According to Google, Sceneform is a 3d framework, that helps the developers to build ARCore apps without knowing a lot about OpenGL. Sceneform comes with a lot of features like checking for camera permission, manipulating 3d assets, and a lot more. Step 1: Create a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note: Select Java as the programming language. Note the location where the app is getting saved because we need that path later. Choose ‘Minimum SDK‘ as ‘API 24: Android 7.0(Nougat)‘ Step 2: Getting the 3D Model Sceneform 1.16.0 supports only glTF files. glTF means GL Transmission Format. Now .glb files are a binary version of the GL Transmission Format. These types of 3d model files are used in VR, AR because it supports motion and animation. For the 3d model, you have to get a .glb file. There are two ways, you can grab a 3d model, download from the web, or make one yourself. If you want to download it from the web, go to this awesome 3d models repository by Google, poly, and search for any glb file. Download any one of them for your project. OR, get a 3D computer graphics software and make a 3d model yourself. I used Blender which is completely free to download and made a 3d model of GEEKS FOR GEEKS text. Get this file from here. Export the model as a .glb file to a specific folder and the filename must contain small_letters or numbers. Come back to Android Studio. On the left panel, Right-Click on res directory. Go to the New > Android Resource Directory. A window will pop up. Change the Resource Type: to Raw. Click OK. A raw folder is generated, under the res directory. Copy the .glb file from that directory where you saved it and paste it under the raw folder. Step 3: Downloading and Setting up SceneForm 1.16.0 Well, for AR apps we need Sceneform SDK. SceneForm 1.15.0 is very famous but recently, there are some plugin errors I faced while getting the “Google Sceneform Tools (Beta)” plugin in the latest Android Studio 4.1. So here I am, using the Sceneform 1.16.0 SDK and setting it up manually. Go to this GitHub link. Download the “sceneform-android-sdk-1.16.0.zip” file. Extract the ‘sceneformsrc‘ and ‘sceneformux‘ folders, where you created your project. (“E:\android\ARApp” for me) Go the Android Studio Go to Gradle Scripts > settings.gradle(Project Settings) Add these lines: // this will add sceneformsrc folder into your project include ‘:sceneform’ project(‘:sceneform’).projectDir = new File(‘sceneformsrc/sceneform’) // this will add sceneformux folder into your project include ‘:sceneformux’ project(‘:sceneformux’).projectDir = new File(‘sceneformux/ux’) After that go to Gradle Scripts > build.gradle(Module:app) Add this line inside the dependencies block. api project(“:sceneformux”) Then in the same file inside the “android” block and just after “buildTypes” block add these lines (if it’s not already there): // to support java 8 in your project compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } After all, these changes click ‘Sync Now‘ on the pop-up above. Now the Android file structure will look like this. Then go to the app > manifests > AndroidManifest.xml Add these lines before the “application” block: XML <!--This permits the user to access Camera--><uses-permission android:name="android.permission.CAMERA" /> <!--This helps to check a specific feature in the phone's hardware, here it is OpenGlES version. Sceneform needs OpenGLES Version 3.0 or later--><uses-feature android:glEsVersion="0x00030000" android:required="true" /> <!--Indicates that this app requires Google Play Services for AR. Limits app visibility in the Google Play Store to ARCore supported devices--><uses-feature android:name="android.hardware.camera.ar" android:required="true"/> After that add this line before the “activity” block. XML <!-- ARCore need to be installed, as the app does not include any non-AR features. For an "AR Optional" app, specify "optional" instead of "required".--><meta-data android:name="com.google.ar.core" android:value="required" /> Below is the complete code for the AndroidManifest.xml file. XML <?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.wheic.arapp"> <!--This helps to permit the user to access Camera--> <uses-permission android:name="android.permission.CAMERA" /> <!--This helps to check a specific feature in the phone's hardware, here it is OpenGl ES version 3--> <uses-feature android:glEsVersion="0x00030000" android:required="true" /> <!--Here it is checking for AR feature in phone camera--> <uses-feature android:name="android.hardware.camera.ar" android:required="true" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/Theme.ARApp"> <meta-data android:name="com.google.ar.core" android:value="required" /> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Step 4: Error Correction Now comes a little boring part. The downloaded folders sceneformsrc and sceneformux contains some java file, that imports the java classes from an older android.support. So, now if you build the project you will see a lot of errors because of that. What you can do now is to migrate your project to the new Androidx. Now, you can find a way to migrate your whole project to Androidx or you can change the imports manually one by one. I know this is boring, but good things come to those who wait, right? Go to Build > Rebuild Project You’ll find loads of errors. So down in the ‘Build’ section double-click on the package import error. A code will open with the error section highlighted. You need to change only three types of import path, given below, whenever you see the first-one change it to second-one:android.support.annotation. -> androidx.annotation.androidx.core.app -> androidx.fragment.app.android.support.v7.widget. -> androidx.appcompat.widget. android.support.annotation. -> androidx.annotation. androidx.core.app -> androidx.fragment.app. android.support.v7.widget. -> androidx.appcompat.widget. You have to continue this till there are no more errors. Step 5: Working with the activity_main.xml file Go to the res > layout > activity_main.xml file. Here is the code of that XML file: XML <?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <!--This is the fragment that will be used as AR camera--> <fragment android:id="@+id/arCameraArea" android:name="com.google.ar.sceneform.ux.ArFragment" android:layout_width="match_parent" android:layout_height="match_parent" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout> ArFragment contains a lot of features itself like it asks you to download ARCore if it’s already not installed in your phone or like it asks for the camera permission if it’s not already granted. So ArFragment is the best thing to use here. After writing this code, the App UI will look like this: Step 6: Working with MainActivity.java file Go to java > com.wheic.arapp(your’s may differ) > MainActivity.java In the MainActivity class, first, we have to make an object of ArFragment. Java // object of ArFragment Classprivate ArFragment arCam; Now, let’s create a hardware check function outside the onCreate() function. This function will check whether your phone’s hardware meets all the systemic requirements to run this AR App. It’s going to check:Is the API version of the running Android >= 24 that means Android Nougat 7.0Is the OpenGL version >= 3.0 Is the API version of the running Android >= 24 that means Android Nougat 7.0 Is the OpenGL version >= 3.0 Having these is mandatory to run AR Applications using ARCore and Sceneform. Here is the code of that function: Java public static boolean checkSystemSupport(Activity activity) { // checking whether the API version of the running Android >= 24 // that means Android Nougat 7.0 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { String openGlVersion = ((ActivityManager) Objects.requireNonNull(activity.getSystemService(Context.ACTIVITY_SERVICE))).getDeviceConfigurationInfo().getGlEsVersion(); // checking whether the OpenGL version >= 3.0 if (Double.parseDouble(openGlVersion) >= 3.0) { return true; } else { Toast.makeText(activity, "App needs OpenGl Version 3.0 or later", Toast.LENGTH_SHORT).show(); activity.finish(); return false; } } else { Toast.makeText(activity, "App does not support required Build Version", Toast.LENGTH_SHORT).show(); activity.finish(); return false; }} Inside the onCreate() function first, we need to check the phone’s hardware. If it returns true, then the rest of the function will execute. Now the ArFragment is linked up with its respective id used in the activity_main.xml. Java // ArFragment is linked up with its respective id used in the activity_main.xmlarCam = (ArFragment) getSupportFragmentManager().findFragmentById(R.id.arCameraArea); An onTapListener is called, to show the 3d model, when we tap on the screen. Inside the setOnTapArPlaneListener, an Anchor object is created. Anchor actually helps to bring virtual objects on the screen and make them stay at the same position and orientation in the space. Now a ModelRenderable class is used with a bunch of functions. This class is used to render the downloaded or created 3d model by attaching it to an AnchorNode.setSource() function helps to get the source of the 3d model.setIsFilamentGltf() function checks whether it is a glb file.build() function renders the model.A function is called inside thenAccept() function to receive the model by attaching an AnchorNode with the ModelRenderable.exceptionally() function throws an exception if something goes wrong while building the model. setSource() function helps to get the source of the 3d model. setIsFilamentGltf() function checks whether it is a glb file. build() function renders the model. A function is called inside thenAccept() function to receive the model by attaching an AnchorNode with the ModelRenderable. exceptionally() function throws an exception if something goes wrong while building the model. Java arCam.setOnTapArPlaneListener((hitResult, plane, motionEvent) -> { clickNo++; // the 3d model comes to the scene only the first time we tap the screen if (clickNo == 1) { Anchor anchor = hitResult.createAnchor(); ModelRenderable.builder() .setSource(this, R.raw.gfg_gold_text_stand_2) .setIsFilamentGltf(true) .build() .thenAccept(modelRenderable -> addModel(anchor, modelRenderable)) .exceptionally(throwable -> { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage("Something is not right" + throwable.getMessage()).show(); return null; }); }}); Now, let’s see what’s in the addModel() function:It takes two parameters, the first one is Anchor and the other one is ModelRenderable.An AnchorNode object is created. It is the root node of the scene. AnchorNode automatically positioned in the world, based on the Anchor.TransformableNode helps the user to interact with the 3d model, like changing position, resize, rotate, etc. It takes two parameters, the first one is Anchor and the other one is ModelRenderable. An AnchorNode object is created. It is the root node of the scene. AnchorNode automatically positioned in the world, based on the Anchor. TransformableNode helps the user to interact with the 3d model, like changing position, resize, rotate, etc. Java private void addModel(Anchor anchor, ModelRenderable modelRenderable) { // Creating a AnchorNode with a specific anchor AnchorNode anchorNode = new AnchorNode(anchor); // attaching the anchorNode with the ArFragment anchorNode.setParent(arCam.getArSceneView().getScene()); TransformableNode transform = new TransformableNode(arCam.getTransformationSystem()); // attaching the anchorNode with the TransformableNode transform.setParent(anchorNode); // attaching the 3d model with the TransformableNode that is // already attached with the node transform.setRenderable(modelRenderable); transform.select();} Here is the complete code of the MainActivity.java file. Comments are added inside the code to understand the code in more detail. Java import android.app.Activity;import android.app.ActivityManager;import android.app.AlertDialog;import android.content.Context;import android.os.Build;import android.os.Bundle;import android.widget.Toast;import androidx.appcompat.app.AppCompatActivity;import com.google.ar.core.Anchor;import com.google.ar.sceneform.AnchorNode;import com.google.ar.sceneform.rendering.ModelRenderable;import com.google.ar.sceneform.ux.ArFragment;import com.google.ar.sceneform.ux.TransformableNode;import java.util.Objects; public class MainActivity extends AppCompatActivity { // object of ArFragment Class private ArFragment arCam; // helps to render the 3d model // only once when we tap the screen private int clickNo = 0; public static boolean checkSystemSupport(Activity activity) { // checking whether the API version of the running Android >= 24 // that means Android Nougat 7.0 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { String openGlVersion = ((ActivityManager) Objects.requireNonNull(activity.getSystemService(Context.ACTIVITY_SERVICE))).getDeviceConfigurationInfo().getGlEsVersion(); // checking whether the OpenGL version >= 3.0 if (Double.parseDouble(openGlVersion) >= 3.0) { return true; } else { Toast.makeText(activity, "App needs OpenGl Version 3.0 or later", Toast.LENGTH_SHORT).show(); activity.finish(); return false; } } else { Toast.makeText(activity, "App does not support required Build Version", Toast.LENGTH_SHORT).show(); activity.finish(); return false; } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (checkSystemSupport(this)) { // ArFragment is linked up with its respective id used in the activity_main.xml arCam = (ArFragment) getSupportFragmentManager().findFragmentById(R.id.arCameraArea); arCam.setOnTapArPlaneListener((hitResult, plane, motionEvent) -> { clickNo++; // the 3d model comes to the scene only // when clickNo is one that means once if (clickNo == 1) { Anchor anchor = hitResult.createAnchor(); ModelRenderable.builder() .setSource(this, R.raw.gfg_gold_text_stand_2) .setIsFilamentGltf(true) .build() .thenAccept(modelRenderable -> addModel(anchor, modelRenderable)) .exceptionally(throwable -> { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage("Something is not right" + throwable.getMessage()).show(); return null; }); } }); } else { return; } } private void addModel(Anchor anchor, ModelRenderable modelRenderable) { // Creating a AnchorNode with a specific anchor AnchorNode anchorNode = new AnchorNode(anchor); // attaching the anchorNode with the ArFragment anchorNode.setParent(arCam.getArSceneView().getScene()); // attaching the anchorNode with the TransformableNode TransformableNode model = new TransformableNode(arCam.getTransformationSystem()); model.setParent(anchorNode); // attaching the 3d model with the TransformableNode // that is already attached with the node model.setRenderable(modelRenderable); model.select(); }} Output: Run on a Physical Device Finally, we built a simple Augmented Reality app using Android Studio. You can check this project in this GitHub link. akshaysingh98088 android Technical Scripter 2020 Advanced Computer Subject Android Java Technical Scripter Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Copying Files to and from Docker Containers Principal Component Analysis with Python Classifying data using Support Vector Machines(SVMs) in Python Fuzzy Logic | Introduction Q-Learning in Python MVVM (Model View ViewModel) Architecture Pattern in Android Bottom Navigation Bar in Android Android Architecture How to Create and Add Data to SQLite Database in Android? Broadcast Receiver in Android With Example
[ { "code": null, "e": 24252, "s": 24224, "text": "\n22 Jun, 2021" }, { "code": null, "e": 24999, "s": 24252, "text": "Augmented Reality has crossed a long way from Sci-fi Stories to Scientific reality. With this speed of technical advancement, it’s probably not very far when we can also manipulate digital data in this real physical world as Tony Stark did in his lab. When we superimpose information like sound, text, image to our real-world and also can interact with it through a special medium, that is Augmented Reality. The world-famous “Pokemon GO” app is just another example of an Augmented Reality Application. Let’s make a very simple Augmented Reality App in Android Studio using JAVA. This app shows a custom made or downloaded 3d model using the phone camera. A sample GIF is given below to get an idea about what we are going to do in this article." }, { "code": null, "e": 25333, "s": 24999, "text": "ARCore: According to Google, ARCore is a platform for Augmented Reality. ARCore actually helps the phone to sense its environment and interact with the world. ARCore mainly uses 3 key principles – Motion Tracking, Understanding Environment, and Light Estimation. Here is a list provided by Google, of the phones that supports ARCore." }, { "code": null, "e": 25593, "s": 25333, "text": "Sceneform: According to Google, Sceneform is a 3d framework, that helps the developers to build ARCore apps without knowing a lot about OpenGL. Sceneform comes with a lot of features like checking for camera permission, manipulating 3d assets, and a lot more." }, { "code": null, "e": 25622, "s": 25593, "text": "Step 1: Create a New Project" }, { "code": null, "e": 25734, "s": 25622, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. " }, { "code": null, "e": 25741, "s": 25734, "text": "Note: " }, { "code": null, "e": 25782, "s": 25741, "text": "Select Java as the programming language." }, { "code": null, "e": 25864, "s": 25782, "text": "Note the location where the app is getting saved because we need that path later." }, { "code": null, "e": 25918, "s": 25864, "text": "Choose ‘Minimum SDK‘ as ‘API 24: Android 7.0(Nougat)‘" }, { "code": null, "e": 25947, "s": 25918, "text": "Step 2: Getting the 3D Model" }, { "code": null, "e": 26184, "s": 25947, "text": "Sceneform 1.16.0 supports only glTF files. glTF means GL Transmission Format. Now .glb files are a binary version of the GL Transmission Format. These types of 3d model files are used in VR, AR because it supports motion and animation." }, { "code": null, "e": 26231, "s": 26184, "text": "For the 3d model, you have to get a .glb file." }, { "code": null, "e": 26321, "s": 26231, "text": "There are two ways, you can grab a 3d model, download from the web, or make one yourself." }, { "code": null, "e": 26491, "s": 26321, "text": "If you want to download it from the web, go to this awesome 3d models repository by Google, poly, and search for any glb file. Download any one of them for your project." }, { "code": null, "e": 26561, "s": 26491, "text": "OR, get a 3D computer graphics software and make a 3d model yourself." }, { "code": null, "e": 26683, "s": 26561, "text": "I used Blender which is completely free to download and made a 3d model of GEEKS FOR GEEKS text. Get this file from here." }, { "code": null, "e": 26792, "s": 26683, "text": "Export the model as a .glb file to a specific folder and the filename must contain small_letters or numbers." }, { "code": null, "e": 26821, "s": 26792, "text": "Come back to Android Studio." }, { "code": null, "e": 26936, "s": 26821, "text": "On the left panel, Right-Click on res directory. Go to the New > Android Resource Directory. A window will pop up." }, { "code": null, "e": 27032, "s": 26936, "text": "Change the Resource Type: to Raw. Click OK. A raw folder is generated, under the res directory." }, { "code": null, "e": 27125, "s": 27032, "text": "Copy the .glb file from that directory where you saved it and paste it under the raw folder." }, { "code": null, "e": 27177, "s": 27125, "text": "Step 3: Downloading and Setting up SceneForm 1.16.0" }, { "code": null, "e": 27465, "s": 27177, "text": "Well, for AR apps we need Sceneform SDK. SceneForm 1.15.0 is very famous but recently, there are some plugin errors I faced while getting the “Google Sceneform Tools (Beta)” plugin in the latest Android Studio 4.1. So here I am, using the Sceneform 1.16.0 SDK and setting it up manually." }, { "code": null, "e": 27489, "s": 27465, "text": "Go to this GitHub link." }, { "code": null, "e": 27543, "s": 27489, "text": "Download the “sceneform-android-sdk-1.16.0.zip” file." }, { "code": null, "e": 27657, "s": 27543, "text": "Extract the ‘sceneformsrc‘ and ‘sceneformux‘ folders, where you created your project. (“E:\\android\\ARApp” for me)" }, { "code": null, "e": 27679, "s": 27657, "text": "Go the Android Studio" }, { "code": null, "e": 27736, "s": 27679, "text": "Go to Gradle Scripts > settings.gradle(Project Settings)" }, { "code": null, "e": 27753, "s": 27736, "text": "Add these lines:" }, { "code": null, "e": 27808, "s": 27753, "text": "// this will add sceneformsrc folder into your project" }, { "code": null, "e": 27829, "s": 27808, "text": "include ‘:sceneform’" }, { "code": null, "e": 27899, "s": 27829, "text": "project(‘:sceneform’).projectDir = new File(‘sceneformsrc/sceneform’)" }, { "code": null, "e": 27955, "s": 27901, "text": "// this will add sceneformux folder into your project" }, { "code": null, "e": 27978, "s": 27955, "text": "include ‘:sceneformux’" }, { "code": null, "e": 28042, "s": 27978, "text": "project(‘:sceneformux’).projectDir = new File(‘sceneformux/ux’)" }, { "code": null, "e": 28101, "s": 28042, "text": "After that go to Gradle Scripts > build.gradle(Module:app)" }, { "code": null, "e": 28146, "s": 28101, "text": "Add this line inside the dependencies block." }, { "code": null, "e": 28174, "s": 28146, "text": "api project(“:sceneformux”)" }, { "code": null, "e": 28302, "s": 28174, "text": "Then in the same file inside the “android” block and just after “buildTypes” block add these lines (if it’s not already there):" }, { "code": null, "e": 28339, "s": 28302, "text": "// to support java 8 in your project" }, { "code": null, "e": 28356, "s": 28339, "text": "compileOptions {" }, { "code": null, "e": 28407, "s": 28356, "text": " sourceCompatibility JavaVersion.VERSION_1_8" }, { "code": null, "e": 28458, "s": 28407, "text": " targetCompatibility JavaVersion.VERSION_1_8" }, { "code": null, "e": 28460, "s": 28458, "text": "}" }, { "code": null, "e": 28575, "s": 28460, "text": "After all, these changes click ‘Sync Now‘ on the pop-up above. Now the Android file structure will look like this." }, { "code": null, "e": 28628, "s": 28575, "text": "Then go to the app > manifests > AndroidManifest.xml" }, { "code": null, "e": 28676, "s": 28628, "text": "Add these lines before the “application” block:" }, { "code": null, "e": 28680, "s": 28676, "text": "XML" }, { "code": "<!--This permits the user to access Camera--><uses-permission android:name=\"android.permission.CAMERA\" /> <!--This helps to check a specific feature in the phone's hardware, here it is OpenGlES version. Sceneform needs OpenGLES Version 3.0 or later--><uses-feature android:glEsVersion=\"0x00030000\" android:required=\"true\" /> <!--Indicates that this app requires Google Play Services for AR. Limits app visibility in the Google Play Store to ARCore supported devices--><uses-feature android:name=\"android.hardware.camera.ar\" android:required=\"true\"/>", "e": 29236, "s": 28680, "text": null }, { "code": null, "e": 29291, "s": 29236, "text": " After that add this line before the “activity” block." }, { "code": null, "e": 29295, "s": 29291, "text": "XML" }, { "code": "<!-- ARCore need to be installed, as the app does not include any non-AR features. For an \"AR Optional\" app, specify \"optional\" instead of \"required\".--><meta-data android:name=\"com.google.ar.core\" android:value=\"required\" />", "e": 29525, "s": 29295, "text": null }, { "code": null, "e": 29589, "s": 29525, "text": " Below is the complete code for the AndroidManifest.xml file. " }, { "code": null, "e": 29593, "s": 29589, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"com.wheic.arapp\"> <!--This helps to permit the user to access Camera--> <uses-permission android:name=\"android.permission.CAMERA\" /> <!--This helps to check a specific feature in the phone's hardware, here it is OpenGl ES version 3--> <uses-feature android:glEsVersion=\"0x00030000\" android:required=\"true\" /> <!--Here it is checking for AR feature in phone camera--> <uses-feature android:name=\"android.hardware.camera.ar\" android:required=\"true\" /> <application android:allowBackup=\"true\" android:icon=\"@mipmap/ic_launcher\" android:label=\"@string/app_name\" android:roundIcon=\"@mipmap/ic_launcher_round\" android:supportsRtl=\"true\" android:theme=\"@style/Theme.ARApp\"> <meta-data android:name=\"com.google.ar.core\" android:value=\"required\" /> <activity android:name=\".MainActivity\"> <intent-filter> <action android:name=\"android.intent.action.MAIN\" /> <category android:name=\"android.intent.category.LAUNCHER\" /> </intent-filter> </activity> </application> </manifest>", "e": 30889, "s": 29593, "text": null }, { "code": null, "e": 30915, "s": 30889, "text": " Step 4: Error Correction" }, { "code": null, "e": 31419, "s": 30915, "text": "Now comes a little boring part. The downloaded folders sceneformsrc and sceneformux contains some java file, that imports the java classes from an older android.support. So, now if you build the project you will see a lot of errors because of that. What you can do now is to migrate your project to the new Androidx. Now, you can find a way to migrate your whole project to Androidx or you can change the imports manually one by one. I know this is boring, but good things come to those who wait, right?" }, { "code": null, "e": 31449, "s": 31419, "text": "Go to Build > Rebuild Project" }, { "code": null, "e": 31604, "s": 31449, "text": "You’ll find loads of errors. So down in the ‘Build’ section double-click on the package import error. A code will open with the error section highlighted." }, { "code": null, "e": 31875, "s": 31604, "text": "You need to change only three types of import path, given below, whenever you see the first-one change it to second-one:android.support.annotation. -> androidx.annotation.androidx.core.app -> androidx.fragment.app.android.support.v7.widget. -> androidx.appcompat.widget." }, { "code": null, "e": 31927, "s": 31875, "text": "android.support.annotation. -> androidx.annotation." }, { "code": null, "e": 31971, "s": 31927, "text": "androidx.core.app -> androidx.fragment.app." }, { "code": null, "e": 32028, "s": 31971, "text": "android.support.v7.widget. -> androidx.appcompat.widget." }, { "code": null, "e": 32085, "s": 32028, "text": "You have to continue this till there are no more errors." }, { "code": null, "e": 32133, "s": 32085, "text": "Step 5: Working with the activity_main.xml file" }, { "code": null, "e": 32182, "s": 32133, "text": "Go to the res > layout > activity_main.xml file." }, { "code": null, "e": 32217, "s": 32182, "text": "Here is the code of that XML file:" }, { "code": null, "e": 32221, "s": 32217, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <!--This is the fragment that will be used as AR camera--> <fragment android:id=\"@+id/arCameraArea\" android:name=\"com.google.ar.sceneform.ux.ArFragment\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" /> </androidx.constraintlayout.widget.ConstraintLayout>", "e": 33113, "s": 32221, "text": null }, { "code": null, "e": 33354, "s": 33113, "text": "ArFragment contains a lot of features itself like it asks you to download ARCore if it’s already not installed in your phone or like it asks for the camera permission if it’s not already granted. So ArFragment is the best thing to use here." }, { "code": null, "e": 33411, "s": 33354, "text": "After writing this code, the App UI will look like this:" }, { "code": null, "e": 33455, "s": 33411, "text": "Step 6: Working with MainActivity.java file" }, { "code": null, "e": 33523, "s": 33455, "text": "Go to java > com.wheic.arapp(your’s may differ) > MainActivity.java" }, { "code": null, "e": 33598, "s": 33523, "text": "In the MainActivity class, first, we have to make an object of ArFragment." }, { "code": null, "e": 33603, "s": 33598, "text": "Java" }, { "code": "// object of ArFragment Classprivate ArFragment arCam;", "e": 33658, "s": 33603, "text": null }, { "code": null, "e": 33972, "s": 33658, "text": "Now, let’s create a hardware check function outside the onCreate() function. This function will check whether your phone’s hardware meets all the systemic requirements to run this AR App. It’s going to check:Is the API version of the running Android >= 24 that means Android Nougat 7.0Is the OpenGL version >= 3.0" }, { "code": null, "e": 34050, "s": 33972, "text": "Is the API version of the running Android >= 24 that means Android Nougat 7.0" }, { "code": null, "e": 34079, "s": 34050, "text": "Is the OpenGL version >= 3.0" }, { "code": null, "e": 34191, "s": 34079, "text": "Having these is mandatory to run AR Applications using ARCore and Sceneform. Here is the code of that function:" }, { "code": null, "e": 34196, "s": 34191, "text": "Java" }, { "code": "public static boolean checkSystemSupport(Activity activity) { // checking whether the API version of the running Android >= 24 // that means Android Nougat 7.0 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { String openGlVersion = ((ActivityManager) Objects.requireNonNull(activity.getSystemService(Context.ACTIVITY_SERVICE))).getDeviceConfigurationInfo().getGlEsVersion(); // checking whether the OpenGL version >= 3.0 if (Double.parseDouble(openGlVersion) >= 3.0) { return true; } else { Toast.makeText(activity, \"App needs OpenGl Version 3.0 or later\", Toast.LENGTH_SHORT).show(); activity.finish(); return false; } } else { Toast.makeText(activity, \"App does not support required Build Version\", Toast.LENGTH_SHORT).show(); activity.finish(); return false; }}", "e": 35086, "s": 34196, "text": null }, { "code": null, "e": 35227, "s": 35086, "text": "Inside the onCreate() function first, we need to check the phone’s hardware. If it returns true, then the rest of the function will execute." }, { "code": null, "e": 35313, "s": 35227, "text": "Now the ArFragment is linked up with its respective id used in the activity_main.xml." }, { "code": null, "e": 35318, "s": 35313, "text": "Java" }, { "code": "// ArFragment is linked up with its respective id used in the activity_main.xmlarCam = (ArFragment) getSupportFragmentManager().findFragmentById(R.id.arCameraArea);", "e": 35483, "s": 35318, "text": null }, { "code": null, "e": 35560, "s": 35483, "text": "An onTapListener is called, to show the 3d model, when we tap on the screen." }, { "code": null, "e": 35756, "s": 35560, "text": "Inside the setOnTapArPlaneListener, an Anchor object is created. Anchor actually helps to bring virtual objects on the screen and make them stay at the same position and orientation in the space." }, { "code": null, "e": 36291, "s": 35756, "text": "Now a ModelRenderable class is used with a bunch of functions. This class is used to render the downloaded or created 3d model by attaching it to an AnchorNode.setSource() function helps to get the source of the 3d model.setIsFilamentGltf() function checks whether it is a glb file.build() function renders the model.A function is called inside thenAccept() function to receive the model by attaching an AnchorNode with the ModelRenderable.exceptionally() function throws an exception if something goes wrong while building the model." }, { "code": null, "e": 36353, "s": 36291, "text": "setSource() function helps to get the source of the 3d model." }, { "code": null, "e": 36415, "s": 36353, "text": "setIsFilamentGltf() function checks whether it is a glb file." }, { "code": null, "e": 36451, "s": 36415, "text": "build() function renders the model." }, { "code": null, "e": 36575, "s": 36451, "text": "A function is called inside thenAccept() function to receive the model by attaching an AnchorNode with the ModelRenderable." }, { "code": null, "e": 36670, "s": 36575, "text": "exceptionally() function throws an exception if something goes wrong while building the model." }, { "code": null, "e": 36675, "s": 36670, "text": "Java" }, { "code": "arCam.setOnTapArPlaneListener((hitResult, plane, motionEvent) -> { clickNo++; // the 3d model comes to the scene only the first time we tap the screen if (clickNo == 1) { Anchor anchor = hitResult.createAnchor(); ModelRenderable.builder() .setSource(this, R.raw.gfg_gold_text_stand_2) .setIsFilamentGltf(true) .build() .thenAccept(modelRenderable -> addModel(anchor, modelRenderable)) .exceptionally(throwable -> { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(\"Something is not right\" + throwable.getMessage()).show(); return null; }); }});", "e": 37434, "s": 36675, "text": null }, { "code": null, "e": 37815, "s": 37434, "text": "Now, let’s see what’s in the addModel() function:It takes two parameters, the first one is Anchor and the other one is ModelRenderable.An AnchorNode object is created. It is the root node of the scene. AnchorNode automatically positioned in the world, based on the Anchor.TransformableNode helps the user to interact with the 3d model, like changing position, resize, rotate, etc." }, { "code": null, "e": 37902, "s": 37815, "text": "It takes two parameters, the first one is Anchor and the other one is ModelRenderable." }, { "code": null, "e": 38040, "s": 37902, "text": "An AnchorNode object is created. It is the root node of the scene. AnchorNode automatically positioned in the world, based on the Anchor." }, { "code": null, "e": 38149, "s": 38040, "text": "TransformableNode helps the user to interact with the 3d model, like changing position, resize, rotate, etc." }, { "code": null, "e": 38154, "s": 38149, "text": "Java" }, { "code": "private void addModel(Anchor anchor, ModelRenderable modelRenderable) { // Creating a AnchorNode with a specific anchor AnchorNode anchorNode = new AnchorNode(anchor); // attaching the anchorNode with the ArFragment anchorNode.setParent(arCam.getArSceneView().getScene()); TransformableNode transform = new TransformableNode(arCam.getTransformationSystem()); // attaching the anchorNode with the TransformableNode transform.setParent(anchorNode); // attaching the 3d model with the TransformableNode that is // already attached with the node transform.setRenderable(modelRenderable); transform.select();}", "e": 38820, "s": 38154, "text": null }, { "code": null, "e": 38953, "s": 38820, "text": " Here is the complete code of the MainActivity.java file. Comments are added inside the code to understand the code in more detail. " }, { "code": null, "e": 38958, "s": 38953, "text": "Java" }, { "code": "import android.app.Activity;import android.app.ActivityManager;import android.app.AlertDialog;import android.content.Context;import android.os.Build;import android.os.Bundle;import android.widget.Toast;import androidx.appcompat.app.AppCompatActivity;import com.google.ar.core.Anchor;import com.google.ar.sceneform.AnchorNode;import com.google.ar.sceneform.rendering.ModelRenderable;import com.google.ar.sceneform.ux.ArFragment;import com.google.ar.sceneform.ux.TransformableNode;import java.util.Objects; public class MainActivity extends AppCompatActivity { // object of ArFragment Class private ArFragment arCam; // helps to render the 3d model // only once when we tap the screen private int clickNo = 0; public static boolean checkSystemSupport(Activity activity) { // checking whether the API version of the running Android >= 24 // that means Android Nougat 7.0 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { String openGlVersion = ((ActivityManager) Objects.requireNonNull(activity.getSystemService(Context.ACTIVITY_SERVICE))).getDeviceConfigurationInfo().getGlEsVersion(); // checking whether the OpenGL version >= 3.0 if (Double.parseDouble(openGlVersion) >= 3.0) { return true; } else { Toast.makeText(activity, \"App needs OpenGl Version 3.0 or later\", Toast.LENGTH_SHORT).show(); activity.finish(); return false; } } else { Toast.makeText(activity, \"App does not support required Build Version\", Toast.LENGTH_SHORT).show(); activity.finish(); return false; } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (checkSystemSupport(this)) { // ArFragment is linked up with its respective id used in the activity_main.xml arCam = (ArFragment) getSupportFragmentManager().findFragmentById(R.id.arCameraArea); arCam.setOnTapArPlaneListener((hitResult, plane, motionEvent) -> { clickNo++; // the 3d model comes to the scene only // when clickNo is one that means once if (clickNo == 1) { Anchor anchor = hitResult.createAnchor(); ModelRenderable.builder() .setSource(this, R.raw.gfg_gold_text_stand_2) .setIsFilamentGltf(true) .build() .thenAccept(modelRenderable -> addModel(anchor, modelRenderable)) .exceptionally(throwable -> { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(\"Something is not right\" + throwable.getMessage()).show(); return null; }); } }); } else { return; } } private void addModel(Anchor anchor, ModelRenderable modelRenderable) { // Creating a AnchorNode with a specific anchor AnchorNode anchorNode = new AnchorNode(anchor); // attaching the anchorNode with the ArFragment anchorNode.setParent(arCam.getArSceneView().getScene()); // attaching the anchorNode with the TransformableNode TransformableNode model = new TransformableNode(arCam.getTransformationSystem()); model.setParent(anchorNode); // attaching the 3d model with the TransformableNode // that is already attached with the node model.setRenderable(modelRenderable); model.select(); }}", "e": 42746, "s": 38958, "text": null }, { "code": null, "e": 42780, "s": 42746, "text": " Output: Run on a Physical Device" }, { "code": null, "e": 42899, "s": 42780, "text": "Finally, we built a simple Augmented Reality app using Android Studio. You can check this project in this GitHub link." }, { "code": null, "e": 42918, "s": 42901, "text": "akshaysingh98088" }, { "code": null, "e": 42926, "s": 42918, "text": "android" }, { "code": null, "e": 42950, "s": 42926, "text": "Technical Scripter 2020" }, { "code": null, "e": 42976, "s": 42950, "text": "Advanced Computer Subject" }, { "code": null, "e": 42984, "s": 42976, "text": "Android" }, { "code": null, "e": 42989, "s": 42984, "text": "Java" }, { "code": null, "e": 43008, "s": 42989, "text": "Technical Scripter" }, { "code": null, "e": 43013, "s": 43008, "text": "Java" }, { "code": null, "e": 43021, "s": 43013, "text": "Android" }, { "code": null, "e": 43119, "s": 43021, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 43163, "s": 43119, "text": "Copying Files to and from Docker Containers" }, { "code": null, "e": 43204, "s": 43163, "text": "Principal Component Analysis with Python" }, { "code": null, "e": 43267, "s": 43204, "text": "Classifying data using Support Vector Machines(SVMs) in Python" }, { "code": null, "e": 43294, "s": 43267, "text": "Fuzzy Logic | Introduction" }, { "code": null, "e": 43315, "s": 43294, "text": "Q-Learning in Python" }, { "code": null, "e": 43375, "s": 43315, "text": "MVVM (Model View ViewModel) Architecture Pattern in Android" }, { "code": null, "e": 43408, "s": 43375, "text": "Bottom Navigation Bar in Android" }, { "code": null, "e": 43429, "s": 43408, "text": "Android Architecture" }, { "code": null, "e": 43487, "s": 43429, "text": "How to Create and Add Data to SQLite Database in Android?" } ]
Creating Knockout Application along with Setting up Environment in Visual Studio - GeeksforGeeks
30 Apr, 2019 Setting up Environment –Step 1 : Open Visual Studio and Create ASP.Net Application (Web -> Visual Studio[version]), name it as KOSetup Step 2 : Install jQuery file and knockout.jsfile and Create folder named as Scripts and drag these two files(jQuery and knockout.js) into the Scripts folder Step 3 : Create .aspx page, name it as LearnKO.aspx Step 4 : Create .js page, name it as LearnKO.js Step 5 : Open the “LearnKO.js” file and drag the jQuery file and “knockout.js” library file to the “LearKO.js” Step 6 : Write $(document).ready(function() { }); in LearnKO.js file. The document.ready function is fired when our HTML document object model has been loaded into the browser. Creating Knockout Application – Step 7 : Create a database and a table(named as Student) in it. Step 8 : Create ADO.NET Entity data Model ( Visual C# -> Data), naming it as LearningKO.edmx,Click Add -> Generate from Database -> Select Table as created in the Database -> Untick the last option i.e. Import Selected stored procedures and functions into the entity model -> Name Model Namespace as LearningKOModel, we’ll get certain files in our solution in context and tt files. Step 9 : Write Methods(Code) in .aspx.cs page using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.Services; namespace Setup{ public partial class LearnKO : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } [WebMethod] public static Student[] FetchStudents() { Entities dbEntities = new Entities(); var data = (from item in dbEntities.Students orderby item.StudentId select item).Take(5); return data.ToArray(); } [WebMethod] public static string SaveStudent(Student[] data) { try { var dbContext = new Entities(); var studentList = from dbStududent in dbContext.Students select dbStududent; foreach (Student userDetails in data) { var student = new Student(); if (userDetails != null) { student.StudentId = userDetails.StudentId; student.FirstName = userDetails.FirstName; student.LastName = userDetails.LastName; student.Address = userDetails.Address; student.Age = userDetails.Age; student.Gender = userDetails.Gender; student.Batch = userDetails.Batch; student.Class = userDetails.Class; student.School = userDetails.School; student.Domicile = userDetails.Domicile; } Student stud = (from st in studentList where st.StudentId == student.StudentId select st).FirstOrDefault(); if (stud == null) dbContext.Students.Add(student); dbContext.SaveChanges(); } return "Data saved to database!"; } catch (Exception ex) { return "Error: " + ex.Message; } } [WebMethod] public static string DeleteStudent(Student data) { try { var dbContext = new Entities(); var student = dbContext.Students.FirstOrDefault (userId => userId.StudentId == data.StudentId); if (student != null) { dbContext.Students.Remove(student); dbContext.SaveChanges(); } return "Data deleted from database!"; } catch (Exception ex) { return "Error: " + ex.Message; } } [WebMethod] public static string UpdateStudent(Student data) { try { var dbContext = new Entities(); var student = dbContext.Students.FirstOrDefault (userId => userId.StudentId == data.StudentId); if (student != null) { student.FirstName = data.FirstName; student.LastName = data.LastName; student.Address = data.Address; student.Age = data.Age; student.Gender = data.Gender; student.Batch = data.Batch; student.Class = data.Class; student.School = data.School; student.Domicile = data.Domicile; dbContext.SaveChanges(); } return "Data updated in database!"; } catch (Exception ex) { return "Error: " + ex.Message; } } }} Step 10 : Write Code in .aspx page <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="LearnKO.aspx.cs" Inherits="Setup.LearnKO" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"><head id="Head1" runat="server"> <title>Learning Knockout.js</title> <script src="Scripts/jquery-3.4.0.min.js"></script> <script src="Scripts/knockout-3.5.0.js"></script> <script src="Scripts/LearnKO.js"></script> <link href="Styles/Style.css" rel="stylesheet" /></head><body> <form id="form1" runat="server"> <h2>Add Student</h2> <table style="width:100%;" > <tr> <td>Student ID (int):</td> <td> <input data-bind="value: StudentId" /></td> <!--, valueUpdate:'keypress'--> <td><span data-bind="text: StudentId" /></td> </tr> <tr> <td>First Name :</td> <td> <input data-bind="value: FirstName" /></td> <td ><span data-bind="text: FirstName" /></td> </tr> <tr> <td>Last Name :</td> <td> <input data-bind="value: LastName" /></td> <td><span data-bind="text: LastName" /></td> </tr> <tr> <td>Student Age (int) :</td> <td> <input data-bind="value: Age" /></td> <td><span data-bind="text: Age" /></td> </tr> <tr> <td>Gender :</td> <td> <select data-bind="options: Genders, value: Gender, optionsCaption: 'Select Gender...'"></select></td> <td><span data-bind="text: Gender" /></td> </tr> <tr> <td>Batch :</td> <td> <input data-bind="value: Batch" /></td> <td><span data-bind="text: Batch" /></td> </tr> <tr> <td>Address :</td> <td> <input data-bind="value: Address" /></td> <td><span data-bind="text: Address" /></td> </tr> <tr> <td>Class :</td> <td> <input data-bind="value: Class" /></td> <td><span data-bind="text: Class" /></td> </tr> <tr> <td>School :</td> <td> <input data-bind="value: School" /></td> <td><span data-bind="text: School" /></td> </tr> <tr> <td>Domicile :</td> <td> <select data-bind="options: Domiciles, value: Domicile, optionsCaption: 'Select Domicile...'"></select> </td> <td><span data-bind="text: Domicile" /></td> </tr> <tr> <td colspan="3" > <button type="button" data-bind="click: AddStudent"> Add Student </button> <button type="button" data-bind="click: SaveStudent"> Save Student To Database </button> </td> </tr> </table> <br /> <h2>List of Students</h2> <table style="width:100%;" data-bind="visible: Students().length > 0" border="0" > <tr> <th>Student Id</th> <th>First Name</th> <th>Last Name</th> <th>Age</th> <th>Gender</th> <th>Batch</th> <th>Address</th> <th>Class</th> <th>School</th> <th>Domicile</th> </tr> <tbody data-bind="foreach: Students"> <tr> <td><span data-bind="text: StudentId" /></td> <td> <input data-bind="value: FirstName" /></td> <td> <input data-bind="value: LastName" /></td> <td> <input data-bind="value: Age" /></td> <td> <select data-bind="options: $root.Genders, value: Gender"> </select></td> <td> <input data-bind="value: Batch" /></td> <td> <input data-bind="value: Address" /></td> <td> <input data-bind="value: Class" /></td> <td> <input data-bind="value: School" /></td> <td> <select data-bind="options: $root.Domiciles, value: Domicile"> </select></td> <td><a href="#" data-bind="click: $root.DeleteStudent"> Delete</a></td> <td><a href="#" data-bind="click: $root.UpdateStudent"> Update</a></td> </tr> </tbody> </table> </form></body></html> Step 11 : Write Code in LearnKO.js page /// <reference path="Scripts/jquery-3.4.0.min.js" />/// <reference path="Scripts/knockout-3.5.0.js" />function Student(data) { this.StudentId = ko.observable(data.StudentId); this.FirstName = ko.observable(data.FirstName); this.LastName = ko.observable(data.LastName); this.Age = ko.observable(data.Age); this.Gender = ko.observable(data.Gender); this.Batch = ko.observable(data.Batch); this.Address = ko.observable(data.Address); this.Class = ko.observable(data.Class); this.School = ko.observable(data.School); this.Domicile = ko.observable(data.Domicile); } function StudentViewModel() { var self = this; self.Domiciles = ko.observableArray(['Delhi', 'Outside Delhi']); self.Genders = ko.observableArray(['Male', 'Female']); self.Students = ko.observableArray([]); self.StudentId = ko.observable(); self.FirstName = ko.observable(); self.LastName = ko.observable(); self.Age = ko.observable(); self.Batch = ko.observable(); self.Address = ko.observable(); self.Class = ko.observable(); self.School = ko.observable(); self.Domicile = ko.observable(); self.Gender = ko.observable(); self.AddStudent = function () { self.Students.push(new Student({ StudentId: self.StudentId(), FirstName: self.FirstName(), LastName: self.LastName(), Domicile: self.Domicile(), Age: self.Age(), Batch: self.Batch(), Address: self.Address(), Class: self.Class(), School: self.School(), Gender: self.Gender() })); self.StudentId(""), self.FirstName(""), self.LastName(""), self.Domicile(""), self.Age(""), self.Batch(""), self.Address(""), self.Class(""), self.School(""), self.Gender("") }; self.DeleteStudent = function (student) { $.ajax({ type: "POST", url: 'LearnKO.aspx/DeleteStudent', data: ko.toJSON({ data: student }), contentType: "application/json; charset=utf-8", success: function (result) { alert(result.d); self.Students.remove(student) }, error: function (err) { alert(err.status + " - " + err.statusText); } }); }; self.SaveStudent = function () { $.ajax({ type: "POST", url: 'LearnKO.aspx/SaveStudent', data: ko.toJSON({ data: self.Students }), contentType: "application/json; charset=utf-8", success: function (result) { alert(result.d); }, error: function (err) { alert(err.status + " - " + err.statusText); } }); }; self.UpdateStudent = function (student) { $.ajax({ type: "POST", url: 'LearnKO.aspx/UpdateStudent', data: ko.toJSON({ data: student }), contentType: "application/json; charset=utf-8", success: function(response) { $(".errMsg ul").remove(); var myObject = eval('(' + response.d + ')'); if (myObject > 0) { bindData(); $(".errMsg").append("<ul><li>Data updated successfully</li></ul>"); } else { $(".errMsg").append("<ul><li>Opppps something went wrong.</li></ul>"); } $(".errMsg").show("slow"); clear(); }, error: function (response) { alert(response.status + ' ' + response.statusText); } }); }; $.ajax({ type: "POST", url: 'LearnKO.aspx/FetchStudents', contentType: "application/json; charset=utf-8", dataType: "json", success: function (results) { var students = $.map(results.d, function (item) { return new Student(item) }); self.Students(students); }, error: function (err) { alert(err.status + " - " + err.statusText); } }); } $(document).ready(function () { ko.applyBindings(new StudentViewModel()); }); Step 12 : Press F5 to run the Application Articles Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Time Complexity and Space Complexity Docker - COPY Instruction SQL | Date functions Time complexities of different data structures Implementation of LinkedList in Javascript Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills
[ { "code": null, "e": 24424, "s": 24396, "text": "\n30 Apr, 2019" }, { "code": null, "e": 24559, "s": 24424, "text": "Setting up Environment –Step 1 : Open Visual Studio and Create ASP.Net Application (Web -> Visual Studio[version]), name it as KOSetup" }, { "code": null, "e": 24716, "s": 24559, "text": "Step 2 : Install jQuery file and knockout.jsfile and Create folder named as Scripts and drag these two files(jQuery and knockout.js) into the Scripts folder" }, { "code": null, "e": 24768, "s": 24716, "text": "Step 3 : Create .aspx page, name it as LearnKO.aspx" }, { "code": null, "e": 24816, "s": 24768, "text": "Step 4 : Create .js page, name it as LearnKO.js" }, { "code": null, "e": 24927, "s": 24816, "text": "Step 5 : Open the “LearnKO.js” file and drag the jQuery file and “knockout.js” library file to the “LearKO.js”" }, { "code": null, "e": 25104, "s": 24927, "text": "Step 6 : Write $(document).ready(function() { }); in LearnKO.js file. The document.ready function is fired when our HTML document object model has been loaded into the browser." }, { "code": null, "e": 25136, "s": 25104, "text": "Creating Knockout Application –" }, { "code": null, "e": 25200, "s": 25136, "text": "Step 7 : Create a database and a table(named as Student) in it." }, { "code": null, "e": 25582, "s": 25200, "text": "Step 8 : Create ADO.NET Entity data Model ( Visual C# -> Data), naming it as LearningKO.edmx,Click Add -> Generate from Database -> Select Table as created in the Database -> Untick the last option i.e. Import Selected stored procedures and functions into the entity model -> Name Model Namespace as LearningKOModel, we’ll get certain files in our solution in context and tt files." }, { "code": null, "e": 25628, "s": 25582, "text": "Step 9 : Write Methods(Code) in .aspx.cs page" }, { "code": "using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.Services; namespace Setup{ public partial class LearnKO : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } [WebMethod] public static Student[] FetchStudents() { Entities dbEntities = new Entities(); var data = (from item in dbEntities.Students orderby item.StudentId select item).Take(5); return data.ToArray(); } [WebMethod] public static string SaveStudent(Student[] data) { try { var dbContext = new Entities(); var studentList = from dbStududent in dbContext.Students select dbStududent; foreach (Student userDetails in data) { var student = new Student(); if (userDetails != null) { student.StudentId = userDetails.StudentId; student.FirstName = userDetails.FirstName; student.LastName = userDetails.LastName; student.Address = userDetails.Address; student.Age = userDetails.Age; student.Gender = userDetails.Gender; student.Batch = userDetails.Batch; student.Class = userDetails.Class; student.School = userDetails.School; student.Domicile = userDetails.Domicile; } Student stud = (from st in studentList where st.StudentId == student.StudentId select st).FirstOrDefault(); if (stud == null) dbContext.Students.Add(student); dbContext.SaveChanges(); } return \"Data saved to database!\"; } catch (Exception ex) { return \"Error: \" + ex.Message; } } [WebMethod] public static string DeleteStudent(Student data) { try { var dbContext = new Entities(); var student = dbContext.Students.FirstOrDefault (userId => userId.StudentId == data.StudentId); if (student != null) { dbContext.Students.Remove(student); dbContext.SaveChanges(); } return \"Data deleted from database!\"; } catch (Exception ex) { return \"Error: \" + ex.Message; } } [WebMethod] public static string UpdateStudent(Student data) { try { var dbContext = new Entities(); var student = dbContext.Students.FirstOrDefault (userId => userId.StudentId == data.StudentId); if (student != null) { student.FirstName = data.FirstName; student.LastName = data.LastName; student.Address = data.Address; student.Age = data.Age; student.Gender = data.Gender; student.Batch = data.Batch; student.Class = data.Class; student.School = data.School; student.Domicile = data.Domicile; dbContext.SaveChanges(); } return \"Data updated in database!\"; } catch (Exception ex) { return \"Error: \" + ex.Message; } } }}", "e": 29814, "s": 25628, "text": null }, { "code": null, "e": 29849, "s": 29814, "text": "Step 10 : Write Code in .aspx page" }, { "code": "<%@ Page Language=\"C#\" AutoEventWireup=\"true\" CodeBehind=\"LearnKO.aspx.cs\" Inherits=\"Setup.LearnKO\" %> <!DOCTYPE html> <html xmlns=\"http://www.w3.org/1999/xhtml\"><head id=\"Head1\" runat=\"server\"> <title>Learning Knockout.js</title> <script src=\"Scripts/jquery-3.4.0.min.js\"></script> <script src=\"Scripts/knockout-3.5.0.js\"></script> <script src=\"Scripts/LearnKO.js\"></script> <link href=\"Styles/Style.css\" rel=\"stylesheet\" /></head><body> <form id=\"form1\" runat=\"server\"> <h2>Add Student</h2> <table style=\"width:100%;\" > <tr> <td>Student ID (int):</td> <td> <input data-bind=\"value: StudentId\" /></td> <!--, valueUpdate:'keypress'--> <td><span data-bind=\"text: StudentId\" /></td> </tr> <tr> <td>First Name :</td> <td> <input data-bind=\"value: FirstName\" /></td> <td ><span data-bind=\"text: FirstName\" /></td> </tr> <tr> <td>Last Name :</td> <td> <input data-bind=\"value: LastName\" /></td> <td><span data-bind=\"text: LastName\" /></td> </tr> <tr> <td>Student Age (int) :</td> <td> <input data-bind=\"value: Age\" /></td> <td><span data-bind=\"text: Age\" /></td> </tr> <tr> <td>Gender :</td> <td> <select data-bind=\"options: Genders, value: Gender, optionsCaption: 'Select Gender...'\"></select></td> <td><span data-bind=\"text: Gender\" /></td> </tr> <tr> <td>Batch :</td> <td> <input data-bind=\"value: Batch\" /></td> <td><span data-bind=\"text: Batch\" /></td> </tr> <tr> <td>Address :</td> <td> <input data-bind=\"value: Address\" /></td> <td><span data-bind=\"text: Address\" /></td> </tr> <tr> <td>Class :</td> <td> <input data-bind=\"value: Class\" /></td> <td><span data-bind=\"text: Class\" /></td> </tr> <tr> <td>School :</td> <td> <input data-bind=\"value: School\" /></td> <td><span data-bind=\"text: School\" /></td> </tr> <tr> <td>Domicile :</td> <td> <select data-bind=\"options: Domiciles, value: Domicile, optionsCaption: 'Select Domicile...'\"></select> </td> <td><span data-bind=\"text: Domicile\" /></td> </tr> <tr> <td colspan=\"3\" > <button type=\"button\" data-bind=\"click: AddStudent\"> Add Student </button> <button type=\"button\" data-bind=\"click: SaveStudent\"> Save Student To Database </button> </td> </tr> </table> <br /> <h2>List of Students</h2> <table style=\"width:100%;\" data-bind=\"visible: Students().length > 0\" border=\"0\" > <tr> <th>Student Id</th> <th>First Name</th> <th>Last Name</th> <th>Age</th> <th>Gender</th> <th>Batch</th> <th>Address</th> <th>Class</th> <th>School</th> <th>Domicile</th> </tr> <tbody data-bind=\"foreach: Students\"> <tr> <td><span data-bind=\"text: StudentId\" /></td> <td> <input data-bind=\"value: FirstName\" /></td> <td> <input data-bind=\"value: LastName\" /></td> <td> <input data-bind=\"value: Age\" /></td> <td> <select data-bind=\"options: $root.Genders, value: Gender\"> </select></td> <td> <input data-bind=\"value: Batch\" /></td> <td> <input data-bind=\"value: Address\" /></td> <td> <input data-bind=\"value: Class\" /></td> <td> <input data-bind=\"value: School\" /></td> <td> <select data-bind=\"options: $root.Domiciles, value: Domicile\"> </select></td> <td><a href=\"#\" data-bind=\"click: $root.DeleteStudent\"> Delete</a></td> <td><a href=\"#\" data-bind=\"click: $root.UpdateStudent\"> Update</a></td> </tr> </tbody> </table> </form></body></html>", "e": 35111, "s": 29849, "text": null }, { "code": null, "e": 35151, "s": 35111, "text": "Step 11 : Write Code in LearnKO.js page" }, { "code": "/// <reference path=\"Scripts/jquery-3.4.0.min.js\" />/// <reference path=\"Scripts/knockout-3.5.0.js\" />function Student(data) { this.StudentId = ko.observable(data.StudentId); this.FirstName = ko.observable(data.FirstName); this.LastName = ko.observable(data.LastName); this.Age = ko.observable(data.Age); this.Gender = ko.observable(data.Gender); this.Batch = ko.observable(data.Batch); this.Address = ko.observable(data.Address); this.Class = ko.observable(data.Class); this.School = ko.observable(data.School); this.Domicile = ko.observable(data.Domicile); } function StudentViewModel() { var self = this; self.Domiciles = ko.observableArray(['Delhi', 'Outside Delhi']); self.Genders = ko.observableArray(['Male', 'Female']); self.Students = ko.observableArray([]); self.StudentId = ko.observable(); self.FirstName = ko.observable(); self.LastName = ko.observable(); self.Age = ko.observable(); self.Batch = ko.observable(); self.Address = ko.observable(); self.Class = ko.observable(); self.School = ko.observable(); self.Domicile = ko.observable(); self.Gender = ko.observable(); self.AddStudent = function () { self.Students.push(new Student({ StudentId: self.StudentId(), FirstName: self.FirstName(), LastName: self.LastName(), Domicile: self.Domicile(), Age: self.Age(), Batch: self.Batch(), Address: self.Address(), Class: self.Class(), School: self.School(), Gender: self.Gender() })); self.StudentId(\"\"), self.FirstName(\"\"), self.LastName(\"\"), self.Domicile(\"\"), self.Age(\"\"), self.Batch(\"\"), self.Address(\"\"), self.Class(\"\"), self.School(\"\"), self.Gender(\"\") }; self.DeleteStudent = function (student) { $.ajax({ type: \"POST\", url: 'LearnKO.aspx/DeleteStudent', data: ko.toJSON({ data: student }), contentType: \"application/json; charset=utf-8\", success: function (result) { alert(result.d); self.Students.remove(student) }, error: function (err) { alert(err.status + \" - \" + err.statusText); } }); }; self.SaveStudent = function () { $.ajax({ type: \"POST\", url: 'LearnKO.aspx/SaveStudent', data: ko.toJSON({ data: self.Students }), contentType: \"application/json; charset=utf-8\", success: function (result) { alert(result.d); }, error: function (err) { alert(err.status + \" - \" + err.statusText); } }); }; self.UpdateStudent = function (student) { $.ajax({ type: \"POST\", url: 'LearnKO.aspx/UpdateStudent', data: ko.toJSON({ data: student }), contentType: \"application/json; charset=utf-8\", success: function(response) { $(\".errMsg ul\").remove(); var myObject = eval('(' + response.d + ')'); if (myObject > 0) { bindData(); $(\".errMsg\").append(\"<ul><li>Data updated successfully</li></ul>\"); } else { $(\".errMsg\").append(\"<ul><li>Opppps something went wrong.</li></ul>\"); } $(\".errMsg\").show(\"slow\"); clear(); }, error: function (response) { alert(response.status + ' ' + response.statusText); } }); }; $.ajax({ type: \"POST\", url: 'LearnKO.aspx/FetchStudents', contentType: \"application/json; charset=utf-8\", dataType: \"json\", success: function (results) { var students = $.map(results.d, function (item) { return new Student(item) }); self.Students(students); }, error: function (err) { alert(err.status + \" - \" + err.statusText); } }); } $(document).ready(function () { ko.applyBindings(new StudentViewModel()); });", "e": 39523, "s": 35151, "text": null }, { "code": null, "e": 39565, "s": 39523, "text": "Step 12 : Press F5 to run the Application" }, { "code": null, "e": 39574, "s": 39565, "text": "Articles" }, { "code": null, "e": 39591, "s": 39574, "text": "Web Technologies" }, { "code": null, "e": 39689, "s": 39591, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39726, "s": 39689, "text": "Time Complexity and Space Complexity" }, { "code": null, "e": 39752, "s": 39726, "text": "Docker - COPY Instruction" }, { "code": null, "e": 39773, "s": 39752, "text": "SQL | Date functions" }, { "code": null, "e": 39820, "s": 39773, "text": "Time complexities of different data structures" }, { "code": null, "e": 39863, "s": 39820, "text": "Implementation of LinkedList in Javascript" }, { "code": null, "e": 39905, "s": 39863, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 39938, "s": 39905, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 39981, "s": 39938, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 40031, "s": 39981, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Python Program to Find the Gravitational Force Acting Between Two Objects
When it is required to find the gravitational force that acts between the two objects, a method named ‘find_gravity’ is used, and three parameters are passed to it. Below is the demonstration of the same − Live Demo def find_gravity(m_1, m_2, r): G_val = 6.673*(10**-11) F_val = (G_val*m_1*m_2)/(r**2) return round(F_val, 2) m_1 = 6000000 m_2 = 1000000 r = 45 print("The gravitational force is: ") print(find_gravity(m_1, m_2, r), "N") The gravitational force is: 0.2 N A method named ‘find_gravity’ is defined, that takes three parameters. A method named ‘find_gravity’ is defined, that takes three parameters. The gravitational force, and the gravitational constant are determined, and the force value is returned as output. The gravitational force, and the gravitational constant are determined, and the force value is returned as output. Outside the method, three integers are defined. Outside the method, three integers are defined. The method is called by passing these values as parameters. The method is called by passing these values as parameters. The output is displayed on the console. The output is displayed on the console.
[ { "code": null, "e": 1227, "s": 1062, "text": "When it is required to find the gravitational force that acts between the two objects, a method named ‘find_gravity’ is used, and three parameters are passed to it." }, { "code": null, "e": 1268, "s": 1227, "text": "Below is the demonstration of the same −" }, { "code": null, "e": 1279, "s": 1268, "text": " Live Demo" }, { "code": null, "e": 1510, "s": 1279, "text": "def find_gravity(m_1, m_2, r):\n G_val = 6.673*(10**-11)\n F_val = (G_val*m_1*m_2)/(r**2)\n\n return round(F_val, 2)\n\nm_1 = 6000000\nm_2 = 1000000\nr = 45\nprint(\"The gravitational force is: \")\nprint(find_gravity(m_1, m_2, r), \"N\")" }, { "code": null, "e": 1544, "s": 1510, "text": "The gravitational force is:\n0.2 N" }, { "code": null, "e": 1615, "s": 1544, "text": "A method named ‘find_gravity’ is defined, that takes three parameters." }, { "code": null, "e": 1686, "s": 1615, "text": "A method named ‘find_gravity’ is defined, that takes three parameters." }, { "code": null, "e": 1801, "s": 1686, "text": "The gravitational force, and the gravitational constant are determined, and the force value is returned as output." }, { "code": null, "e": 1916, "s": 1801, "text": "The gravitational force, and the gravitational constant are determined, and the force value is returned as output." }, { "code": null, "e": 1964, "s": 1916, "text": "Outside the method, three integers are defined." }, { "code": null, "e": 2012, "s": 1964, "text": "Outside the method, three integers are defined." }, { "code": null, "e": 2072, "s": 2012, "text": "The method is called by passing these values as parameters." }, { "code": null, "e": 2132, "s": 2072, "text": "The method is called by passing these values as parameters." }, { "code": null, "e": 2172, "s": 2132, "text": "The output is displayed on the console." }, { "code": null, "e": 2212, "s": 2172, "text": "The output is displayed on the console." } ]
C# | How to change BufferWidth of the Console - GeeksforGeeks
28 Jan, 2019 Given the normal Console in C#, the task is to find the default value of Buffer Width and change it to something else. Buffer Width refers to the current width of the buffer area of the console in columns. Approach: This can be done using the Buffer Width property in the Console class of the System package in C#. Program 1: Finding the default Buffer Width // C# program to demonstrate the // Console.BufferWidth Propertyusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks; namespace GFG { class Program { // Main Method static void Main(string[] args) { // Display current Buffer Width Console.WriteLine("Default Buffer Width: {0}", Console.BufferWidth); }}} Output: Program 2: Changing the Buffer Width to 100 // C# program to demonstrate the // Console.BufferWidth Propertyusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks; namespace GFG { class Program { static void Main(string[] args) { // Display current Buffer Width Console.WriteLine("Default Buffer Width: {0}", Console.BufferWidth); // Set the Buffer Width to 100 Console.BufferWidth = 100; // Display current Buffer Width Console.WriteLine("Changed Buffer Width: {0}", Console.BufferWidth); }}} Output: Note: See how the horizontal scrolling bar on the bottom has changed in both the images. CSharp-Console-Class C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 50 C# Interview Questions & Answers Extension Method in C# HashSet in C# with Examples Partial Classes in C# C# | Inheritance Convert String to Character Array in C# Linked List Implementation in C# C# | How to insert an element in an Array? C# | List Class Difference between Hashtable and Dictionary in C#
[ { "code": null, "e": 23911, "s": 23883, "text": "\n28 Jan, 2019" }, { "code": null, "e": 24030, "s": 23911, "text": "Given the normal Console in C#, the task is to find the default value of Buffer Width and change it to something else." }, { "code": null, "e": 24117, "s": 24030, "text": "Buffer Width refers to the current width of the buffer area of the console in columns." }, { "code": null, "e": 24226, "s": 24117, "text": "Approach: This can be done using the Buffer Width property in the Console class of the System package in C#." }, { "code": null, "e": 24270, "s": 24226, "text": "Program 1: Finding the default Buffer Width" }, { "code": "// C# program to demonstrate the // Console.BufferWidth Propertyusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks; namespace GFG { class Program { // Main Method static void Main(string[] args) { // Display current Buffer Width Console.WriteLine(\"Default Buffer Width: {0}\", Console.BufferWidth); }}}", "e": 24695, "s": 24270, "text": null }, { "code": null, "e": 24703, "s": 24695, "text": "Output:" }, { "code": null, "e": 24747, "s": 24703, "text": "Program 2: Changing the Buffer Width to 100" }, { "code": "// C# program to demonstrate the // Console.BufferWidth Propertyusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks; namespace GFG { class Program { static void Main(string[] args) { // Display current Buffer Width Console.WriteLine(\"Default Buffer Width: {0}\", Console.BufferWidth); // Set the Buffer Width to 100 Console.BufferWidth = 100; // Display current Buffer Width Console.WriteLine(\"Changed Buffer Width: {0}\", Console.BufferWidth); }}}", "e": 25378, "s": 24747, "text": null }, { "code": null, "e": 25386, "s": 25378, "text": "Output:" }, { "code": null, "e": 25475, "s": 25386, "text": "Note: See how the horizontal scrolling bar on the bottom has changed in both the images." }, { "code": null, "e": 25496, "s": 25475, "text": "CSharp-Console-Class" }, { "code": null, "e": 25499, "s": 25496, "text": "C#" }, { "code": null, "e": 25597, "s": 25499, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25606, "s": 25597, "text": "Comments" }, { "code": null, "e": 25619, "s": 25606, "text": "Old Comments" }, { "code": null, "e": 25659, "s": 25619, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 25682, "s": 25659, "text": "Extension Method in C#" }, { "code": null, "e": 25710, "s": 25682, "text": "HashSet in C# with Examples" }, { "code": null, "e": 25732, "s": 25710, "text": "Partial Classes in C#" }, { "code": null, "e": 25749, "s": 25732, "text": "C# | Inheritance" }, { "code": null, "e": 25789, "s": 25749, "text": "Convert String to Character Array in C#" }, { "code": null, "e": 25822, "s": 25789, "text": "Linked List Implementation in C#" }, { "code": null, "e": 25865, "s": 25822, "text": "C# | How to insert an element in an Array?" }, { "code": null, "e": 25881, "s": 25865, "text": "C# | List Class" } ]
Finding number of occurrences of a specific string in MySQL?
Use LENGTH() for this. Let us first create a table − mysql> create table DemoTable -> ( -> Value text -> ); Query OK, 0 rows affected (0.74 sec) Insert some records in the table using insert command − mysql> insert into DemoTable values('10,20,10,30,10,40,50,40'); Query OK, 1 row affected (0.24 sec) Display all records from the table using select statement − mysql> select *from DemoTable; This will produce the following output − +-------------------------+ | Value | +-------------------------+ | 10,20,10,30,10,40,50,40 | +-------------------------+ 1 row in set (0.00 sec) Following is the query to find number of occurrences of a specific string in MySQL. The occurrence of ‘10’ is what we are finding here − mysql> select LENGTH(Value) + 2 -LENGTH(REPLACE(CONCAT(',', Value, ','), ',10,', 'len'))from DemoTable; This will produce the following output − +----------------------------------------------------------------------------+ | LENGTH(Value) + 2 -LENGTH(REPLACE(CONCAT(',', Value, ','), ',10,', 'len')) | +----------------------------------------------------------------------------+ | 3 | +----------------------------------------------------------------------------+ 1 row in set (0.00 sec)
[ { "code": null, "e": 1115, "s": 1062, "text": "Use LENGTH() for this. Let us first create a table −" }, { "code": null, "e": 1207, "s": 1115, "text": "mysql> create table DemoTable\n-> (\n-> Value text\n-> );\nQuery OK, 0 rows affected (0.74 sec)" }, { "code": null, "e": 1263, "s": 1207, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1363, "s": 1263, "text": "mysql> insert into DemoTable values('10,20,10,30,10,40,50,40');\nQuery OK, 1 row affected (0.24 sec)" }, { "code": null, "e": 1423, "s": 1363, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1454, "s": 1423, "text": "mysql> select *from DemoTable;" }, { "code": null, "e": 1495, "s": 1454, "text": "This will produce the following output −" }, { "code": null, "e": 1659, "s": 1495, "text": "+-------------------------+\n| Value |\n+-------------------------+\n| 10,20,10,30,10,40,50,40 |\n+-------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 1796, "s": 1659, "text": "Following is the query to find number of occurrences of a specific string in MySQL. The occurrence of ‘10’ is what we are finding here −" }, { "code": null, "e": 1900, "s": 1796, "text": "mysql> select LENGTH(Value) + 2 -LENGTH(REPLACE(CONCAT(',', Value, ','), ',10,', 'len'))from DemoTable;" }, { "code": null, "e": 1941, "s": 1900, "text": "This will produce the following output −" }, { "code": null, "e": 2360, "s": 1941, "text": "+----------------------------------------------------------------------------+\n| LENGTH(Value) + 2 -LENGTH(REPLACE(CONCAT(',', Value, ','), ',10,', 'len')) |\n+----------------------------------------------------------------------------+\n| 3 |\n+----------------------------------------------------------------------------+\n1 row in set (0.00 sec)" } ]
How to change the Drive letter using PowerShell?
To change the drive letter using PowerShell, we can use the Set−Partition command but before that, we need to know which drive letter to change. You can check the drive letter using Windows Explorer, Get−Partition, Gwmi win32_Logicaldisk, or Get−CimInstance Win32_Logicaldisk command. Suppose we have an E: and we need to rename its drive letter to F, so we can use the below command. Set−Partition −DriveLetter 'E' −NewDriveLetter 'F' Make sure that the drive is not in use by Pagefile, open application, or open file from the drive otherwise the drive letter will fail to change. To change the drive letter on the remote computer, you can connect to a remote session using the New−CIMSession command or using the Invoke−Command remote computer method. With the CIM session command, $sess = New−CimSession −ComputerName Labmachine2k12 Set−Partition −CimSession $sess −DriveLetter 'E' −NewDriveLetter 'F' In the above example, we are using a remote computer name LabMachine2k12. You can change as per your remote system. With the Invoke−Command method, Invoke−Command −ComputerName Labmachine2k12 −ScriptBlock{Set−Partition −DriveLetter 'E' −NewDriveLetter 'F'} You can also use the DiskID instead of DriveLetter.
[ { "code": null, "e": 1347, "s": 1062, "text": "To change the drive letter using PowerShell, we can use the Set−Partition command but before that, we need to know which drive letter to change. You can check the drive letter using Windows Explorer, Get−Partition, Gwmi win32_Logicaldisk, or Get−CimInstance Win32_Logicaldisk command." }, { "code": null, "e": 1447, "s": 1347, "text": "Suppose we have an E: and we need to rename its drive letter to F, so we can use the below command." }, { "code": null, "e": 1498, "s": 1447, "text": "Set−Partition −DriveLetter 'E' −NewDriveLetter 'F'" }, { "code": null, "e": 1644, "s": 1498, "text": "Make sure that the drive is not in use by Pagefile, open application, or open file from the drive otherwise the drive letter will fail to change." }, { "code": null, "e": 1816, "s": 1644, "text": "To change the drive letter on the remote computer, you can connect to a remote session using the New−CIMSession command or using the Invoke−Command remote computer method." }, { "code": null, "e": 1846, "s": 1816, "text": "With the CIM session command," }, { "code": null, "e": 1967, "s": 1846, "text": "$sess = New−CimSession −ComputerName Labmachine2k12\nSet−Partition −CimSession $sess −DriveLetter 'E' −NewDriveLetter 'F'" }, { "code": null, "e": 2083, "s": 1967, "text": "In the above example, we are using a remote computer name LabMachine2k12. You can change as per your remote system." }, { "code": null, "e": 2115, "s": 2083, "text": "With the Invoke−Command method," }, { "code": null, "e": 2225, "s": 2115, "text": "Invoke−Command −ComputerName Labmachine2k12 −ScriptBlock{Set−Partition −DriveLetter 'E' −NewDriveLetter 'F'}\n" }, { "code": null, "e": 2277, "s": 2225, "text": "You can also use the DiskID instead of DriveLetter." } ]
A Mathematical Explanation of Support Vector Machines | by Terence Shin | Towards Data Science
Support Vector Machines (SVMs) are one of the most popular machine learning models in the data science world. Intuitively, it’s a rather simple concept. Mathematically speaking, however, support vector machines can seem like a black box. In this article, I have two goals: I want to demystify the mechanics underlying support vector machines and give you a better understanding of its overall logic.I’ll want to teach you how to implement a simple SVM in Python and deploy it using Gradio. By the end, you’ll be able to build something like this: I want to demystify the mechanics underlying support vector machines and give you a better understanding of its overall logic. I’ll want to teach you how to implement a simple SVM in Python and deploy it using Gradio. By the end, you’ll be able to build something like this: With that said, let’s dive right into it! A Support Vector Machine (SVM) is a supervised classification technique. The essence of SVMs simply involves finding a boundary that separates different classes from each other. In 2-dimensional space, the boundary is called a line. In 3-dimensional space, the boundary is called a plane. In any dimension greater than 3, the boundary is called a hyperplane. Let’s assume that there are two classes of data. A support vector machine will find a boundary that maximizes the margin between the two classes (see image above). There are many planes that can separate the two classes, but only one plane can maximize the margin or distance between the classes. n = number of data pointsm = number of attributesx_ij = ith attribute of jth data pointy_j = 1 if data point is blue, -1 if data point is red After reading this, you’ll understand what the equation above is trying to achieve. Don’t worry if it looks confusing! I will do my best to break it down step by step. Keep in mind that this covers the math for a fundamental support vector machine and does not consider things like kernels or non-linear boundaries. Breaking this down, we can separate this into two separate parts: Red Part: The red part focuses on minimizing the error, the number of falsely classified points, that the SVM makes. Blue Part: The blue part focuses on maximizing the margin, which was discussed earlier in the article. Let’s first talk about the blue part, or the second term of the equation. As I said earlier, there are many boundaries that you can put in between two classes of data points, but there is only one boundary that maximizes the margin between the two classes (as shown by the dotted lines above). We want the decision boundary to be as far away from the support vectors as possible so that when we have new data, it will fall in one or the other class with greater certainty. Let’s suppose that the two equations above represent each side of the margin. Don’t worry so much about m/-m. Just notice how they represent the equation of a line. The distance between the two dotted lines is found from the following formula, which you can read more about here: Don’t worry so much about how this equation is derived. Rather, notice that as all a’s between 1 and m (a1, a2, ... am) get smaller, than the denominator gets smaller, and the distance or the margin gets larger! Now that you understand what the second term (blue part) means, lets talk about the first term (red part). In reality, it’s not going to be the case that you’ll be able to find a hyperplane that perfectly separates different classes from each other. And even if it exists, it’s not always the case that you’ll want to use that hyperplane. Consider the image below: Technically, we could set the boundary so that the red and blue classes are on the right side of the boundary. However, given that the blue square on the left is an outlier, it may be more ideal to have an imperfect hyperplane with a larger margin, this is known as a soft margin: Now that we’ve introduced the concept of “error”, you should understand that the full equation for Support Vector Machines is trying to minimize error while maximizing the margin. Now that we understand the goal behind the first term, let’s revisit the equation: In English, this equation says to “take the sum of the errors of each point”. So how does ^ this part of the equation represent the error of each point? Let’s dive into that: Let’s set m and -m to 1 and -1 respectively. In reality, they can be any number as m is a scaling factor of the margin. Since y_j = 1 if data point is blue, -1 if data point is red, we can combine the equation for the upper boundary and the equation for the lower boundary to represent all points: This can be re-written as the following: This equation assumes that all points are classified on the right side of the equation. For any point that is on the wrong side of the boundary, it will not satisfy the equation. For some of you, I bet the light bulbs are lighting up in your head. If not, no worries! We’re almost at the end. Remember when I said that this equation “takes the sum of the errors of each point.” Specifically, it’s taking the max of zero, and the second part. The rule is as follows: Let the equation above represent Z. If a given point is on the right side of the line, then Z will be greater than 1. This means the second part of the first term will be a negative number, so the given point will return 0 (no error) If a given point is on the wrong side of the line, then Z will be less than 1. This means the second part of the first term will be a positive number, so the given point will return a value greater than 0 (error). And that’s it! To summarize, the objective of support vector machines is to minimize the total error and maximize the margin by minimizing a_i. Now that you understand the math behind SVMs, the next step is to actually build a support vector machine model in Python and deploy it! I’m going to use the classic iris data set to show how you can build a support vector machine in Python (See the full code here). Before starting you’ll need to install the following libraries: Numpy Pandas Seaborn Sklearn Gradio # Importing librariesimport numpy as npimport pandas as pdimport seaborn as sns# Importing datairis=sns.load_dataset("iris") from sklearn.model_selection import train_test_split# Splitting features and target variablesX=iris.drop("species",axis=1)y=iris["species"]# Splitting data into train and test setsX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25) from sklearn.svm import SVC# Creating modelmodel = SVC(probability=True)model.fit(X_train,y_train) # Writing a prediction functiondef predict_flower(sepal_length, sepal_width, petal_length, petal_width): df = pd.DataFrame.from_dict({'Sepal Length':[sepal_length], 'Sepal Width': [sepal_width], 'Petal Length': [petal_length], 'Petal Width': [petal_width]})predict = model.predict_proba(df)[0]return {model.classes_[i]: predict[i] for i in range(3)}# Importing gradioimport gradio as gr# Creating Web Appsepal_length = gr.inputs.Slider(minimum=0, maximum=10, default=5, label="sepal_length")sepal_width = gr.inputs.Slider(minimum=0, maximum=10, default=5, label="sepal_width")petal_length = gr.inputs.Slider(minimum=0, maximum=10, default=5, label="petal_length")petal_width = gr.inputs.Slider(minimum=0, maximum=10, default=5, label="petal_width")gr.Interface(predict_flower, [sepal_length, sepal_width, petal_length, petal_width], "label", live=True).launch(debug=True) And there you have it! You should have a fully function web app where you can play around with the inputs of the model and immediately see the output probabilities. If you made it to the end, congrats! You should now have a strong understanding of how a basic support vector machine works, and you now know how to build your own fully function SVM web application. If you enjoyed this, please give this some claps and follow me on Medium! As always I wish you best in your learning endeavors. :D Not sure what to read next? I’ve picked another article for you: towardsdatascience.com and another! towardsdatascience.com If you enjoyed this, follow me on Medium for more Interested in collaborating? Let’s connect on LinkedIn Sign up for my email list here!
[ { "code": null, "e": 409, "s": 171, "text": "Support Vector Machines (SVMs) are one of the most popular machine learning models in the data science world. Intuitively, it’s a rather simple concept. Mathematically speaking, however, support vector machines can seem like a black box." }, { "code": null, "e": 444, "s": 409, "text": "In this article, I have two goals:" }, { "code": null, "e": 718, "s": 444, "text": "I want to demystify the mechanics underlying support vector machines and give you a better understanding of its overall logic.I’ll want to teach you how to implement a simple SVM in Python and deploy it using Gradio. By the end, you’ll be able to build something like this:" }, { "code": null, "e": 845, "s": 718, "text": "I want to demystify the mechanics underlying support vector machines and give you a better understanding of its overall logic." }, { "code": null, "e": 993, "s": 845, "text": "I’ll want to teach you how to implement a simple SVM in Python and deploy it using Gradio. By the end, you’ll be able to build something like this:" }, { "code": null, "e": 1035, "s": 993, "text": "With that said, let’s dive right into it!" }, { "code": null, "e": 1213, "s": 1035, "text": "A Support Vector Machine (SVM) is a supervised classification technique. The essence of SVMs simply involves finding a boundary that separates different classes from each other." }, { "code": null, "e": 1268, "s": 1213, "text": "In 2-dimensional space, the boundary is called a line." }, { "code": null, "e": 1324, "s": 1268, "text": "In 3-dimensional space, the boundary is called a plane." }, { "code": null, "e": 1394, "s": 1324, "text": "In any dimension greater than 3, the boundary is called a hyperplane." }, { "code": null, "e": 1691, "s": 1394, "text": "Let’s assume that there are two classes of data. A support vector machine will find a boundary that maximizes the margin between the two classes (see image above). There are many planes that can separate the two classes, but only one plane can maximize the margin or distance between the classes." }, { "code": null, "e": 1833, "s": 1691, "text": "n = number of data pointsm = number of attributesx_ij = ith attribute of jth data pointy_j = 1 if data point is blue, -1 if data point is red" }, { "code": null, "e": 2001, "s": 1833, "text": "After reading this, you’ll understand what the equation above is trying to achieve. Don’t worry if it looks confusing! I will do my best to break it down step by step." }, { "code": null, "e": 2149, "s": 2001, "text": "Keep in mind that this covers the math for a fundamental support vector machine and does not consider things like kernels or non-linear boundaries." }, { "code": null, "e": 2215, "s": 2149, "text": "Breaking this down, we can separate this into two separate parts:" }, { "code": null, "e": 2332, "s": 2215, "text": "Red Part: The red part focuses on minimizing the error, the number of falsely classified points, that the SVM makes." }, { "code": null, "e": 2435, "s": 2332, "text": "Blue Part: The blue part focuses on maximizing the margin, which was discussed earlier in the article." }, { "code": null, "e": 2509, "s": 2435, "text": "Let’s first talk about the blue part, or the second term of the equation." }, { "code": null, "e": 2729, "s": 2509, "text": "As I said earlier, there are many boundaries that you can put in between two classes of data points, but there is only one boundary that maximizes the margin between the two classes (as shown by the dotted lines above)." }, { "code": null, "e": 2908, "s": 2729, "text": "We want the decision boundary to be as far away from the support vectors as possible so that when we have new data, it will fall in one or the other class with greater certainty." }, { "code": null, "e": 3073, "s": 2908, "text": "Let’s suppose that the two equations above represent each side of the margin. Don’t worry so much about m/-m. Just notice how they represent the equation of a line." }, { "code": null, "e": 3188, "s": 3073, "text": "The distance between the two dotted lines is found from the following formula, which you can read more about here:" }, { "code": null, "e": 3400, "s": 3188, "text": "Don’t worry so much about how this equation is derived. Rather, notice that as all a’s between 1 and m (a1, a2, ... am) get smaller, than the denominator gets smaller, and the distance or the margin gets larger!" }, { "code": null, "e": 3507, "s": 3400, "text": "Now that you understand what the second term (blue part) means, lets talk about the first term (red part)." }, { "code": null, "e": 3739, "s": 3507, "text": "In reality, it’s not going to be the case that you’ll be able to find a hyperplane that perfectly separates different classes from each other. And even if it exists, it’s not always the case that you’ll want to use that hyperplane." }, { "code": null, "e": 3765, "s": 3739, "text": "Consider the image below:" }, { "code": null, "e": 4046, "s": 3765, "text": "Technically, we could set the boundary so that the red and blue classes are on the right side of the boundary. However, given that the blue square on the left is an outlier, it may be more ideal to have an imperfect hyperplane with a larger margin, this is known as a soft margin:" }, { "code": null, "e": 4226, "s": 4046, "text": "Now that we’ve introduced the concept of “error”, you should understand that the full equation for Support Vector Machines is trying to minimize error while maximizing the margin." }, { "code": null, "e": 4309, "s": 4226, "text": "Now that we understand the goal behind the first term, let’s revisit the equation:" }, { "code": null, "e": 4387, "s": 4309, "text": "In English, this equation says to “take the sum of the errors of each point”." }, { "code": null, "e": 4484, "s": 4387, "text": "So how does ^ this part of the equation represent the error of each point? Let’s dive into that:" }, { "code": null, "e": 4604, "s": 4484, "text": "Let’s set m and -m to 1 and -1 respectively. In reality, they can be any number as m is a scaling factor of the margin." }, { "code": null, "e": 4782, "s": 4604, "text": "Since y_j = 1 if data point is blue, -1 if data point is red, we can combine the equation for the upper boundary and the equation for the lower boundary to represent all points:" }, { "code": null, "e": 4823, "s": 4782, "text": "This can be re-written as the following:" }, { "code": null, "e": 5002, "s": 4823, "text": "This equation assumes that all points are classified on the right side of the equation. For any point that is on the wrong side of the boundary, it will not satisfy the equation." }, { "code": null, "e": 5116, "s": 5002, "text": "For some of you, I bet the light bulbs are lighting up in your head. If not, no worries! We’re almost at the end." }, { "code": null, "e": 5289, "s": 5116, "text": "Remember when I said that this equation “takes the sum of the errors of each point.” Specifically, it’s taking the max of zero, and the second part. The rule is as follows:" }, { "code": null, "e": 5325, "s": 5289, "text": "Let the equation above represent Z." }, { "code": null, "e": 5523, "s": 5325, "text": "If a given point is on the right side of the line, then Z will be greater than 1. This means the second part of the first term will be a negative number, so the given point will return 0 (no error)" }, { "code": null, "e": 5737, "s": 5523, "text": "If a given point is on the wrong side of the line, then Z will be less than 1. This means the second part of the first term will be a positive number, so the given point will return a value greater than 0 (error)." }, { "code": null, "e": 5881, "s": 5737, "text": "And that’s it! To summarize, the objective of support vector machines is to minimize the total error and maximize the margin by minimizing a_i." }, { "code": null, "e": 6018, "s": 5881, "text": "Now that you understand the math behind SVMs, the next step is to actually build a support vector machine model in Python and deploy it!" }, { "code": null, "e": 6148, "s": 6018, "text": "I’m going to use the classic iris data set to show how you can build a support vector machine in Python (See the full code here)." }, { "code": null, "e": 6212, "s": 6148, "text": "Before starting you’ll need to install the following libraries:" }, { "code": null, "e": 6218, "s": 6212, "text": "Numpy" }, { "code": null, "e": 6225, "s": 6218, "text": "Pandas" }, { "code": null, "e": 6233, "s": 6225, "text": "Seaborn" }, { "code": null, "e": 6241, "s": 6233, "text": "Sklearn" }, { "code": null, "e": 6248, "s": 6241, "text": "Gradio" }, { "code": null, "e": 6373, "s": 6248, "text": "# Importing librariesimport numpy as npimport pandas as pdimport seaborn as sns# Importing datairis=sns.load_dataset(\"iris\")" }, { "code": null, "e": 6627, "s": 6373, "text": "from sklearn.model_selection import train_test_split# Splitting features and target variablesX=iris.drop(\"species\",axis=1)y=iris[\"species\"]# Splitting data into train and test setsX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25)" }, { "code": null, "e": 6726, "s": 6627, "text": "from sklearn.svm import SVC# Creating modelmodel = SVC(probability=True)model.fit(X_train,y_train)" }, { "code": null, "e": 7704, "s": 6726, "text": "# Writing a prediction functiondef predict_flower(sepal_length, sepal_width, petal_length, petal_width): df = pd.DataFrame.from_dict({'Sepal Length':[sepal_length], 'Sepal Width': [sepal_width], 'Petal Length': [petal_length], 'Petal Width': [petal_width]})predict = model.predict_proba(df)[0]return {model.classes_[i]: predict[i] for i in range(3)}# Importing gradioimport gradio as gr# Creating Web Appsepal_length = gr.inputs.Slider(minimum=0, maximum=10, default=5, label=\"sepal_length\")sepal_width = gr.inputs.Slider(minimum=0, maximum=10, default=5, label=\"sepal_width\")petal_length = gr.inputs.Slider(minimum=0, maximum=10, default=5, label=\"petal_length\")petal_width = gr.inputs.Slider(minimum=0, maximum=10, default=5, label=\"petal_width\")gr.Interface(predict_flower, [sepal_length, sepal_width, petal_length, petal_width], \"label\", live=True).launch(debug=True)" }, { "code": null, "e": 7869, "s": 7704, "text": "And there you have it! You should have a fully function web app where you can play around with the inputs of the model and immediately see the output probabilities." }, { "code": null, "e": 8069, "s": 7869, "text": "If you made it to the end, congrats! You should now have a strong understanding of how a basic support vector machine works, and you now know how to build your own fully function SVM web application." }, { "code": null, "e": 8143, "s": 8069, "text": "If you enjoyed this, please give this some claps and follow me on Medium!" }, { "code": null, "e": 8200, "s": 8143, "text": "As always I wish you best in your learning endeavors. :D" }, { "code": null, "e": 8265, "s": 8200, "text": "Not sure what to read next? I’ve picked another article for you:" }, { "code": null, "e": 8288, "s": 8265, "text": "towardsdatascience.com" }, { "code": null, "e": 8301, "s": 8288, "text": "and another!" }, { "code": null, "e": 8324, "s": 8301, "text": "towardsdatascience.com" }, { "code": null, "e": 8374, "s": 8324, "text": "If you enjoyed this, follow me on Medium for more" }, { "code": null, "e": 8429, "s": 8374, "text": "Interested in collaborating? Let’s connect on LinkedIn" } ]
How to bind events to Tkinter Canvas items?
Tkinter events can be bound with the widgets to perform a set of operations on the widgets. To be more specific, we can also bind an event handler to Canvas Items by using bind(<Button>, callback) method. Binding the event with the canvas item makes a canvas item dynamic which can be customized by event handlers. #Import the required Libraries from tkinter import * import random #Create an instance of Tkinter frame win = Tk() #Set the geometry of the window win.geometry("700x350") #Crate a canvas canvas=Canvas(win,width=700,height=350,bg='white') def draw_shapes(e): canvas.delete(ALL) canvas.create_oval(random.randint(5,300),random.randint(1,300),25,25,fill='O rangeRed2') canvas.pack() #Bind the spacebar Key to a function win.bind("<space>", draw_shapes) win.mainloop() Running the above code will display a window that contains a Canvas. When we press the <Space> key, it will generate random shapes in the canvas window.
[ { "code": null, "e": 1377, "s": 1062, "text": "Tkinter events can be bound with the widgets to perform a set of operations on the widgets. To be more specific, we can also bind an event handler to Canvas Items by using bind(<Button>, callback) method. Binding the event with the canvas item makes a canvas item dynamic which can be customized by event handlers." }, { "code": null, "e": 1850, "s": 1377, "text": "#Import the required Libraries\nfrom tkinter import *\nimport random\n\n#Create an instance of Tkinter frame\nwin = Tk()\n\n#Set the geometry of the window\nwin.geometry(\"700x350\")\n\n#Crate a canvas\ncanvas=Canvas(win,width=700,height=350,bg='white')\ndef draw_shapes(e):\n canvas.delete(ALL)\n\ncanvas.create_oval(random.randint(5,300),random.randint(1,300),25,25,fill='O rangeRed2')\ncanvas.pack()\n\n#Bind the spacebar Key to a function\nwin.bind(\"<space>\", draw_shapes)\nwin.mainloop()" }, { "code": null, "e": 1919, "s": 1850, "text": "Running the above code will display a window that contains a Canvas." }, { "code": null, "e": 2003, "s": 1919, "text": "When we press the <Space> key, it will generate random shapes in the canvas window." } ]
Evaluating performance of an object detection model | by Renu Khandelwal | Towards Data Science
In this article, you will figure out how to use mAP to evaluate the performance of an object detection model. What is mAP? How to calculate mAP along with 11-point interpolation? We use machine learning and deep learning to solve regression or classification problem. We used Root Mean Square(RMS) or Mean Average Percentage Error(MAPE) etc. to evaluate the performance of a regression model. Classification models are evaluated using Accuracy, Precision, Recall or an F1- Score. Is object detection, a classification or a regression problem? Multiple deep learning algorithms exist for object detection like RCNN’s: Fast RCNN, Faster RCNN, YOLO, Mask RCNN etc. Objective of an object detection models is to Classification: Identify if an object is present in the image and the class of the object Localization: Predict the co-ordinates of the bounding box around the object when an object is present in the image. Here we compare the co-ordinates of ground truth and predicted bounding boxes We need to evaluate the performance of both classification as well as localization of using bounding boxes in the image How do we measure the performance of object detection model? For object detection we use the concept of Intersection over Union (IoU). IoU computes intersection over the union of the two bounding boxes; the bounding box for the ground truth and the predicted bounding box An IoU of 1 implies that predicted and the ground-truth bounding boxes perfectly overlap. You can set a threshold value for the IoU to determine if the object detection is valid or not not. Let’s say you set IoU to 0.5, in that case if IoU ≥0.5, classify the object detection as True Positive(TP) if Iou <0.5, then it is a wrong detection and classify it as False Positive(FP) When a ground truth is present in the image and model failed to detect the object, classify it as False Negative(FN). True Negative (TN): TN is every part of the image where we did not predict an object. This metrics is not useful for object detection, hence we ignore TN. Set IoU threshold value to 0.5 or greater. It can be set to 0.5, 0.75. 0.9 or 0.95 etc. Use Precision and Recall as the metrics to evaluate the performance. Precision and Recall are calculated using true positives(TP), false positives(FP) and false negatives(FN). Calculate precision and recall for all objects present in the image. You also need to consider the confidence score for each object detected by the model in the image. Consider all of the predicted bounding boxes with a confidence score above a certain threshold. Bounding boxes above the threshold value are considered as positive boxes and all predicted bounding boxes below the threshold value are considered as negative. How to calculate mAP using 11 point interpolation? Step 1: Plot Precision and Recall Plot the precision and recall values on a Precision Recall(PR) graph. PR graph is monotonically decreasing, there is always a trade-off between precision and recall. Increasing one will decrease the other. Sometimes PR graph is not always monotonically decreasing due to certain exceptions and/or lack of data. Step 2: Calculate the mean Average Precision(mAP), use 11 point interpolation technique. Interpolated precision is average precision measured at 11 equally spaced recall levels of 0.0, 0.1, 0.2, 0.3 ....0.9, 1.0 as shown in the figure above The PR graph sometimes may not be monotonically decreasing, to resolve the issue, we set max of precision for a value of recall. Graphically, at each recall level, we replace each precision value with the maximum precision value to the right of that recall level i.e.; we take the maximum of all future points The rationale is the willingness to look at higher precision values if both precision and recall get better. Finally calculate the arithmetic mean of the interpolated precision at each recall level for each information in the test collection. mAP is always calculated over the entire dataset. Let’s understand with an example as shown below, recall values are sorted for us to plot the PR graph 11 point interpolation will use the highest value for the precision for a recall value. We create 11 equally spaced recall levels of 0.0, 0.1, 0.2, 0.3 ....0.9, 1.0 Recall of 0.2 has the highest precision value of 1.00. Recall value of 0.4 has different precision values 0.4, 0.67, 0.5. In this scenario, we use the highest precision value of 0.67. When the precision value is 0.6, we have precision value of 0.5 but for a recall of 0.8, we see a higher precision value of 0.57. Based on the rationale for 11 point interpolation, we take the maximum of all future points, so the precision that we need consider is 0.57 instead of 0.5. Finally for a recall of 1.0, we take the max precision which is 0.5. Now plotting the Precision Recall as well as the Interpolated precision. We finally apply the mean average precision formula AP =1/11(4* 1.0 + 2 * 0.67+ 4*0.57 + 1*0.5) =0.74 This gives us the mean average precision using 11 point interpolation Pascal VOC Bounding box is defined by (x-top left, y-top left,x-bottom right, y-bottom right) #GT Boxesgt_boxes= {"img_00285.png": [[480, 457, 515, 529], [637, 435, 676, 536]]}#Pred Boxespred_boxs={"img_00285.png": {"boxes": [[330, 463, 387, 505], [356, 456, 391, 521], [420, 433, 451, 498], [328, 465, 403, 540], [480, 477, 508, 522], [357, 460, 417, 537], [344, 459, 389, 493], [485, 459, 503, 511], [336, 463, 362, 496], [468, 435, 520, 521], [357, 458, 382, 485], [649, 479, 670, 531], [484, 455, 514, 519], [641, 439, 670, 532]], "scores": [0.0739, 0.0843, 0.091, 0.1008, 0.1012, 0.1058, 0.1243, 0.1266, 0.1342, 0.1618, 0.2452, 0.8505, 0.9113, 0.972]}} Importing required libraries import numpy as npfrom copy import deepcopyimport pandas as pdimport matplotlib.pyplot as pltimport seaborn as sns%matplotlib inline Create a dictionary of image id and confidence score def get_model_scores(pred_boxes): """Creates a dictionary of from model_scores to image ids. Args: pred_boxes (dict): dict of dicts of 'boxes' and 'scores' Returns: dict: keys are model_scores and values are image ids (usually filenames) """ model_score={} for img_id, val in pred_boxes.items(): for score in val['scores']: if score not in model_score.keys(): model_score[score]=[img_id] else: model_score[score].append(img_id) return model_score Calculate the IoU for bounding boxes with Pascal VOC format def calc_iou( gt_bbox, pred_bbox): ''' This function takes the predicted bounding box and ground truth bounding box and return the IoU ratio ''' x_topleft_gt, y_topleft_gt, x_bottomright_gt, y_bottomright_gt= gt_bbox x_topleft_p, y_topleft_p, x_bottomright_p, y_bottomright_p= pred_bbox if (x_topleft_gt > x_bottomright_gt) or (y_topleft_gt> y_bottomright_gt): raise AssertionError("Ground Truth Bounding Box is not correct") if (x_topleft_p > x_bottomright_p) or (y_topleft_p> y_bottomright_p): raise AssertionError("Predicted Bounding Box is not correct",x_topleft_p, x_bottomright_p,y_topleft_p,y_bottomright_gt) #if the GT bbox and predcited BBox do not overlap then iou=0 if(x_bottomright_gt< x_topleft_p): # If bottom right of x-coordinate GT bbox is less than or above the top left of x coordinate of the predicted BBox return 0.0 if(y_bottomright_gt< y_topleft_p): # If bottom right of y-coordinate GT bbox is less than or above the top left of y coordinate of the predicted BBox return 0.0 if(x_topleft_gt> x_bottomright_p): # If bottom right of x-coordinate GT bbox is greater than or below the bottom right of x coordinate of the predcited BBox return 0.0 if(y_topleft_gt> y_bottomright_p): # If bottom right of y-coordinate GT bbox is greater than or below the bottom right of y coordinate of the predcited BBox return 0.0 GT_bbox_area = (x_bottomright_gt - x_topleft_gt + 1) * ( y_bottomright_gt -y_topleft_gt + 1) Pred_bbox_area =(x_bottomright_p - x_topleft_p + 1 ) * ( y_bottomright_p -y_topleft_p + 1) x_top_left =np.max([x_topleft_gt, x_topleft_p]) y_top_left = np.max([y_topleft_gt, y_topleft_p]) x_bottom_right = np.min([x_bottomright_gt, x_bottomright_p]) y_bottom_right = np.min([y_bottomright_gt, y_bottomright_p]) intersection_area = (x_bottom_right- x_top_left + 1) * (y_bottom_right-y_top_left + 1) union_area = (GT_bbox_area + Pred_bbox_area - intersection_area) return intersection_area/union_area Calculate precision and recall def calc_precision_recall(image_results): """Calculates precision and recall from the set of images Args: img_results (dict): dictionary formatted like: { 'img_id1': {'true_pos': int, 'false_pos': int, 'false_neg': int}, 'img_id2': ... ... } Returns: tuple: of floats of (precision, recall) """ true_positive=0 false_positive=0 false_negative=0 for img_id, res in image_results.items(): true_positive +=res['true_positive'] false_positive += res['false_positive'] false_negative += res['false_negative'] try: precision = true_positive/(true_positive+ false_positive) except ZeroDivisionError: precision=0.0 try: recall = true_positive/(true_positive + false_negative) except ZeroDivisionError: recall=0.0 return (precision, recall) Returns true positive, false positive and false negative for the batch of bounding boxes for a single image. def get_single_image_results(gt_boxes, pred_boxes, iou_thr): """Calculates number of true_pos, false_pos, false_neg from single batch of boxes. Args: gt_boxes (list of list of floats): list of locations of ground truth objects as [xmin, ymin, xmax, ymax] pred_boxes (dict): dict of dicts of 'boxes' (formatted like `gt_boxes`) and 'scores' iou_thr (float): value of IoU to consider as threshold for a true prediction. Returns: dict: true positives (int), false positives (int), false negatives (int) """ all_pred_indices= range(len(pred_boxes)) all_gt_indices=range(len(gt_boxes)) if len(all_pred_indices)==0: tp=0 fp=0 fn=0 return {'true_positive':tp, 'false_positive':fp, 'false_negative':fn} if len(all_gt_indices)==0: tp=0 fp=0 fn=0 return {'true_positive':tp, 'false_positive':fp, 'false_negative':fn} gt_idx_thr=[] pred_idx_thr=[] ious=[] for ipb, pred_box in enumerate(pred_boxes): for igb, gt_box in enumerate(gt_boxes): iou= calc_iou(gt_box, pred_box) if iou >iou_thr: gt_idx_thr.append(igb) pred_idx_thr.append(ipb) ious.append(iou) iou_sort = np.argsort(ious)[::1] if len(iou_sort)==0: tp=0 fp=0 fn=0 return {'true_positive':tp, 'false_positive':fp, 'false_negative':fn} else: gt_match_idx=[] pred_match_idx=[] for idx in iou_sort: gt_idx=gt_idx_thr[idx] pr_idx= pred_idx_thr[idx] # If the boxes are unmatched, add them to matches if(gt_idx not in gt_match_idx) and (pr_idx not in pred_match_idx): gt_match_idx.append(gt_idx) pred_match_idx.append(pr_idx) tp= len(gt_match_idx) fp= len(pred_boxes) - len(pred_match_idx) fn = len(gt_boxes) - len(gt_match_idx) return {'true_positive': tp, 'false_positive': fp, 'false_negative': fn} Finally calculating the mAP using 11 point interpolation technique. You can specify your IoU threshold here else a default value of 0.5 will be used def get_avg_precision_at_iou(gt_boxes, pred_bb, iou_thr=0.5): model_scores = get_model_scores(pred_bb) sorted_model_scores= sorted(model_scores.keys())# Sort the predicted boxes in descending order (lowest scoring boxes first): for img_id in pred_bb.keys(): arg_sort = np.argsort(pred_bb[img_id]['scores']) pred_bb[img_id]['scores'] = np.array(pred_bb[img_id]['scores'])[arg_sort].tolist() pred_bb[img_id]['boxes'] = np.array(pred_bb[img_id]['boxes'])[arg_sort].tolist()pred_boxes_pruned = deepcopy(pred_bb) precisions = [] recalls = [] model_thrs = [] img_results = {}# Loop over model score thresholds and calculate precision, recall for ithr, model_score_thr in enumerate(sorted_model_scores[:-1]): # On first iteration, define img_results for the first time: print("Mode score : ", model_score_thr) img_ids = gt_boxes.keys() if ithr == 0 else model_scores[model_score_thr]for img_id in img_ids: gt_boxes_img = gt_boxes[img_id] box_scores = pred_boxes_pruned[img_id]['scores'] start_idx = 0 for score in box_scores: if score <= model_score_thr: pred_boxes_pruned[img_id] start_idx += 1 else: break # Remove boxes, scores of lower than threshold scores: pred_boxes_pruned[img_id]['scores']= pred_boxes_pruned[img_id]['scores'][start_idx:] pred_boxes_pruned[img_id]['boxes']= pred_boxes_pruned[img_id]['boxes'][start_idx:]# Recalculate image results for this image print(img_id) img_results[img_id] = get_single_image_results(gt_boxes_img, pred_boxes_pruned[img_id]['boxes'], iou_thr=0.5)# calculate precision and recall prec, rec = calc_precision_recall(img_results) precisions.append(prec) recalls.append(rec) model_thrs.append(model_score_thr)precisions = np.array(precisions) recalls = np.array(recalls) prec_at_rec = [] for recall_level in np.linspace(0.0, 1.0, 11): try: args= np.argwhere(recalls>recall_level).flatten() prec= max(precisions[args]) print(recalls,"Recall") print( recall_level,"Recall Level") print( args, "Args") print( prec, "precision") except ValueError: prec=0.0 prec_at_rec.append(prec) avg_prec = np.mean(prec_at_rec) return { 'avg_prec': avg_prec, 'precisions': precisions, 'recalls': recalls, 'model_thrs': model_thrs}
[ { "code": null, "e": 350, "s": 171, "text": "In this article, you will figure out how to use mAP to evaluate the performance of an object detection model. What is mAP? How to calculate mAP along with 11-point interpolation?" }, { "code": null, "e": 439, "s": 350, "text": "We use machine learning and deep learning to solve regression or classification problem." }, { "code": null, "e": 564, "s": 439, "text": "We used Root Mean Square(RMS) or Mean Average Percentage Error(MAPE) etc. to evaluate the performance of a regression model." }, { "code": null, "e": 651, "s": 564, "text": "Classification models are evaluated using Accuracy, Precision, Recall or an F1- Score." }, { "code": null, "e": 714, "s": 651, "text": "Is object detection, a classification or a regression problem?" }, { "code": null, "e": 833, "s": 714, "text": "Multiple deep learning algorithms exist for object detection like RCNN’s: Fast RCNN, Faster RCNN, YOLO, Mask RCNN etc." }, { "code": null, "e": 879, "s": 833, "text": "Objective of an object detection models is to" }, { "code": null, "e": 969, "s": 879, "text": "Classification: Identify if an object is present in the image and the class of the object" }, { "code": null, "e": 1164, "s": 969, "text": "Localization: Predict the co-ordinates of the bounding box around the object when an object is present in the image. Here we compare the co-ordinates of ground truth and predicted bounding boxes" }, { "code": null, "e": 1284, "s": 1164, "text": "We need to evaluate the performance of both classification as well as localization of using bounding boxes in the image" }, { "code": null, "e": 1345, "s": 1284, "text": "How do we measure the performance of object detection model?" }, { "code": null, "e": 1556, "s": 1345, "text": "For object detection we use the concept of Intersection over Union (IoU). IoU computes intersection over the union of the two bounding boxes; the bounding box for the ground truth and the predicted bounding box" }, { "code": null, "e": 1646, "s": 1556, "text": "An IoU of 1 implies that predicted and the ground-truth bounding boxes perfectly overlap." }, { "code": null, "e": 1746, "s": 1646, "text": "You can set a threshold value for the IoU to determine if the object detection is valid or not not." }, { "code": null, "e": 1789, "s": 1746, "text": "Let’s say you set IoU to 0.5, in that case" }, { "code": null, "e": 1853, "s": 1789, "text": "if IoU ≥0.5, classify the object detection as True Positive(TP)" }, { "code": null, "e": 1933, "s": 1853, "text": "if Iou <0.5, then it is a wrong detection and classify it as False Positive(FP)" }, { "code": null, "e": 2051, "s": 1933, "text": "When a ground truth is present in the image and model failed to detect the object, classify it as False Negative(FN)." }, { "code": null, "e": 2206, "s": 2051, "text": "True Negative (TN): TN is every part of the image where we did not predict an object. This metrics is not useful for object detection, hence we ignore TN." }, { "code": null, "e": 2294, "s": 2206, "text": "Set IoU threshold value to 0.5 or greater. It can be set to 0.5, 0.75. 0.9 or 0.95 etc." }, { "code": null, "e": 2470, "s": 2294, "text": "Use Precision and Recall as the metrics to evaluate the performance. Precision and Recall are calculated using true positives(TP), false positives(FP) and false negatives(FN)." }, { "code": null, "e": 2539, "s": 2470, "text": "Calculate precision and recall for all objects present in the image." }, { "code": null, "e": 2895, "s": 2539, "text": "You also need to consider the confidence score for each object detected by the model in the image. Consider all of the predicted bounding boxes with a confidence score above a certain threshold. Bounding boxes above the threshold value are considered as positive boxes and all predicted bounding boxes below the threshold value are considered as negative." }, { "code": null, "e": 2946, "s": 2895, "text": "How to calculate mAP using 11 point interpolation?" }, { "code": null, "e": 2980, "s": 2946, "text": "Step 1: Plot Precision and Recall" }, { "code": null, "e": 3291, "s": 2980, "text": "Plot the precision and recall values on a Precision Recall(PR) graph. PR graph is monotonically decreasing, there is always a trade-off between precision and recall. Increasing one will decrease the other. Sometimes PR graph is not always monotonically decreasing due to certain exceptions and/or lack of data." }, { "code": null, "e": 3380, "s": 3291, "text": "Step 2: Calculate the mean Average Precision(mAP), use 11 point interpolation technique." }, { "code": null, "e": 3532, "s": 3380, "text": "Interpolated precision is average precision measured at 11 equally spaced recall levels of 0.0, 0.1, 0.2, 0.3 ....0.9, 1.0 as shown in the figure above" }, { "code": null, "e": 3842, "s": 3532, "text": "The PR graph sometimes may not be monotonically decreasing, to resolve the issue, we set max of precision for a value of recall. Graphically, at each recall level, we replace each precision value with the maximum precision value to the right of that recall level i.e.; we take the maximum of all future points" }, { "code": null, "e": 3951, "s": 3842, "text": "The rationale is the willingness to look at higher precision values if both precision and recall get better." }, { "code": null, "e": 4085, "s": 3951, "text": "Finally calculate the arithmetic mean of the interpolated precision at each recall level for each information in the test collection." }, { "code": null, "e": 4135, "s": 4085, "text": "mAP is always calculated over the entire dataset." }, { "code": null, "e": 4237, "s": 4135, "text": "Let’s understand with an example as shown below, recall values are sorted for us to plot the PR graph" }, { "code": null, "e": 4325, "s": 4237, "text": "11 point interpolation will use the highest value for the precision for a recall value." }, { "code": null, "e": 4402, "s": 4325, "text": "We create 11 equally spaced recall levels of 0.0, 0.1, 0.2, 0.3 ....0.9, 1.0" }, { "code": null, "e": 4941, "s": 4402, "text": "Recall of 0.2 has the highest precision value of 1.00. Recall value of 0.4 has different precision values 0.4, 0.67, 0.5. In this scenario, we use the highest precision value of 0.67. When the precision value is 0.6, we have precision value of 0.5 but for a recall of 0.8, we see a higher precision value of 0.57. Based on the rationale for 11 point interpolation, we take the maximum of all future points, so the precision that we need consider is 0.57 instead of 0.5. Finally for a recall of 1.0, we take the max precision which is 0.5." }, { "code": null, "e": 5014, "s": 4941, "text": "Now plotting the Precision Recall as well as the Interpolated precision." }, { "code": null, "e": 5066, "s": 5014, "text": "We finally apply the mean average precision formula" }, { "code": null, "e": 5116, "s": 5066, "text": "AP =1/11(4* 1.0 + 2 * 0.67+ 4*0.57 + 1*0.5) =0.74" }, { "code": null, "e": 5186, "s": 5116, "text": "This gives us the mean average precision using 11 point interpolation" }, { "code": null, "e": 5280, "s": 5186, "text": "Pascal VOC Bounding box is defined by (x-top left, y-top left,x-bottom right, y-bottom right)" }, { "code": null, "e": 5844, "s": 5280, "text": "#GT Boxesgt_boxes= {\"img_00285.png\": [[480, 457, 515, 529], [637, 435, 676, 536]]}#Pred Boxespred_boxs={\"img_00285.png\": {\"boxes\": [[330, 463, 387, 505], [356, 456, 391, 521], [420, 433, 451, 498], [328, 465, 403, 540], [480, 477, 508, 522], [357, 460, 417, 537], [344, 459, 389, 493], [485, 459, 503, 511], [336, 463, 362, 496], [468, 435, 520, 521], [357, 458, 382, 485], [649, 479, 670, 531], [484, 455, 514, 519], [641, 439, 670, 532]], \"scores\": [0.0739, 0.0843, 0.091, 0.1008, 0.1012, 0.1058, 0.1243, 0.1266, 0.1342, 0.1618, 0.2452, 0.8505, 0.9113, 0.972]}}" }, { "code": null, "e": 5873, "s": 5844, "text": "Importing required libraries" }, { "code": null, "e": 6006, "s": 5873, "text": "import numpy as npfrom copy import deepcopyimport pandas as pdimport matplotlib.pyplot as pltimport seaborn as sns%matplotlib inline" }, { "code": null, "e": 6059, "s": 6006, "text": "Create a dictionary of image id and confidence score" }, { "code": null, "e": 6600, "s": 6059, "text": "def get_model_scores(pred_boxes): \"\"\"Creates a dictionary of from model_scores to image ids. Args: pred_boxes (dict): dict of dicts of 'boxes' and 'scores' Returns: dict: keys are model_scores and values are image ids (usually filenames) \"\"\" model_score={} for img_id, val in pred_boxes.items(): for score in val['scores']: if score not in model_score.keys(): model_score[score]=[img_id] else: model_score[score].append(img_id) return model_score" }, { "code": null, "e": 6660, "s": 6600, "text": "Calculate the IoU for bounding boxes with Pascal VOC format" }, { "code": null, "e": 8796, "s": 6660, "text": "def calc_iou( gt_bbox, pred_bbox): ''' This function takes the predicted bounding box and ground truth bounding box and return the IoU ratio ''' x_topleft_gt, y_topleft_gt, x_bottomright_gt, y_bottomright_gt= gt_bbox x_topleft_p, y_topleft_p, x_bottomright_p, y_bottomright_p= pred_bbox if (x_topleft_gt > x_bottomright_gt) or (y_topleft_gt> y_bottomright_gt): raise AssertionError(\"Ground Truth Bounding Box is not correct\") if (x_topleft_p > x_bottomright_p) or (y_topleft_p> y_bottomright_p): raise AssertionError(\"Predicted Bounding Box is not correct\",x_topleft_p, x_bottomright_p,y_topleft_p,y_bottomright_gt) #if the GT bbox and predcited BBox do not overlap then iou=0 if(x_bottomright_gt< x_topleft_p): # If bottom right of x-coordinate GT bbox is less than or above the top left of x coordinate of the predicted BBox return 0.0 if(y_bottomright_gt< y_topleft_p): # If bottom right of y-coordinate GT bbox is less than or above the top left of y coordinate of the predicted BBox return 0.0 if(x_topleft_gt> x_bottomright_p): # If bottom right of x-coordinate GT bbox is greater than or below the bottom right of x coordinate of the predcited BBox return 0.0 if(y_topleft_gt> y_bottomright_p): # If bottom right of y-coordinate GT bbox is greater than or below the bottom right of y coordinate of the predcited BBox return 0.0 GT_bbox_area = (x_bottomright_gt - x_topleft_gt + 1) * ( y_bottomright_gt -y_topleft_gt + 1) Pred_bbox_area =(x_bottomright_p - x_topleft_p + 1 ) * ( y_bottomright_p -y_topleft_p + 1) x_top_left =np.max([x_topleft_gt, x_topleft_p]) y_top_left = np.max([y_topleft_gt, y_topleft_p]) x_bottom_right = np.min([x_bottomright_gt, x_bottomright_p]) y_bottom_right = np.min([y_bottomright_gt, y_bottomright_p]) intersection_area = (x_bottom_right- x_top_left + 1) * (y_bottom_right-y_top_left + 1) union_area = (GT_bbox_area + Pred_bbox_area - intersection_area) return intersection_area/union_area" }, { "code": null, "e": 8827, "s": 8796, "text": "Calculate precision and recall" }, { "code": null, "e": 9760, "s": 8827, "text": "def calc_precision_recall(image_results): \"\"\"Calculates precision and recall from the set of images Args: img_results (dict): dictionary formatted like: { 'img_id1': {'true_pos': int, 'false_pos': int, 'false_neg': int}, 'img_id2': ... ... } Returns: tuple: of floats of (precision, recall) \"\"\" true_positive=0 false_positive=0 false_negative=0 for img_id, res in image_results.items(): true_positive +=res['true_positive'] false_positive += res['false_positive'] false_negative += res['false_negative'] try: precision = true_positive/(true_positive+ false_positive) except ZeroDivisionError: precision=0.0 try: recall = true_positive/(true_positive + false_negative) except ZeroDivisionError: recall=0.0 return (precision, recall)" }, { "code": null, "e": 9869, "s": 9760, "text": "Returns true positive, false positive and false negative for the batch of bounding boxes for a single image." }, { "code": null, "e": 11911, "s": 9869, "text": "def get_single_image_results(gt_boxes, pred_boxes, iou_thr): \"\"\"Calculates number of true_pos, false_pos, false_neg from single batch of boxes. Args: gt_boxes (list of list of floats): list of locations of ground truth objects as [xmin, ymin, xmax, ymax] pred_boxes (dict): dict of dicts of 'boxes' (formatted like `gt_boxes`) and 'scores' iou_thr (float): value of IoU to consider as threshold for a true prediction. Returns: dict: true positives (int), false positives (int), false negatives (int) \"\"\" all_pred_indices= range(len(pred_boxes)) all_gt_indices=range(len(gt_boxes)) if len(all_pred_indices)==0: tp=0 fp=0 fn=0 return {'true_positive':tp, 'false_positive':fp, 'false_negative':fn} if len(all_gt_indices)==0: tp=0 fp=0 fn=0 return {'true_positive':tp, 'false_positive':fp, 'false_negative':fn} gt_idx_thr=[] pred_idx_thr=[] ious=[] for ipb, pred_box in enumerate(pred_boxes): for igb, gt_box in enumerate(gt_boxes): iou= calc_iou(gt_box, pred_box) if iou >iou_thr: gt_idx_thr.append(igb) pred_idx_thr.append(ipb) ious.append(iou) iou_sort = np.argsort(ious)[::1] if len(iou_sort)==0: tp=0 fp=0 fn=0 return {'true_positive':tp, 'false_positive':fp, 'false_negative':fn} else: gt_match_idx=[] pred_match_idx=[] for idx in iou_sort: gt_idx=gt_idx_thr[idx] pr_idx= pred_idx_thr[idx] # If the boxes are unmatched, add them to matches if(gt_idx not in gt_match_idx) and (pr_idx not in pred_match_idx): gt_match_idx.append(gt_idx) pred_match_idx.append(pr_idx) tp= len(gt_match_idx) fp= len(pred_boxes) - len(pred_match_idx) fn = len(gt_boxes) - len(gt_match_idx) return {'true_positive': tp, 'false_positive': fp, 'false_negative': fn}" }, { "code": null, "e": 12060, "s": 11911, "text": "Finally calculating the mAP using 11 point interpolation technique. You can specify your IoU threshold here else a default value of 0.5 will be used" } ]
gRPC - Server Streaming RPC
Let us now discuss how server streaming works while using gRPC communication. In this case, the client will search for books with a given author. Assume the server requires some time to go through all the books. Instead of waiting to give all the books after going through all the books, the server instead would provide books in a streaming fashion, i.e., as soon as it finds one. First let us define the bookstore.proto file in common_proto_files − syntax = "proto3"; option java_package = "com.tp.bookstore"; service BookStore { rpc first (BookSearch) returns (stream Book) {} } message BookSearch { string name = 1; string author = 2; string genre = 3; } message Book { string name = 1; string author = 2; int32 price = 3; } The following block represents the name of the service "BookStore" and the function name "searchByAuthor" which can be called. The "searchByAuthor" function takes in the input of type "BookSearch" and returns the stream of type "Book". So, effectively, we let the client search for a title and return one of the book matching the author queried for. service BookStore { rpc searchByAuthor (BookSearch) returns (stream Book) {} } Now let us look at these types. message BookSearch { string name = 1; string author = 2; string genre = 3; } Here, we have defined BookSearch which contains a few attributes like name, author and genre. The client is supposed to send the object of type "BookSearch" to the server. message Book { string name = 1; string author = 2; int32 price = 3; } We have also defined that, given a "BookSearch", the server would return a stream of "Book" which contains the book attributes along with the price of the book. The server is supposed to send a stream of "Book". Note that we already had the Maven setup done for auto-generating our class files as well as our RPC code. So, now we can simply compile our project − mvn clean install This should auto-generate the source code required for us to use gRPC. The source code would be placed under − Protobuf class code: target/generated-sources/protobuf/java/com.tp.bookstore Protobuf gRPC code: target/generated-sources/protobuf/grpc-java/com.tp.bookstore Now that we have defined the proto file which contains the function definition, let us setup a server which can serve call these functions. Let us write our server code to serve the above function and save it in com.tp.bookstore.BookeStoreServerStreaming.java − package com.tp.bookstore; import io.grpc.Server; import io.grpc.ServerBuilder; import io.grpc.stub.StreamObserver; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.TimeUnit; import java.util.logging.Logger; import java.util.stream.Collectors; import com.tp.bookstore.BookStoreOuterClass.Book; import com.tp.bookstore.BookStoreOuterClass.BookSearch; public class BookeStoreServerUnary { private static final Logger logger = Logger.getLogger(BookeStoreServerrStreaming.class.getName()); static Map<String, Book> bookMap = new HashMap<>(); static { bookMap.put("Great Gatsby", Book.newBuilder().setName("Great Gatsby") .setAuthor("Scott Fitzgerald") .setPrice(300).build()); bookMap.put("To Kill MockingBird", Book.newBuilder().setName("To Kill MockingBird") .setAuthor("Harper Lee") .setPrice(400).build()); bookMap.put("Passage to India", Book.newBuilder().setName("Passage to India") .setAuthor("E.M.Forster") .setPrice(500).build()); bookMap.put("The Side of Paradise", Book.newBuilder().setName("The Side of Paradise") .setAuthor("Scott Fitzgerald") .setPrice(600).build()); bookMap.put("Go Set a Watchman", Book.newBuilder().setName("Go Set a Watchman") .setAuthor("Harper Lee") .setPrice(700).build()); } private Server server; private void start() throws IOException { int port = 50051; server = ServerBuilder.forPort(port) .addService(new BookStoreImpl()).build().start(); logger.info("Server started, listening on " + port); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { System.err.println("Shutting down gRPC server"); try { server.shutdown().awaitTermination(30, TimeUnit.SECONDS); } catch (InterruptedException e) { e.printStackTrace(System.err); } } }); } public static void main(String[] args) throws IOException, InterruptedException { final BookeStoreServerUnary greetServer = new BookeStoreServerUnary(); greetServer.start(); greetServer.server.awaitTermination(); } static class BookStoreImpl extends BookStoreGrpc.BookStoreImplBase { @Override public void searchByAuthor(BookSearch searchQuery, StreamObserver<Book> responseObserver) { logger.info("Searching for book with author: " + searchQuery.getAuthor()); for (Entry<String, Book> bookEntry : bookMap.entrySet()) { try { logger.info("Going through more books...."); Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } if(bookEntry.getValue().getAuthor().startsWith(searchQuery.getAuthor())){ logger.info("Found book with required author: " + bookEntry.getValue().getName()+ ". Sending...."); responseObserver.onNext(bookEntry.getValue()); } } responseObserver.onCompleted(); } } } The above code starts a gRPC server at a specified port and serves the functions and services which we had written in our proto file. Let us walk through the above code − Starting from the main method, we create a gRPC server at a specified port. Starting from the main method, we create a gRPC server at a specified port. But before starting the server, we assign the server the service which we want to run, i.e., in our case, the BookStore service. But before starting the server, we assign the server the service which we want to run, i.e., in our case, the BookStore service. For this purpose, we need to pass the service instance to the server, so we go ahead and create a service instance, i.e., in our case, the BookStoreImpl For this purpose, we need to pass the service instance to the server, so we go ahead and create a service instance, i.e., in our case, the BookStoreImpl The service instance need to provide an implementation of the method/function which is present in the .proto file, i.e., in our case, the searchByAuthor method. The service instance need to provide an implementation of the method/function which is present in the .proto file, i.e., in our case, the searchByAuthor method. The method expects an object of type as defined in the .proto file, i.e.,for us the BookSearch The method expects an object of type as defined in the .proto file, i.e.,for us the BookSearch Note that we have added a sleep to mimic the operation of searching through all the books. In case of streaming, the server does not wait for all the searched books to be available. It returns the book as soon it is available by using the onNext() call. Note that we have added a sleep to mimic the operation of searching through all the books. In case of streaming, the server does not wait for all the searched books to be available. It returns the book as soon it is available by using the onNext() call. When the server is done with the request, it shuts down the channel by calling onCompleted(). When the server is done with the request, it shuts down the channel by calling onCompleted(). Finally, we also have a shutdown hook to ensure clean shutting down of the server when we are done executing our code. Finally, we also have a shutdown hook to ensure clean shutting down of the server when we are done executing our code. Now that we have written the code for the server, let us setup a client which can call these functions. Let us write our client code to call the above function and save it in com.tp.bookstore.BookStoreClientServerStreamingBlocking.java − package com.tp.bookstore; import io.grpc.Channel; import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; import io.grpc.StatusRuntimeException; import java.util.Iterator; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.logging.Logger; import com.tp.bookstore.BookStoreOuterClass.Book; import com.tp.bookstore.BookStoreOuterClass.BookSearch; import com.tp.greeting.GreeterGrpc; import com.tp.greeting.Greeting.ServerOutput; import com.tp.greeting.Greeting.ClientInput; public class BookStoreClientServerStreamingBlocking { private static final Logger logger = Logger.getLogger(BookStoreClientServerStreamingBlocking.class.getName()); private final BookStoreGrpc.BookStoreBlockingStub blockingStub; public BookStoreClientServerStreamingBlocking(Channel channel) { blockingStub = BookStoreGrpc.newBlockingStub(channel); } public void getBook((String author) { logger.info("Querying for book with author: " + author); BookSearch request = BookSearch.newBuilder()..setAuthor(author).build(); Iterator<Book> response; try { response = blockingStub.searchByAuthor(request); while(response.hasNext()) { logger.info("Found book: " + response.next()); } } catch (StatusRuntimeException e) { logger.log(Level.WARNING, "RPC failed: {0}", e.getStatus()); return; } } public static void main(String[] args) throws Exception { String authorName = args[0]; String serverAddress = "localhost:50051"; ManagedChannel channel = ManagedChannelBuilder.forTarget(serverAddress) .usePlaintext() .build(); try { BookStoreClientServerStreamingBlocking client = new BookStoreClientUnaryBlocking(channel); client.getBook(authorName); } finally { channel.shutdownNow().awaitTermination(5, TimeUnit.SECONDS); } } } The above code starts a gRPC server at a specified port and serves the functions and services which we had written in our proto file. Let us walk through the above code − Starting from the main method, we accept one argument, i.e., the title of the book we want to search for. Starting from the main method, we accept one argument, i.e., the title of the book we want to search for. We setup a Channel for gRPC communication with our server. We setup a Channel for gRPC communication with our server. And then, we create a blocking stub using the channel. This is where we choose the service "BookStore" whose functions we plan to call. And then, we create a blocking stub using the channel. This is where we choose the service "BookStore" whose functions we plan to call. Then, we simply create the expected input defined in the .proto file,i.e., in our case, BookSearch, and we add the title that we want the server to search for. Then, we simply create the expected input defined in the .proto file,i.e., in our case, BookSearch, and we add the title that we want the server to search for. We ultimately make the call and get an iterator on valid Books. When we iterate, we get the corresponding Books made available by the Server. We ultimately make the call and get an iterator on valid Books. When we iterate, we get the corresponding Books made available by the Server. Finally, we close the channel to avoid any resource leak. Finally, we close the channel to avoid any resource leak. So, that is our client code. To sum up, what we want to do is the following − Start the gRPC server. Start the gRPC server. The Client queries the Server for a book with a given author. The Client queries the Server for a book with a given author. The Server searches the book in its store which is a time-consuming process. The Server searches the book in its store which is a time-consuming process. The Server responds whenever it finds a book with the given criteria. The Server does not wait for all the valid books to be available. It sends the output as soon as it finds one. And then repeats the process. The Server responds whenever it finds a book with the given criteria. The Server does not wait for all the valid books to be available. It sends the output as soon as it finds one. And then repeats the process. Now, that we have defined our proto file, written our server and the client code, let us proceed to execute this code and see things in action. For running the code, fire up two shells. Start the server on the first shell by executing the following command − java -cp .\target\grpc-point-1.0.jar com.tp.bookstore.BookeStoreServerStreaming We would see the following output − Jul 03, 2021 10:37:21 PM com.tp.bookstore.BookeStoreServerStreaming start INFO: Server started, listening on 50051 The above output means the server has started. Now, let us start the client. java -cp .\target\grpc-point-1.0.jar com.tp.bookstore.BookStoreClientServerStreamingBlocking "Har" We would see the following output − Jul 03, 2021 10:40:31 PM com.tp.bookstore.BookStoreClientServerStreamingBlocking getBook INFO: Querying for book with author: Har Jul 03, 2021 10:40:37 PM com.tp.bookstore.BookStoreClientServerStreamingBlocking getBook INFO: Found book: name: "Go Set a Watchman" author: "Harper Lee" price: 700 Jul 03, 2021 10:40:42 PM com.tp.bookstore.BookStoreClientServerStreamingBlocking getBook INFO: Found book: name: "To Kill MockingBird" author: "Harper Lee" price: 400 So, as we see, the client was able to get the book details by querying the server with the name of the book. But more importantly, the client got the 1st book and the 2nd book at different timestamps, i.e., a gap of almost 5 seconds. Print Add Notes Bookmark this page
[ { "code": null, "e": 2219, "s": 1837, "text": "Let us now discuss how server streaming works while using gRPC communication. In this case, the client will search for books with a given author. Assume the server requires some time to go through all the books. Instead of waiting to give all the books after going through all the books, the server instead would provide books in a streaming fashion, i.e., as soon as it finds one." }, { "code": null, "e": 2288, "s": 2219, "text": "First let us define the bookstore.proto file in common_proto_files −" }, { "code": null, "e": 2588, "s": 2288, "text": "syntax = \"proto3\";\noption java_package = \"com.tp.bookstore\";\nservice BookStore {\n rpc first (BookSearch) returns (stream Book) {}\n}\nmessage BookSearch {\n string name = 1;\n string author = 2;\n string genre = 3;\n}\nmessage Book {\n string name = 1;\n string author = 2;\n int32 price = 3;\n}\n" }, { "code": null, "e": 2938, "s": 2588, "text": "The following block represents the name of the service \"BookStore\" and the function name \"searchByAuthor\" which can be called. The \"searchByAuthor\" function takes in the input of type \"BookSearch\" and returns the stream of type \"Book\". So, effectively, we let the client search for a title and return one of the book matching the author queried for." }, { "code": null, "e": 3021, "s": 2938, "text": "service BookStore {\n rpc searchByAuthor (BookSearch) returns (stream Book) {}\n}\n" }, { "code": null, "e": 3053, "s": 3021, "text": "Now let us look at these types." }, { "code": null, "e": 3140, "s": 3053, "text": "message BookSearch {\n string name = 1;\n string author = 2;\n string genre = 3;\n}\n" }, { "code": null, "e": 3312, "s": 3140, "text": "Here, we have defined BookSearch which contains a few attributes like name, author and genre. The client is supposed to send the object of type \"BookSearch\" to the server." }, { "code": null, "e": 3392, "s": 3312, "text": "message Book {\n string name = 1;\n string author = 2;\n int32 price = 3;\n}\n" }, { "code": null, "e": 3604, "s": 3392, "text": "We have also defined that, given a \"BookSearch\", the server would return a stream of \"Book\" which contains the book attributes along with the price of the book. The server is supposed to send a stream of \"Book\"." }, { "code": null, "e": 3755, "s": 3604, "text": "Note that we already had the Maven setup done for auto-generating our class files as well as our RPC code. So, now we can simply compile our project −" }, { "code": null, "e": 3774, "s": 3755, "text": "mvn clean install\n" }, { "code": null, "e": 3885, "s": 3774, "text": "This should auto-generate the source code required for us to use gRPC. The source code would be placed under −" }, { "code": null, "e": 4044, "s": 3885, "text": "Protobuf class code: target/generated-sources/protobuf/java/com.tp.bookstore\nProtobuf gRPC code: target/generated-sources/protobuf/grpc-java/com.tp.bookstore\n" }, { "code": null, "e": 4184, "s": 4044, "text": "Now that we have defined the proto file which contains the function definition, let us setup a server which can serve call these functions." }, { "code": null, "e": 4306, "s": 4184, "text": "Let us write our server code to serve the above function and save it in com.tp.bookstore.BookeStoreServerStreaming.java −" }, { "code": null, "e": 7551, "s": 4306, "text": "package com.tp.bookstore;\n\nimport io.grpc.Server;\nimport io.grpc.ServerBuilder;\nimport io.grpc.stub.StreamObserver;\nimport java.io.IOException;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Map.Entry;\nimport java.util.concurrent.TimeUnit;\nimport java.util.logging.Logger;\nimport java.util.stream.Collectors;\n\nimport com.tp.bookstore.BookStoreOuterClass.Book;\nimport com.tp.bookstore.BookStoreOuterClass.BookSearch;\n\npublic class BookeStoreServerUnary {\n private static final Logger logger = Logger.getLogger(BookeStoreServerrStreaming.class.getName());\n \n static Map<String, Book> bookMap = new HashMap<>();\n static {\n bookMap.put(\"Great Gatsby\", Book.newBuilder().setName(\"Great Gatsby\")\n .setAuthor(\"Scott Fitzgerald\")\n .setPrice(300).build());\n bookMap.put(\"To Kill MockingBird\", Book.newBuilder().setName(\"To Kill MockingBird\")\n .setAuthor(\"Harper Lee\")\n .setPrice(400).build());\n bookMap.put(\"Passage to India\", Book.newBuilder().setName(\"Passage to India\")\n .setAuthor(\"E.M.Forster\")\n .setPrice(500).build());\n bookMap.put(\"The Side of Paradise\", Book.newBuilder().setName(\"The Side of Paradise\")\n .setAuthor(\"Scott Fitzgerald\")\n .setPrice(600).build());\n bookMap.put(\"Go Set a Watchman\", Book.newBuilder().setName(\"Go Set a Watchman\")\n .setAuthor(\"Harper Lee\")\n .setPrice(700).build());\n }\n private Server server;\n \n private void start() throws IOException {\n int port = 50051;\n server = ServerBuilder.forPort(port)\n .addService(new BookStoreImpl()).build().start();\n \n logger.info(\"Server started, listening on \" + port);\n \n Runtime.getRuntime().addShutdownHook(new Thread() {\n @Override\n public void run() {\n System.err.println(\"Shutting down gRPC server\");\n try {\n server.shutdown().awaitTermination(30, TimeUnit.SECONDS);\n } catch (InterruptedException e) {\n e.printStackTrace(System.err);\n }\n }\n });\n }\n public static void main(String[] args) throws IOException, InterruptedException {\n final BookeStoreServerUnary greetServer = new BookeStoreServerUnary();\n greetServer.start();\n greetServer.server.awaitTermination();\n }\n static class BookStoreImpl extends BookStoreGrpc.BookStoreImplBase {\n @Override\n public void searchByAuthor(BookSearch searchQuery, StreamObserver<Book> responseObserver) {\n logger.info(\"Searching for book with author: \" + searchQuery.getAuthor());\n for (Entry<String, Book> bookEntry : bookMap.entrySet()) {\n try {\n logger.info(\"Going through more books....\");\n Thread.sleep(5000);\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n \n if(bookEntry.getValue().getAuthor().startsWith(searchQuery.getAuthor())){\n logger.info(\"Found book with required author: \" + bookEntry.getValue().getName()+ \". Sending....\");\n\n responseObserver.onNext(bookEntry.getValue());\n } \n }\n responseObserver.onCompleted();\n }\n }\n}" }, { "code": null, "e": 7722, "s": 7551, "text": "The above code starts a gRPC server at a specified port and serves the functions and services which we had written in our proto file. Let us walk through the above code −" }, { "code": null, "e": 7798, "s": 7722, "text": "Starting from the main method, we create a gRPC server at a specified port." }, { "code": null, "e": 7874, "s": 7798, "text": "Starting from the main method, we create a gRPC server at a specified port." }, { "code": null, "e": 8003, "s": 7874, "text": "But before starting the server, we assign the server the service which we want to run, i.e., in our case, the BookStore service." }, { "code": null, "e": 8132, "s": 8003, "text": "But before starting the server, we assign the server the service which we want to run, i.e., in our case, the BookStore service." }, { "code": null, "e": 8285, "s": 8132, "text": "For this purpose, we need to pass the service instance to the server, so we go ahead and create a service instance, i.e., in our case, the BookStoreImpl" }, { "code": null, "e": 8438, "s": 8285, "text": "For this purpose, we need to pass the service instance to the server, so we go ahead and create a service instance, i.e., in our case, the BookStoreImpl" }, { "code": null, "e": 8599, "s": 8438, "text": "The service instance need to provide an implementation of the method/function which is present in the .proto file, i.e., in our case, the searchByAuthor method." }, { "code": null, "e": 8760, "s": 8599, "text": "The service instance need to provide an implementation of the method/function which is present in the .proto file, i.e., in our case, the searchByAuthor method." }, { "code": null, "e": 8855, "s": 8760, "text": "The method expects an object of type as defined in the .proto file, i.e.,for us the BookSearch" }, { "code": null, "e": 8950, "s": 8855, "text": "The method expects an object of type as defined in the .proto file, i.e.,for us the BookSearch" }, { "code": null, "e": 9204, "s": 8950, "text": "Note that we have added a sleep to mimic the operation of searching through all the books. In case of streaming, the server does not wait for all the searched books to be available. It returns the book as soon it is available by using the onNext() call." }, { "code": null, "e": 9458, "s": 9204, "text": "Note that we have added a sleep to mimic the operation of searching through all the books. In case of streaming, the server does not wait for all the searched books to be available. It returns the book as soon it is available by using the onNext() call." }, { "code": null, "e": 9552, "s": 9458, "text": "When the server is done with the request, it shuts down the channel by calling onCompleted()." }, { "code": null, "e": 9646, "s": 9552, "text": "When the server is done with the request, it shuts down the channel by calling onCompleted()." }, { "code": null, "e": 9765, "s": 9646, "text": "Finally, we also have a shutdown hook to ensure clean shutting down of the server when we are done executing our code." }, { "code": null, "e": 9884, "s": 9765, "text": "Finally, we also have a shutdown hook to ensure clean shutting down of the server when we are done executing our code." }, { "code": null, "e": 9988, "s": 9884, "text": "Now that we have written the code for the server, let us setup a client which can call these functions." }, { "code": null, "e": 10122, "s": 9988, "text": "Let us write our client code to call the above function and save it in com.tp.bookstore.BookStoreClientServerStreamingBlocking.java −" }, { "code": null, "e": 12072, "s": 10122, "text": "package com.tp.bookstore;\n\nimport io.grpc.Channel;\nimport io.grpc.ManagedChannel;\nimport io.grpc.ManagedChannelBuilder;\nimport io.grpc.StatusRuntimeException;\n\nimport java.util.Iterator;\nimport java.util.concurrent.TimeUnit;\nimport java.util.logging.Level;\nimport java.util.logging.Logger;\n\nimport com.tp.bookstore.BookStoreOuterClass.Book;\nimport com.tp.bookstore.BookStoreOuterClass.BookSearch;\nimport com.tp.greeting.GreeterGrpc;\nimport com.tp.greeting.Greeting.ServerOutput;\nimport com.tp.greeting.Greeting.ClientInput;\n\npublic class BookStoreClientServerStreamingBlocking {\n private static final Logger logger = Logger.getLogger(BookStoreClientServerStreamingBlocking.class.getName());\n private final BookStoreGrpc.BookStoreBlockingStub blockingStub;\n\tpublic BookStoreClientServerStreamingBlocking(Channel channel) {\n blockingStub = BookStoreGrpc.newBlockingStub(channel);\n }\n public void getBook((String author) {\n logger.info(\"Querying for book with author: \" + author);\n BookSearch request = BookSearch.newBuilder()..setAuthor(author).build();\n Iterator<Book> response; \n try {\n response = blockingStub.searchByAuthor(request);\n while(response.hasNext()) {\n logger.info(\"Found book: \" + response.next());\n }\n } catch (StatusRuntimeException e) {\n logger.log(Level.WARNING, \"RPC failed: {0}\", e.getStatus());\n return;\n }\n }\n public static void main(String[] args) throws Exception {\n String authorName = args[0];\n String serverAddress = \"localhost:50051\";\n\t \n ManagedChannel channel = ManagedChannelBuilder.forTarget(serverAddress)\n .usePlaintext()\n .build();\n \n try {\n BookStoreClientServerStreamingBlocking client = new BookStoreClientUnaryBlocking(channel);\n client.getBook(authorName);\n } finally {\n channel.shutdownNow().awaitTermination(5, TimeUnit.SECONDS);\n }\n }\n}" }, { "code": null, "e": 12243, "s": 12072, "text": "The above code starts a gRPC server at a specified port and serves the functions and services which we had written in our proto file. Let us walk through the above code −" }, { "code": null, "e": 12349, "s": 12243, "text": "Starting from the main method, we accept one argument, i.e., the title of the book we want to search for." }, { "code": null, "e": 12455, "s": 12349, "text": "Starting from the main method, we accept one argument, i.e., the title of the book we want to search for." }, { "code": null, "e": 12514, "s": 12455, "text": "We setup a Channel for gRPC communication with our server." }, { "code": null, "e": 12573, "s": 12514, "text": "We setup a Channel for gRPC communication with our server." }, { "code": null, "e": 12709, "s": 12573, "text": "And then, we create a blocking stub using the channel. This is where we choose the service \"BookStore\" whose functions we plan to call." }, { "code": null, "e": 12845, "s": 12709, "text": "And then, we create a blocking stub using the channel. This is where we choose the service \"BookStore\" whose functions we plan to call." }, { "code": null, "e": 13005, "s": 12845, "text": "Then, we simply create the expected input defined in the .proto file,i.e., in our case, BookSearch, and we add the title that we want the server to search for." }, { "code": null, "e": 13165, "s": 13005, "text": "Then, we simply create the expected input defined in the .proto file,i.e., in our case, BookSearch, and we add the title that we want the server to search for." }, { "code": null, "e": 13307, "s": 13165, "text": "We ultimately make the call and get an iterator on valid Books. When we iterate, we get the corresponding Books made available by the Server." }, { "code": null, "e": 13449, "s": 13307, "text": "We ultimately make the call and get an iterator on valid Books. When we iterate, we get the corresponding Books made available by the Server." }, { "code": null, "e": 13507, "s": 13449, "text": "Finally, we close the channel to avoid any resource leak." }, { "code": null, "e": 13565, "s": 13507, "text": "Finally, we close the channel to avoid any resource leak." }, { "code": null, "e": 13594, "s": 13565, "text": "So, that is our client code." }, { "code": null, "e": 13643, "s": 13594, "text": "To sum up, what we want to do is the following −" }, { "code": null, "e": 13666, "s": 13643, "text": "Start the gRPC server." }, { "code": null, "e": 13689, "s": 13666, "text": "Start the gRPC server." }, { "code": null, "e": 13751, "s": 13689, "text": "The Client queries the Server for a book with a given author." }, { "code": null, "e": 13813, "s": 13751, "text": "The Client queries the Server for a book with a given author." }, { "code": null, "e": 13890, "s": 13813, "text": "The Server searches the book in its store which is a time-consuming process." }, { "code": null, "e": 13967, "s": 13890, "text": "The Server searches the book in its store which is a time-consuming process." }, { "code": null, "e": 14178, "s": 13967, "text": "The Server responds whenever it finds a book with the given criteria. The Server does not wait for all the valid books to be available. It sends the output as soon as it finds one. And then repeats the process." }, { "code": null, "e": 14389, "s": 14178, "text": "The Server responds whenever it finds a book with the given criteria. The Server does not wait for all the valid books to be available. It sends the output as soon as it finds one. And then repeats the process." }, { "code": null, "e": 14533, "s": 14389, "text": "Now, that we have defined our proto file, written our server and the client code, let us proceed to execute this code and see things in action." }, { "code": null, "e": 14648, "s": 14533, "text": "For running the code, fire up two shells. Start the server on the first shell by executing the following command −" }, { "code": null, "e": 14730, "s": 14648, "text": "java -cp .\\target\\grpc-point-1.0.jar \ncom.tp.bookstore.BookeStoreServerStreaming\n" }, { "code": null, "e": 14766, "s": 14730, "text": "We would see the following output −" }, { "code": null, "e": 14883, "s": 14766, "text": "Jul 03, 2021 10:37:21 PM \ncom.tp.bookstore.BookeStoreServerStreaming start\nINFO: Server started, listening on 50051\n" }, { "code": null, "e": 14930, "s": 14883, "text": "The above output means the server has started." }, { "code": null, "e": 14960, "s": 14930, "text": "Now, let us start the client." }, { "code": null, "e": 15061, "s": 14960, "text": "java -cp .\\target\\grpc-point-1.0.jar \ncom.tp.bookstore.BookStoreClientServerStreamingBlocking \"Har\"\n" }, { "code": null, "e": 15097, "s": 15061, "text": "We would see the following output −" }, { "code": null, "e": 15568, "s": 15097, "text": "Jul 03, 2021 10:40:31 PM \ncom.tp.bookstore.BookStoreClientServerStreamingBlocking \ngetBook\nINFO: Querying for book with author: Har\n\nJul 03, 2021 10:40:37 PM \ncom.tp.bookstore.BookStoreClientServerStreamingBlocking \ngetBook\nINFO: Found book: name: \"Go Set a Watchman\"\nauthor: \"Harper Lee\"\nprice: 700\n\nJul 03, 2021 10:40:42 PM \ncom.tp.bookstore.BookStoreClientServerStreamingBlocking \ngetBook\nINFO: Found book: name: \"To Kill MockingBird\"\nauthor: \"Harper Lee\"\nprice: 400\n" }, { "code": null, "e": 15802, "s": 15568, "text": "So, as we see, the client was able to get the book details by querying the server with the name of the book. But more importantly, the client got the 1st book and the 2nd book at different timestamps, i.e., a gap of almost 5 seconds." }, { "code": null, "e": 15809, "s": 15802, "text": " Print" }, { "code": null, "e": 15820, "s": 15809, "text": " Add Notes" } ]
How to toggle a boolean using JavaScript?
Following is the code for toggling a Boolean using JavaScript − Live Demo <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .result { font-weight: 500; font-size: 18px; color: blueviolet; } </style> </head> <body> <h1>Toggle a boolean using JavaScript</h1> <div class="result"></div> <button class="Btn">Toggle</button> <h3>Click on the above button to toggle the above boolean value</h3> <script> let BtnEle = document.querySelector(".Btn"); let resEle = document.querySelector(".result"); let boolVal = true; resEle.innerHTML = boolVal; BtnEle.addEventListener("click", () => { boolVal = !boolVal; resEle.innerHTML = boolVal; }); </script> </body> </html> On clicking the Toggle button −
[ { "code": null, "e": 1126, "s": 1062, "text": "Following is the code for toggling a Boolean using JavaScript −" }, { "code": null, "e": 1137, "s": 1126, "text": " Live Demo" }, { "code": null, "e": 1978, "s": 1137, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\" />\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n<title>Document</title>\n<style>\n body {\n font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif;\n }\n .result {\n font-weight: 500;\n font-size: 18px;\n color: blueviolet;\n }\n</style>\n</head>\n<body>\n<h1>Toggle a boolean using JavaScript</h1>\n<div class=\"result\"></div>\n<button class=\"Btn\">Toggle</button>\n<h3>Click on the above button to toggle the above boolean value</h3>\n<script>\n let BtnEle = document.querySelector(\".Btn\");\n let resEle = document.querySelector(\".result\");\n let boolVal = true;\n resEle.innerHTML = boolVal;\n BtnEle.addEventListener(\"click\", () => {\n boolVal = !boolVal;\n resEle.innerHTML = boolVal;\n });\n</script>\n</body>\n</html>" }, { "code": null, "e": 2010, "s": 1978, "text": "On clicking the Toggle button −" } ]
CSS Box Shadow
The CSS box-shadow property is used to apply one or more shadows to an element. In its simplest use, you only specify a horizontal and a vertical shadow. The default color of the shadow is the current text-color. Specify a horizontal and a vertical shadow: The color parameter defines the color of the shadow. Specify a color for the shadow: The blur parameter defines the blur radius. The higher the number, the more blurred the shadow will be. Add a blur effect to the shadow: The spread parameter defines the spread radius. A positive value increases the size of the shadow, a negative value decreases the size of the shadow. Set the spread radius of the shadow: The inset parameter changes the shadow from an outer shadow (outset) to an inner shadow. Add the inset parameter: An element can also have multiple shadows: You can also use the box-shadow property to create paper-like cards: January 1, 2021 Hardanger, Norway Set a "2px" horizontal, and "2px" vertical, text shadow for the <h1> element. <style> h1 { : 2px 2px; } </style> <body> <h1>This is a heading</h1> <p>This is a paragraph</p> <p>This is a paragraph</p> </body> Start the Exercise The following table lists the CSS shadow properties: We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: [email protected] Your message has been sent to W3Schools.
[ { "code": null, "e": 81, "s": 0, "text": "The CSS box-shadow property is used to apply \none or more shadows to an element." }, { "code": null, "e": 215, "s": 81, "text": "In its simplest use, you only specify a horizontal and a vertical shadow. The \ndefault color of the shadow is the current text-color." }, { "code": null, "e": 259, "s": 215, "text": "Specify a horizontal and a vertical shadow:" }, { "code": null, "e": 313, "s": 259, "text": "The color parameter defines the color of the \nshadow." }, { "code": null, "e": 345, "s": 313, "text": "Specify a color for the shadow:" }, { "code": null, "e": 450, "s": 345, "text": "The blur parameter defines the blur radius. The higher the number, the more \nblurred the shadow will be." }, { "code": null, "e": 483, "s": 450, "text": "Add a blur effect to the shadow:" }, { "code": null, "e": 634, "s": 483, "text": "The spread parameter defines the spread radius. A positive value increases \nthe size of the shadow, a negative value decreases the size of the shadow." }, { "code": null, "e": 671, "s": 634, "text": "Set the spread radius of the shadow:" }, { "code": null, "e": 761, "s": 671, "text": "The inset parameter changes the shadow from \nan outer shadow (outset) to an inner shadow." }, { "code": null, "e": 786, "s": 761, "text": "Add the inset parameter:" }, { "code": null, "e": 829, "s": 786, "text": "An element can also have multiple shadows:" }, { "code": null, "e": 898, "s": 829, "text": "You can also use the box-shadow property to create paper-like cards:" }, { "code": null, "e": 914, "s": 898, "text": "January 1, 2021" }, { "code": null, "e": 932, "s": 914, "text": "Hardanger, Norway" }, { "code": null, "e": 1010, "s": 932, "text": "Set a \"2px\" horizontal, and \"2px\" vertical, text shadow for the <h1> element." }, { "code": null, "e": 1151, "s": 1010, "text": "<style>\nh1 {\n : 2px 2px;\n}\n</style>\n\n<body>\n <h1>This is a heading</h1>\n <p>This is a paragraph</p>\n <p>This is a paragraph</p>\n</body>\n" }, { "code": null, "e": 1170, "s": 1151, "text": "Start the Exercise" }, { "code": null, "e": 1223, "s": 1170, "text": "The following table lists the CSS shadow properties:" }, { "code": null, "e": 1256, "s": 1223, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 1298, "s": 1256, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 1405, "s": 1298, "text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:" }, { "code": null, "e": 1424, "s": 1405, "text": "[email protected]" } ]
Structuring Text with Graph Representations | by Diogo A.P. Nunes | Towards Data Science
Text is a type of data that, when explored correctly, can be a source of valuable information. However, it can be challenging to explore data in textual form, especially free-text. Free-text lacks explicit structure and standardisation. In this post I will show you how to represent free-text with a graph, making its structure explicit and easily manageable by downstream algorithms. There are various Natural Language Processing (NLP) tasks that can benefit from graph representations of free-text, such as Keyword Extraction and Summarisation. This is so because the implicit structure of text is now explicit in the form of a graph, which can be explored with standard graph-based algorithms, such as Centrality, Shortest Paths, Connected Parts, and many others. In this post, I will present 3 different graph representations of a textual document. These are: 1) Undirected, unweighted graph;2) Directed, unweighted graph;3) Directed, weighted graph; Whatever the representation is, the main idea is always the same: first, identify entities in the text to represent as nodes in the graph, and, second, identify relations between those entities to represent as edges between nodes in the graph. The exact types of entities and relations are context and task dependent. Entities can be individual words, bigrams, n-grams, sequences of variable lengths, etc.; Relations can represent adjacency between entities in a sentence, co-occurrence in a window of fixed length, some kind of semantic or syntactic relation, etc. To keep it simple and approachable, I will consider individual words as nodes and them being adjacent (i.e., they form a bigram in a sentence) as a relation. Even though I will present a Python implementation, based on NetworkX, all ideas and methods are easily transferable to any other implementation. The following document will be our running example (adapted from Wikipedia): In mathematics, graph theory is the study of graphs, which are mathematical structures used to model pairwise relations between objects. A graph in this context is made up of vertices, also called nodes or points, which are connected by edges, also called links or lines. A distinction is made between undirected graphs, where edges link two vertices symmetrically, and directed graphs, where edges link two vertices asymmetrically. Graphs are one of the principal objects of study in discrete mathematics. As noted before, whatever the graph representation, the high-level method is always the same, in this case, composed of 4 steps: Document preprocessing;Identify entities (nodes in the graph);Identify relations (edges in the graph);Build the actual graph. Document preprocessing; Identify entities (nodes in the graph); Identify relations (edges in the graph); Build the actual graph. I will go over each of these steps now (and respective implementations). The implementation of each of these steps, especially the entity and relation getters, is what we have change to build the other graph representations. According to the specifications above, individual words are nodes, and bigrams in sentences are edges. Thus, the preprocessing step must split the document in sentences and each sentence in words. Moreover, because we want to minimize variability, it must also lowercase all text (e.g., words “Hello” and “hello” are considered the same term). Because we are disregarding punctuation marks in our task definition, they are also removed. According to our definition, individual words are nodes in the graph. Thus, for each unique word in the document, there must be a node. According to our definition, there exists an edge between two nodes in the graph if the corresponding words form a bigram in a sentence of the input document. Fortunately, in the pre-processing step, we split the document accordingly, which facilitates this calculation. Now that we have the nodes and the edges, we can easily build the actual graph. In this example, I use NetworkX to build a graph object. We can now plot the actual graph with a simple function. As noted before, in order to create a directed graph, we only have to change slightly the way we build the graph. We will define the direction of the edge between two nodes as that of the order in which the corresponding words appear in a bigram. Thus, the bigram “a graph” will result in an edge from the node “a” to the node “graph”. Fortunately, the bigrams that we were capturing before already take into account the original word order in the text (i.e., we are never purposefully changing their order). This means that the only thing we need to change is the section where we build the actual graph object (in this case, with NetworkX), to tell it to take into consideration the direction of the edges. Thus, we only need to change the line: G = nx.Graph() To (DiGraph stands for Directed Graph): G = nx.DiGraph() And we are done. Finally, the last piece corresponds to adding weights to the edges of the graph. In this case, we will weight each edge according to the number of the times the corresponding bigram appears in the document. Thus, if the bigram “a graph” appears 3 times in the document, the directed edge that links the nodes “a” and “graph” (in that direction) has weight equal to 3. Thus, we need to change the relation getter defined before, to count the number of times each bigram is seen in the document. And, finally, adapt the main function to account for the new weighted edge getter. Notice that the graph built is still a DiGraph, just like before, but the method to add weighted edges has a slightly different interface (different name). Converting free-text to a graph representation makes the text’s implicit structure explicit. This means that now you have immediate access to information such as which words are most commonly used (degree), which n-grams are most commonly used, which words are most commonly used to flow information (paths in the graph between every two nodes), and much more. NetworkX provides a large amount of methods to apply to your graphs and extract valuable information. I will make future posts on information extraction from text, some of which will be largely based on the graph representations we saw in this post. Edit (22 Oct. 2021): You can learn and see an example in my new post on how to apply graph representations of text for Keyphrase/Keyword Extraction.
[ { "code": null, "e": 353, "s": 172, "text": "Text is a type of data that, when explored correctly, can be a source of valuable information. However, it can be challenging to explore data in textual form, especially free-text." }, { "code": null, "e": 939, "s": 353, "text": "Free-text lacks explicit structure and standardisation. In this post I will show you how to represent free-text with a graph, making its structure explicit and easily manageable by downstream algorithms. There are various Natural Language Processing (NLP) tasks that can benefit from graph representations of free-text, such as Keyword Extraction and Summarisation. This is so because the implicit structure of text is now explicit in the form of a graph, which can be explored with standard graph-based algorithms, such as Centrality, Shortest Paths, Connected Parts, and many others." }, { "code": null, "e": 1036, "s": 939, "text": "In this post, I will present 3 different graph representations of a textual document. These are:" }, { "code": null, "e": 1127, "s": 1036, "text": "1) Undirected, unweighted graph;2) Directed, unweighted graph;3) Directed, weighted graph;" }, { "code": null, "e": 1445, "s": 1127, "text": "Whatever the representation is, the main idea is always the same: first, identify entities in the text to represent as nodes in the graph, and, second, identify relations between those entities to represent as edges between nodes in the graph. The exact types of entities and relations are context and task dependent." }, { "code": null, "e": 1693, "s": 1445, "text": "Entities can be individual words, bigrams, n-grams, sequences of variable lengths, etc.; Relations can represent adjacency between entities in a sentence, co-occurrence in a window of fixed length, some kind of semantic or syntactic relation, etc." }, { "code": null, "e": 1851, "s": 1693, "text": "To keep it simple and approachable, I will consider individual words as nodes and them being adjacent (i.e., they form a bigram in a sentence) as a relation." }, { "code": null, "e": 1997, "s": 1851, "text": "Even though I will present a Python implementation, based on NetworkX, all ideas and methods are easily transferable to any other implementation." }, { "code": null, "e": 2074, "s": 1997, "text": "The following document will be our running example (adapted from Wikipedia):" }, { "code": null, "e": 2581, "s": 2074, "text": "In mathematics, graph theory is the study of graphs, which are mathematical structures used to model pairwise relations between objects. A graph in this context is made up of vertices, also called nodes or points, which are connected by edges, also called links or lines. A distinction is made between undirected graphs, where edges link two vertices symmetrically, and directed graphs, where edges link two vertices asymmetrically. Graphs are one of the principal objects of study in discrete mathematics." }, { "code": null, "e": 2710, "s": 2581, "text": "As noted before, whatever the graph representation, the high-level method is always the same, in this case, composed of 4 steps:" }, { "code": null, "e": 2836, "s": 2710, "text": "Document preprocessing;Identify entities (nodes in the graph);Identify relations (edges in the graph);Build the actual graph." }, { "code": null, "e": 2860, "s": 2836, "text": "Document preprocessing;" }, { "code": null, "e": 2900, "s": 2860, "text": "Identify entities (nodes in the graph);" }, { "code": null, "e": 2941, "s": 2900, "text": "Identify relations (edges in the graph);" }, { "code": null, "e": 2965, "s": 2941, "text": "Build the actual graph." }, { "code": null, "e": 3190, "s": 2965, "text": "I will go over each of these steps now (and respective implementations). The implementation of each of these steps, especially the entity and relation getters, is what we have change to build the other graph representations." }, { "code": null, "e": 3627, "s": 3190, "text": "According to the specifications above, individual words are nodes, and bigrams in sentences are edges. Thus, the preprocessing step must split the document in sentences and each sentence in words. Moreover, because we want to minimize variability, it must also lowercase all text (e.g., words “Hello” and “hello” are considered the same term). Because we are disregarding punctuation marks in our task definition, they are also removed." }, { "code": null, "e": 3763, "s": 3627, "text": "According to our definition, individual words are nodes in the graph. Thus, for each unique word in the document, there must be a node." }, { "code": null, "e": 4034, "s": 3763, "text": "According to our definition, there exists an edge between two nodes in the graph if the corresponding words form a bigram in a sentence of the input document. Fortunately, in the pre-processing step, we split the document accordingly, which facilitates this calculation." }, { "code": null, "e": 4228, "s": 4034, "text": "Now that we have the nodes and the edges, we can easily build the actual graph. In this example, I use NetworkX to build a graph object. We can now plot the actual graph with a simple function." }, { "code": null, "e": 4342, "s": 4228, "text": "As noted before, in order to create a directed graph, we only have to change slightly the way we build the graph." }, { "code": null, "e": 4937, "s": 4342, "text": "We will define the direction of the edge between two nodes as that of the order in which the corresponding words appear in a bigram. Thus, the bigram “a graph” will result in an edge from the node “a” to the node “graph”. Fortunately, the bigrams that we were capturing before already take into account the original word order in the text (i.e., we are never purposefully changing their order). This means that the only thing we need to change is the section where we build the actual graph object (in this case, with NetworkX), to tell it to take into consideration the direction of the edges." }, { "code": null, "e": 4976, "s": 4937, "text": "Thus, we only need to change the line:" }, { "code": null, "e": 4991, "s": 4976, "text": "G = nx.Graph()" }, { "code": null, "e": 5031, "s": 4991, "text": "To (DiGraph stands for Directed Graph):" }, { "code": null, "e": 5048, "s": 5031, "text": "G = nx.DiGraph()" }, { "code": null, "e": 5065, "s": 5048, "text": "And we are done." }, { "code": null, "e": 5433, "s": 5065, "text": "Finally, the last piece corresponds to adding weights to the edges of the graph. In this case, we will weight each edge according to the number of the times the corresponding bigram appears in the document. Thus, if the bigram “a graph” appears 3 times in the document, the directed edge that links the nodes “a” and “graph” (in that direction) has weight equal to 3." }, { "code": null, "e": 5559, "s": 5433, "text": "Thus, we need to change the relation getter defined before, to count the number of times each bigram is seen in the document." }, { "code": null, "e": 5798, "s": 5559, "text": "And, finally, adapt the main function to account for the new weighted edge getter. Notice that the graph built is still a DiGraph, just like before, but the method to add weighted edges has a slightly different interface (different name)." }, { "code": null, "e": 6261, "s": 5798, "text": "Converting free-text to a graph representation makes the text’s implicit structure explicit. This means that now you have immediate access to information such as which words are most commonly used (degree), which n-grams are most commonly used, which words are most commonly used to flow information (paths in the graph between every two nodes), and much more. NetworkX provides a large amount of methods to apply to your graphs and extract valuable information." }, { "code": null, "e": 6409, "s": 6261, "text": "I will make future posts on information extraction from text, some of which will be largely based on the graph representations we saw in this post." } ]
Check if an Array is a permutation of numbers from 1 to N : Set 2 - GeeksforGeeks
21 May, 2021 Given an array arr containing N positive integers, the task is to check if the given array arr represents a permutation or not. A sequence of N integers is called a permutation if it contains all integers from 1 to N exactly once. Examples: Input: arr[] = {1, 2, 5, 3, 2} Output: No Explanation: The given array contains 2 twice, and 4 is missing for the array to represent a permutation of length 5. Input: arr[] = {1, 2, 5, 3, 4} Output: Yes Explanation: The given array contains all integers from 1 to 5 exactly once. Hence, it represents a permutation of length 5. Naive Approach: in O(N2) Time This approach is mentioned hereAnother Approach: in O(N) Time and O(N) Space This approach is mentioned here.Efficient Approach: Using HashTable Create a HashTable of N size to store the frequency count of each number from 1 to NTraverse through the given array and store the frequency of each number in the HashTable.Then traverse the HashTable and check if all the numbers from 1 to N have a frequency of 1 or not. Print “Yes” if the above condition is True, Else “No”. Create a HashTable of N size to store the frequency count of each number from 1 to N Traverse through the given array and store the frequency of each number in the HashTable. Then traverse the HashTable and check if all the numbers from 1 to N have a frequency of 1 or not. Print “Yes” if the above condition is True, Else “No”. Below is the implementation of the above approach: CPP Java Python3 C# Javascript // C++ program to decide if an array// represents a permutation or not#include <bits/stdc++.h>using namespace std; // Function to check if an// array represents a permutation or notstring permutation(int arr[], int N){ int hash[N + 1] = { 0 }; // Counting the frequency for (int i = 0; i < N; i++) { hash[arr[i]]++; } // Check if each frequency is 1 only for (int i = 1; i <= N; i++) { if (hash[i] != 1) return "No"; } return "Yes";} // Driver codeint main(){ int arr[] = { 1, 1, 5, 5, 3 }; int n = sizeof(arr) / sizeof(int); cout << permutation(arr, n) << endl; return 0;} // Java program to decide if an array// represents a permutation or notclass GFG{ // Function to check if an// array represents a permutation or notstatic String permutation(int arr[], int N){ int []hash = new int[N + 1]; // Counting the frequency for (int i = 0; i < N; i++) { hash[arr[i]]++; } // Check if each frequency is 1 only for (int i = 1; i <= N; i++) { if (hash[i] != 1) return "No"; } return "Yes";} // Driver codepublic static void main(String[] args){ int arr[] = { 1, 1, 5, 5, 3 }; int n = arr.length; System.out.print(permutation(arr, n) +"\n");}} // This code is contributed by Princi Singh # Python3 program to decide if an array# represents a permutation or not # Function to check if an# array represents a permutation or notdef permutation(arr, N) : hash = [0]*(N + 1); # Counting the frequency for i in range(N) : hash[arr[i]] += 1; # Check if each frequency is 1 only for i in range(1, N + 1) : if (hash[i] != 1) : return "No"; return "Yes"; # Driver codeif __name__ == "__main__" : arr = [ 1, 1, 5, 5, 3 ]; n = len(arr); print(permutation(arr, n)); # This code is contributed by Yash_R // C# program to decide if an array// represents a permutation or notusing System; class GFG{ // Function to check if an // array represents a permutation or not static string permutation(int []arr, int N) { int []hash = new int[N + 1]; // Counting the frequency for (int i = 0; i < N; i++) { hash[arr[i]]++; } // Check if each frequency is 1 only for (int i = 1; i <= N; i++) { if (hash[i] != 1) return "No"; } return "Yes"; } // Driver code public static void Main(string[] args) { int []arr = { 1, 1, 5, 5, 3 }; int n = arr.Length; Console.Write(permutation(arr, n) +"\n"); }} // This code is contributed by Yash_R <script> // JavaScript program to decide if an array// represents a permutation or not // Function to check if an// array represents a permutation or notfunction permutation(arr, N){ var hash = Array(N+1).fill(0); // Counting the frequency for (var i = 0; i < N; i++) { hash[arr[i]]++; } // Check if each frequency is 1 only for (var i = 1; i <= N; i++) { if (hash[i] != 1) return "No"; } return "Yes";} // Driver codevar arr = [1, 1, 5, 5, 3];var n = arr.length;document.write( permutation(arr, n)); </script> No Time Complexity: O(N) Auxiliary Space Complexity: O(N) princi singh Yash_R noob2000 permutation Arrays Hash Mathematical Arrays Hash Mathematical permutation Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stack Data Structure (Introduction and Program) Top 50 Array Coding Problems for Interviews Multidimensional Arrays in Java Introduction to Arrays Linear Search Internal Working of HashMap in Java Hashing | Set 1 (Introduction) Hashing | Set 3 (Open Addressing) Hashing | Set 2 (Separate Chaining) Most frequent element in an array
[ { "code": null, "e": 25236, "s": 25208, "text": "\n21 May, 2021" }, { "code": null, "e": 25365, "s": 25236, "text": "Given an array arr containing N positive integers, the task is to check if the given array arr represents a permutation or not. " }, { "code": null, "e": 25468, "s": 25365, "text": "A sequence of N integers is called a permutation if it contains all integers from 1 to N exactly once." }, { "code": null, "e": 25480, "s": 25468, "text": "Examples: " }, { "code": null, "e": 25810, "s": 25480, "text": "Input: arr[] = {1, 2, 5, 3, 2} Output: No Explanation: The given array contains 2 twice, and 4 is missing for the array to represent a permutation of length 5. Input: arr[] = {1, 2, 5, 3, 4} Output: Yes Explanation: The given array contains all integers from 1 to 5 exactly once. Hence, it represents a permutation of length 5. " }, { "code": null, "e": 25989, "s": 25812, "text": "Naive Approach: in O(N2) Time This approach is mentioned hereAnother Approach: in O(N) Time and O(N) Space This approach is mentioned here.Efficient Approach: Using HashTable " }, { "code": null, "e": 26316, "s": 25989, "text": "Create a HashTable of N size to store the frequency count of each number from 1 to NTraverse through the given array and store the frequency of each number in the HashTable.Then traverse the HashTable and check if all the numbers from 1 to N have a frequency of 1 or not. Print “Yes” if the above condition is True, Else “No”." }, { "code": null, "e": 26401, "s": 26316, "text": "Create a HashTable of N size to store the frequency count of each number from 1 to N" }, { "code": null, "e": 26491, "s": 26401, "text": "Traverse through the given array and store the frequency of each number in the HashTable." }, { "code": null, "e": 26591, "s": 26491, "text": "Then traverse the HashTable and check if all the numbers from 1 to N have a frequency of 1 or not. " }, { "code": null, "e": 26646, "s": 26591, "text": "Print “Yes” if the above condition is True, Else “No”." }, { "code": null, "e": 26699, "s": 26646, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 26703, "s": 26699, "text": "CPP" }, { "code": null, "e": 26708, "s": 26703, "text": "Java" }, { "code": null, "e": 26716, "s": 26708, "text": "Python3" }, { "code": null, "e": 26719, "s": 26716, "text": "C#" }, { "code": null, "e": 26730, "s": 26719, "text": "Javascript" }, { "code": "// C++ program to decide if an array// represents a permutation or not#include <bits/stdc++.h>using namespace std; // Function to check if an// array represents a permutation or notstring permutation(int arr[], int N){ int hash[N + 1] = { 0 }; // Counting the frequency for (int i = 0; i < N; i++) { hash[arr[i]]++; } // Check if each frequency is 1 only for (int i = 1; i <= N; i++) { if (hash[i] != 1) return \"No\"; } return \"Yes\";} // Driver codeint main(){ int arr[] = { 1, 1, 5, 5, 3 }; int n = sizeof(arr) / sizeof(int); cout << permutation(arr, n) << endl; return 0;}", "e": 27370, "s": 26730, "text": null }, { "code": "// Java program to decide if an array// represents a permutation or notclass GFG{ // Function to check if an// array represents a permutation or notstatic String permutation(int arr[], int N){ int []hash = new int[N + 1]; // Counting the frequency for (int i = 0; i < N; i++) { hash[arr[i]]++; } // Check if each frequency is 1 only for (int i = 1; i <= N; i++) { if (hash[i] != 1) return \"No\"; } return \"Yes\";} // Driver codepublic static void main(String[] args){ int arr[] = { 1, 1, 5, 5, 3 }; int n = arr.length; System.out.print(permutation(arr, n) +\"\\n\");}} // This code is contributed by Princi Singh", "e": 28046, "s": 27370, "text": null }, { "code": "# Python3 program to decide if an array# represents a permutation or not # Function to check if an# array represents a permutation or notdef permutation(arr, N) : hash = [0]*(N + 1); # Counting the frequency for i in range(N) : hash[arr[i]] += 1; # Check if each frequency is 1 only for i in range(1, N + 1) : if (hash[i] != 1) : return \"No\"; return \"Yes\"; # Driver codeif __name__ == \"__main__\" : arr = [ 1, 1, 5, 5, 3 ]; n = len(arr); print(permutation(arr, n)); # This code is contributed by Yash_R", "e": 28610, "s": 28046, "text": null }, { "code": "// C# program to decide if an array// represents a permutation or notusing System; class GFG{ // Function to check if an // array represents a permutation or not static string permutation(int []arr, int N) { int []hash = new int[N + 1]; // Counting the frequency for (int i = 0; i < N; i++) { hash[arr[i]]++; } // Check if each frequency is 1 only for (int i = 1; i <= N; i++) { if (hash[i] != 1) return \"No\"; } return \"Yes\"; } // Driver code public static void Main(string[] args) { int []arr = { 1, 1, 5, 5, 3 }; int n = arr.Length; Console.Write(permutation(arr, n) +\"\\n\"); }} // This code is contributed by Yash_R", "e": 29401, "s": 28610, "text": null }, { "code": "<script> // JavaScript program to decide if an array// represents a permutation or not // Function to check if an// array represents a permutation or notfunction permutation(arr, N){ var hash = Array(N+1).fill(0); // Counting the frequency for (var i = 0; i < N; i++) { hash[arr[i]]++; } // Check if each frequency is 1 only for (var i = 1; i <= N; i++) { if (hash[i] != 1) return \"No\"; } return \"Yes\";} // Driver codevar arr = [1, 1, 5, 5, 3];var n = arr.length;document.write( permutation(arr, n)); </script>", "e": 29965, "s": 29401, "text": null }, { "code": null, "e": 29968, "s": 29965, "text": "No" }, { "code": null, "e": 30026, "s": 29970, "text": "Time Complexity: O(N) Auxiliary Space Complexity: O(N) " }, { "code": null, "e": 30039, "s": 30026, "text": "princi singh" }, { "code": null, "e": 30046, "s": 30039, "text": "Yash_R" }, { "code": null, "e": 30055, "s": 30046, "text": "noob2000" }, { "code": null, "e": 30067, "s": 30055, "text": "permutation" }, { "code": null, "e": 30074, "s": 30067, "text": "Arrays" }, { "code": null, "e": 30079, "s": 30074, "text": "Hash" }, { "code": null, "e": 30092, "s": 30079, "text": "Mathematical" }, { "code": null, "e": 30099, "s": 30092, "text": "Arrays" }, { "code": null, "e": 30104, "s": 30099, "text": "Hash" }, { "code": null, "e": 30117, "s": 30104, "text": "Mathematical" }, { "code": null, "e": 30129, "s": 30117, "text": "permutation" }, { "code": null, "e": 30227, "s": 30129, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30275, "s": 30227, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 30319, "s": 30275, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 30351, "s": 30319, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 30374, "s": 30351, "text": "Introduction to Arrays" }, { "code": null, "e": 30388, "s": 30374, "text": "Linear Search" }, { "code": null, "e": 30424, "s": 30388, "text": "Internal Working of HashMap in Java" }, { "code": null, "e": 30455, "s": 30424, "text": "Hashing | Set 1 (Introduction)" }, { "code": null, "e": 30489, "s": 30455, "text": "Hashing | Set 3 (Open Addressing)" }, { "code": null, "e": 30525, "s": 30489, "text": "Hashing | Set 2 (Separate Chaining)" } ]
Different ways to use Const with Reference to a Pointer in C++ - GeeksforGeeks
04 Apr, 2020 Before moving forward with using const with Reference to a Pointers, let us first see what they are one by one: Pointers are used to store the address of variables or a memory location. A variable can be declared as a pointer by putting ‘*’ in the declaration.datatype *var_name; Example:// C++ program to// demonstrate a Pointer #include <iostream>using namespace std; int main(){ // Variable int i = 10; // Pointer to i int* ptr_i = &i; cout << *ptr_i; return 0;}Output:10 datatype *var_name; Example: // C++ program to// demonstrate a Pointer #include <iostream>using namespace std; int main(){ // Variable int i = 10; // Pointer to i int* ptr_i = &i; cout << *ptr_i; return 0;} 10 Reference: When a variable is declared as a reference, it becomes an alternative name for an existing variable. A variable can be declared as a reference by putting ‘&’ in the declaration.datatype &var_name; Example:// C++ program to// demonstrate a Reference #include <iostream>using namespace std; int main(){ // Variable int i = 10; // Reference to i. int& ref = i; // Value of i is now // changed to 20 ref = 20; cout << i; return 0;}Output:20 datatype &var_name; Example: // C++ program to// demonstrate a Reference #include <iostream>using namespace std; int main(){ // Variable int i = 10; // Reference to i. int& ref = i; // Value of i is now // changed to 20 ref = 20; cout << i; return 0;} 20 References to pointers is a modifiable value that’s used same as a normal pointer.datatype *&var_name; Example 1:// C++ program to demonstrate// References to pointers #include <iostream>using namespace std; int main(){ // Variable int i = 10; // Pointer to i int* ptr_i = &i; // Reference to a Pointer ptr_i int*& ptr_ref = ptr_i; cout << *ptr_ref; return 0;}Output:10 Here ptr_ref is a reference to the pointer ptr_i which points to variable ‘i’. Thus printing value at ptr_ref gives the value of ‘i’, which is 10.Example 2: Now let us try to change the address represented by a Reference to a Pointer// C++ program to demonstrate// References to pointers #include <iostream>using namespace std; int main(){ // Variable int i = 10; int j = 5; // Pointer to i int* ptr = &i; // Reference to a Pointer ptr int*& ptr_ref = ptr; // Trying to change the reference // to Pointer ptr_ref to address of j ptr_ref = &j; cout << *ptr; return 0;}Output:5 Here it prints 5, because the value of j is 5 and we changed ptr_ref to point to j. Now as ptr_ref is a reference to pointer ptr, ptr now points to j. Thus we get the output we expected to see. datatype *&var_name; Example 1: // C++ program to demonstrate// References to pointers #include <iostream>using namespace std; int main(){ // Variable int i = 10; // Pointer to i int* ptr_i = &i; // Reference to a Pointer ptr_i int*& ptr_ref = ptr_i; cout << *ptr_ref; return 0;} 10 Here ptr_ref is a reference to the pointer ptr_i which points to variable ‘i’. Thus printing value at ptr_ref gives the value of ‘i’, which is 10. Example 2: Now let us try to change the address represented by a Reference to a Pointer // C++ program to demonstrate// References to pointers #include <iostream>using namespace std; int main(){ // Variable int i = 10; int j = 5; // Pointer to i int* ptr = &i; // Reference to a Pointer ptr int*& ptr_ref = ptr; // Trying to change the reference // to Pointer ptr_ref to address of j ptr_ref = &j; cout << *ptr; return 0;} 5 Here it prints 5, because the value of j is 5 and we changed ptr_ref to point to j. Now as ptr_ref is a reference to pointer ptr, ptr now points to j. Thus we get the output we expected to see. Const Reference to a pointer is a non-modifiable value that’s used same as a const pointer.datatype* const &var_name; Example 1:// C++ program to demonstrate// References to pointers #include <iostream>using namespace std; int main(){ // Variable int i = 10; int j = 5; // Pointer to i int* ptr = &i; // Const Reference to a Pointer int* const& ptr_ref = ptr; // Trying to change the const reference // to Pointer ptr_ref to address of j ptr_ref = &j; cout << *ptr; return 0;}Compilation Error:In function 'int main()': prog.cpp:23:13: error: assignment of read-only reference 'ptr_ref' ptr_ref = &j; ^ Here we get a compile-time error as it is a const reference to a pointer thus we are not allowed to reassign it.Example 2:// C++ program to demonstrate// References to pointers #include <iostream>using namespace std; int main(){ // Variable int i = 10; int j = 5; // Pointer to i int* ptr = &i; // Const Reference to a Pointer int* const& ptr_ref = ptr; // Trying to change the reference // to Pointer ptr_ref *ptr_ref = 100; cout << *ptr; return 0;}Output:100 It prints 100 as it is not a reference to a pointer of a const.Why Example 2 didn’t throw a Compile-time error when Example 1 did?In Example 1, the ptr_ref is a const reference to a pointer to int, and we are trying to change the value of ptr_ref. So the compiler throws a Compile time error, as we are trying to modify a constant value.In Example 2, the ptr_ref is a const reference to a pointer to int, and we are trying to change the value of *ptr_ref, which means we are changing the value of int to which the pointer is pointing, and not the const reference of a pointer. So the compiler doesn’t throw any error and the pointer now points to a value 100. Therefore the int is not a constant here, but the pointer is. As a result, the value of int changed to 100. datatype* const &var_name; Example 1: // C++ program to demonstrate// References to pointers #include <iostream>using namespace std; int main(){ // Variable int i = 10; int j = 5; // Pointer to i int* ptr = &i; // Const Reference to a Pointer int* const& ptr_ref = ptr; // Trying to change the const reference // to Pointer ptr_ref to address of j ptr_ref = &j; cout << *ptr; return 0;} Compilation Error: In function 'int main()': prog.cpp:23:13: error: assignment of read-only reference 'ptr_ref' ptr_ref = &j; ^ Here we get a compile-time error as it is a const reference to a pointer thus we are not allowed to reassign it. Example 2: // C++ program to demonstrate// References to pointers #include <iostream>using namespace std; int main(){ // Variable int i = 10; int j = 5; // Pointer to i int* ptr = &i; // Const Reference to a Pointer int* const& ptr_ref = ptr; // Trying to change the reference // to Pointer ptr_ref *ptr_ref = 100; cout << *ptr; return 0;} 100 It prints 100 as it is not a reference to a pointer of a const. Why Example 2 didn’t throw a Compile-time error when Example 1 did? In Example 1, the ptr_ref is a const reference to a pointer to int, and we are trying to change the value of ptr_ref. So the compiler throws a Compile time error, as we are trying to modify a constant value. In Example 2, the ptr_ref is a const reference to a pointer to int, and we are trying to change the value of *ptr_ref, which means we are changing the value of int to which the pointer is pointing, and not the const reference of a pointer. So the compiler doesn’t throw any error and the pointer now points to a value 100. Therefore the int is not a constant here, but the pointer is. As a result, the value of int changed to 100. Reference to a Const Pointer is a reference to a constant pointer.datatype const *&var_name; Example:// C++ program to demonstrate// References to pointers #include <iostream>using namespace std; int main(){ // Variable int i = 10; int j = 5; // Const Pointer to i int const* ptr = &i; // Reference to a Const Pointer int const*& ptr_ref = ptr; // Trying to change the value of the pointer // ptr with help of its reference ptr_ref *ptr_ref = 124; cout << *ptr; return 0;}Compilation Error:In function 'int main()': prog.cpp:23:14: error: assignment of read-only location '* ptr_ref' *ptr_ref = 124; ^ Here again we get compile time error. This is because here the compiler says to declare ptr_ref as reference to pointer to const int. So we are not allowed to change the value of i. datatype const *&var_name; Example: // C++ program to demonstrate// References to pointers #include <iostream>using namespace std; int main(){ // Variable int i = 10; int j = 5; // Const Pointer to i int const* ptr = &i; // Reference to a Const Pointer int const*& ptr_ref = ptr; // Trying to change the value of the pointer // ptr with help of its reference ptr_ref *ptr_ref = 124; cout << *ptr; return 0;} Compilation Error: In function 'int main()': prog.cpp:23:14: error: assignment of read-only location '* ptr_ref' *ptr_ref = 124; ^ Here again we get compile time error. This is because here the compiler says to declare ptr_ref as reference to pointer to const int. So we are not allowed to change the value of i. Advanced Pointer C++-const keyword cpp-pointer cpp-references C++ C++ Programs CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Map in C++ Standard Template Library (STL) Constructors in C++ Bitwise Operators in C/C++ Socket Programming in C/C++ Operator Overloading in C++ Header files in C/C++ and its uses C++ Program for QuickSort How to return multiple values from a function in C or C++? Program to print ASCII Value of a character C++ program for hashing with chaining
[ { "code": null, "e": 23953, "s": 23925, "text": "\n04 Apr, 2020" }, { "code": null, "e": 24065, "s": 23953, "text": "Before moving forward with using const with Reference to a Pointers, let us first see what they are one by one:" }, { "code": null, "e": 24458, "s": 24065, "text": "Pointers are used to store the address of variables or a memory location. A variable can be declared as a pointer by putting ‘*’ in the declaration.datatype *var_name; \nExample:// C++ program to// demonstrate a Pointer #include <iostream>using namespace std; int main(){ // Variable int i = 10; // Pointer to i int* ptr_i = &i; cout << *ptr_i; return 0;}Output:10\n" }, { "code": null, "e": 24480, "s": 24458, "text": "datatype *var_name; \n" }, { "code": null, "e": 24489, "s": 24480, "text": "Example:" }, { "code": "// C++ program to// demonstrate a Pointer #include <iostream>using namespace std; int main(){ // Variable int i = 10; // Pointer to i int* ptr_i = &i; cout << *ptr_i; return 0;}", "e": 24695, "s": 24489, "text": null }, { "code": null, "e": 24699, "s": 24695, "text": "10\n" }, { "code": null, "e": 25188, "s": 24699, "text": "Reference: When a variable is declared as a reference, it becomes an alternative name for an existing variable. A variable can be declared as a reference by putting ‘&’ in the declaration.datatype &var_name; \nExample:// C++ program to// demonstrate a Reference #include <iostream>using namespace std; int main(){ // Variable int i = 10; // Reference to i. int& ref = i; // Value of i is now // changed to 20 ref = 20; cout << i; return 0;}Output:20\n" }, { "code": null, "e": 25210, "s": 25188, "text": "datatype &var_name; \n" }, { "code": null, "e": 25219, "s": 25210, "text": "Example:" }, { "code": "// C++ program to// demonstrate a Reference #include <iostream>using namespace std; int main(){ // Variable int i = 10; // Reference to i. int& ref = i; // Value of i is now // changed to 20 ref = 20; cout << i; return 0;}", "e": 25481, "s": 25219, "text": null }, { "code": null, "e": 25485, "s": 25481, "text": "20\n" }, { "code": null, "e": 26712, "s": 25485, "text": "References to pointers is a modifiable value that’s used same as a normal pointer.datatype *&var_name; \nExample 1:// C++ program to demonstrate// References to pointers #include <iostream>using namespace std; int main(){ // Variable int i = 10; // Pointer to i int* ptr_i = &i; // Reference to a Pointer ptr_i int*& ptr_ref = ptr_i; cout << *ptr_ref; return 0;}Output:10\nHere ptr_ref is a reference to the pointer ptr_i which points to variable ‘i’. Thus printing value at ptr_ref gives the value of ‘i’, which is 10.Example 2: Now let us try to change the address represented by a Reference to a Pointer// C++ program to demonstrate// References to pointers #include <iostream>using namespace std; int main(){ // Variable int i = 10; int j = 5; // Pointer to i int* ptr = &i; // Reference to a Pointer ptr int*& ptr_ref = ptr; // Trying to change the reference // to Pointer ptr_ref to address of j ptr_ref = &j; cout << *ptr; return 0;}Output:5\nHere it prints 5, because the value of j is 5 and we changed ptr_ref to point to j. Now as ptr_ref is a reference to pointer ptr, ptr now points to j. Thus we get the output we expected to see." }, { "code": null, "e": 26735, "s": 26712, "text": "datatype *&var_name; \n" }, { "code": null, "e": 26746, "s": 26735, "text": "Example 1:" }, { "code": "// C++ program to demonstrate// References to pointers #include <iostream>using namespace std; int main(){ // Variable int i = 10; // Pointer to i int* ptr_i = &i; // Reference to a Pointer ptr_i int*& ptr_ref = ptr_i; cout << *ptr_ref; return 0;}", "e": 27030, "s": 26746, "text": null }, { "code": null, "e": 27034, "s": 27030, "text": "10\n" }, { "code": null, "e": 27181, "s": 27034, "text": "Here ptr_ref is a reference to the pointer ptr_i which points to variable ‘i’. Thus printing value at ptr_ref gives the value of ‘i’, which is 10." }, { "code": null, "e": 27269, "s": 27181, "text": "Example 2: Now let us try to change the address represented by a Reference to a Pointer" }, { "code": "// C++ program to demonstrate// References to pointers #include <iostream>using namespace std; int main(){ // Variable int i = 10; int j = 5; // Pointer to i int* ptr = &i; // Reference to a Pointer ptr int*& ptr_ref = ptr; // Trying to change the reference // to Pointer ptr_ref to address of j ptr_ref = &j; cout << *ptr; return 0;}", "e": 27654, "s": 27269, "text": null }, { "code": null, "e": 27657, "s": 27654, "text": "5\n" }, { "code": null, "e": 27851, "s": 27657, "text": "Here it prints 5, because the value of j is 5 and we changed ptr_ref to point to j. Now as ptr_ref is a reference to pointer ptr, ptr now points to j. Thus we get the output we expected to see." }, { "code": null, "e": 29802, "s": 27851, "text": "Const Reference to a pointer is a non-modifiable value that’s used same as a const pointer.datatype* const &var_name; \nExample 1:// C++ program to demonstrate// References to pointers #include <iostream>using namespace std; int main(){ // Variable int i = 10; int j = 5; // Pointer to i int* ptr = &i; // Const Reference to a Pointer int* const& ptr_ref = ptr; // Trying to change the const reference // to Pointer ptr_ref to address of j ptr_ref = &j; cout << *ptr; return 0;}Compilation Error:In function 'int main()':\nprog.cpp:23:13: error: assignment of read-only reference 'ptr_ref'\n ptr_ref = &j;\n ^\nHere we get a compile-time error as it is a const reference to a pointer thus we are not allowed to reassign it.Example 2:// C++ program to demonstrate// References to pointers #include <iostream>using namespace std; int main(){ // Variable int i = 10; int j = 5; // Pointer to i int* ptr = &i; // Const Reference to a Pointer int* const& ptr_ref = ptr; // Trying to change the reference // to Pointer ptr_ref *ptr_ref = 100; cout << *ptr; return 0;}Output:100\nIt prints 100 as it is not a reference to a pointer of a const.Why Example 2 didn’t throw a Compile-time error when Example 1 did?In Example 1, the ptr_ref is a const reference to a pointer to int, and we are trying to change the value of ptr_ref. So the compiler throws a Compile time error, as we are trying to modify a constant value.In Example 2, the ptr_ref is a const reference to a pointer to int, and we are trying to change the value of *ptr_ref, which means we are changing the value of int to which the pointer is pointing, and not the const reference of a pointer. So the compiler doesn’t throw any error and the pointer now points to a value 100. Therefore the int is not a constant here, but the pointer is. As a result, the value of int changed to 100." }, { "code": null, "e": 29831, "s": 29802, "text": "datatype* const &var_name; \n" }, { "code": null, "e": 29842, "s": 29831, "text": "Example 1:" }, { "code": "// C++ program to demonstrate// References to pointers #include <iostream>using namespace std; int main(){ // Variable int i = 10; int j = 5; // Pointer to i int* ptr = &i; // Const Reference to a Pointer int* const& ptr_ref = ptr; // Trying to change the const reference // to Pointer ptr_ref to address of j ptr_ref = &j; cout << *ptr; return 0;}", "e": 30241, "s": 29842, "text": null }, { "code": null, "e": 30260, "s": 30241, "text": "Compilation Error:" }, { "code": null, "e": 30388, "s": 30260, "text": "In function 'int main()':\nprog.cpp:23:13: error: assignment of read-only reference 'ptr_ref'\n ptr_ref = &j;\n ^\n" }, { "code": null, "e": 30501, "s": 30388, "text": "Here we get a compile-time error as it is a const reference to a pointer thus we are not allowed to reassign it." }, { "code": null, "e": 30512, "s": 30501, "text": "Example 2:" }, { "code": "// C++ program to demonstrate// References to pointers #include <iostream>using namespace std; int main(){ // Variable int i = 10; int j = 5; // Pointer to i int* ptr = &i; // Const Reference to a Pointer int* const& ptr_ref = ptr; // Trying to change the reference // to Pointer ptr_ref *ptr_ref = 100; cout << *ptr; return 0;}", "e": 30891, "s": 30512, "text": null }, { "code": null, "e": 30896, "s": 30891, "text": "100\n" }, { "code": null, "e": 30960, "s": 30896, "text": "It prints 100 as it is not a reference to a pointer of a const." }, { "code": null, "e": 31028, "s": 30960, "text": "Why Example 2 didn’t throw a Compile-time error when Example 1 did?" }, { "code": null, "e": 31236, "s": 31028, "text": "In Example 1, the ptr_ref is a const reference to a pointer to int, and we are trying to change the value of ptr_ref. So the compiler throws a Compile time error, as we are trying to modify a constant value." }, { "code": null, "e": 31667, "s": 31236, "text": "In Example 2, the ptr_ref is a const reference to a pointer to int, and we are trying to change the value of *ptr_ref, which means we are changing the value of int to which the pointer is pointing, and not the const reference of a pointer. So the compiler doesn’t throw any error and the pointer now points to a value 100. Therefore the int is not a constant here, but the pointer is. As a result, the value of int changed to 100." }, { "code": null, "e": 32519, "s": 31667, "text": "Reference to a Const Pointer is a reference to a constant pointer.datatype const *&var_name; \nExample:// C++ program to demonstrate// References to pointers #include <iostream>using namespace std; int main(){ // Variable int i = 10; int j = 5; // Const Pointer to i int const* ptr = &i; // Reference to a Const Pointer int const*& ptr_ref = ptr; // Trying to change the value of the pointer // ptr with help of its reference ptr_ref *ptr_ref = 124; cout << *ptr; return 0;}Compilation Error:In function 'int main()':\nprog.cpp:23:14: error: assignment of read-only location '* ptr_ref'\n *ptr_ref = 124;\n ^\nHere again we get compile time error. This is because here the compiler says to declare ptr_ref as reference to pointer to const int. So we are not allowed to change the value of i." }, { "code": null, "e": 32548, "s": 32519, "text": "datatype const *&var_name; \n" }, { "code": null, "e": 32557, "s": 32548, "text": "Example:" }, { "code": "// C++ program to demonstrate// References to pointers #include <iostream>using namespace std; int main(){ // Variable int i = 10; int j = 5; // Const Pointer to i int const* ptr = &i; // Reference to a Const Pointer int const*& ptr_ref = ptr; // Trying to change the value of the pointer // ptr with help of its reference ptr_ref *ptr_ref = 124; cout << *ptr; return 0;}", "e": 32977, "s": 32557, "text": null }, { "code": null, "e": 32996, "s": 32977, "text": "Compilation Error:" }, { "code": null, "e": 33128, "s": 32996, "text": "In function 'int main()':\nprog.cpp:23:14: error: assignment of read-only location '* ptr_ref'\n *ptr_ref = 124;\n ^\n" }, { "code": null, "e": 33310, "s": 33128, "text": "Here again we get compile time error. This is because here the compiler says to declare ptr_ref as reference to pointer to const int. So we are not allowed to change the value of i." }, { "code": null, "e": 33327, "s": 33310, "text": "Advanced Pointer" }, { "code": null, "e": 33345, "s": 33327, "text": "C++-const keyword" }, { "code": null, "e": 33357, "s": 33345, "text": "cpp-pointer" }, { "code": null, "e": 33372, "s": 33357, "text": "cpp-references" }, { "code": null, "e": 33376, "s": 33372, "text": "C++" }, { "code": null, "e": 33389, "s": 33376, "text": "C++ Programs" }, { "code": null, "e": 33393, "s": 33389, "text": "CPP" }, { "code": null, "e": 33491, "s": 33393, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33500, "s": 33491, "text": "Comments" }, { "code": null, "e": 33513, "s": 33500, "text": "Old Comments" }, { "code": null, "e": 33556, "s": 33513, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 33576, "s": 33556, "text": "Constructors in C++" }, { "code": null, "e": 33603, "s": 33576, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 33631, "s": 33603, "text": "Socket Programming in C/C++" }, { "code": null, "e": 33659, "s": 33631, "text": "Operator Overloading in C++" }, { "code": null, "e": 33694, "s": 33659, "text": "Header files in C/C++ and its uses" }, { "code": null, "e": 33720, "s": 33694, "text": "C++ Program for QuickSort" }, { "code": null, "e": 33779, "s": 33720, "text": "How to return multiple values from a function in C or C++?" }, { "code": null, "e": 33823, "s": 33779, "text": "Program to print ASCII Value of a character" } ]
Java 1-d and 2-d Array | Practice | GeeksforGeeks
Given a integer n. We have n*n values of a 2-d array, and n values of 1-d array. Task is to find the sum of the left diagonal values of the 2-d array and the max element of the 1-d array and print them with space in between. Example 1: ​Input : arr[][] = {{1,2,3}, {4,5,6}, {7, 8,9}} and N = 3 brr[] = {3, 6, 9} Output : 15 9 Explanation: 1 2 3 4 5 6 7 8 9 So, this sum of left diagonal (1+ 5 + 9) = 15 The maximum element in an array brr is 9 So, will return {15, 9} as an answer. ​Example 2: Input : arr[][] = {{1,2}, {1, 2}} and N = 2 brr[] = {10, 1} Output : 3 10 Your Task: This is a function problem. The input is already taken care of by the driver code. You only need to complete the function array() that takes a two-dimension array (a), another one dimension array (b), sizeOfArray (n), and return the ArrayList which is having the sum of the diagonal elements of the array a and the maximum number of the array b. The driver code takes care of the printing. Expected Time Complexity: O(N2). Expected Auxiliary Space: O(1). Constraints 1 ≤ n ≤ 100 1 ≤ a[i][j], b[i] ≤ 103 +1 prashantfp32 days ago class Complete{ public static ArrayList<Integer> array(int a[][], int b[], int n) { // Complete the function int sum=0; for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { if(i==j) { sum=sum+a[i][j]; } } } // Finding Max element from 1D array int max=b[0]; for(int i=1;i<b.length;i++) { if(b[i]>max) { max=b[i]; } } // created ArrayList and stored sum of diagonal elements and max of 1D array ArrayList<Integer> li=new ArrayList<Integer>(); li.add(sum); li.add(max); return li; }} 0 singhmanjeetsk753 days ago In java solution class Complete{ public static ArrayList<Integer> array(int a[][], int b[], int n) { ArrayList<Integer> c = new ArrayList<Integer>(); int max=Arrays.stream(b).max().getAsInt(); int sum=0; for(int i=0;i<n;i++){ sum=sum+a[i][i]; } c.add(sum); c.add(max); return c; }} 0 dostdedhoka2 weeks ago int sum=0; for(int i=0;i<n;i++){ sum+=a[i][i]; } int max=-1; for(int i=0;i<n;i++){ max=Math.max(max,b[i]); } ArrayList<Integer> ob=new ArrayList<>(); ob.add(sum); ob.add(max); return ob; 0 priobratamalik2 months ago /* O(n) Java Code */ ArrayList<Integer> ans = new ArrayList<>(); int first=0, second=0; for(int i=0; i<n; i++) { first+=a[i][i]; if(second<b[i]) second=b[i]; } ans.add(first); ans.add(second); return ans; 0 skpuntri2 months ago li.add(sum); li.add(max); return li; +1 jagtapshubham1913 months ago class Complete{ public static ArrayList<Integer> array(int a[][], int b[], int n) { // Complete the function // Addition of left diagonal element of 2D array int sum=0; for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { if(i==j) { sum=sum+a[i][j]; } } } // Finding Max element from 1D array int max=b[0]; for(int i=1;i<b.length;i++) { if(b[i]>max) { max=b[i]; } } // created ArrayList and stored sum of diagonal elements and max of 1D array ArrayList<Integer> li=new ArrayList<Integer>(); li.add(sum); li.add(max); return li; }} 0 arvind16yadav3 months ago /*JAVA SOLUTION*/ public static ArrayList<Integer> array(int a[][], int b[], int n) { // Complete the function int sum_of_left_diagonal = 0; int max_number = b[0]; ArrayList<Integer> ans = new ArrayList<Integer>(); for(int i=0; i<n; i++){ sum_of_left_diagonal += a[i][i]; } ans.add(sum_of_left_diagonal); for(int i=1; i<n; i++){ if(max_number < b[i]){ max_number = b[i]; } } ans.add(max_number); return ans; } 0 prateekkasaudhan1233 months ago // JAVA SOLUTION ArrayList<Integer> ans = new ArrayList<>(); int ansA = 0; int ansB = 0; for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ if(i==j){ ansA += a[i][j]; } } if(b[i]>ansB){ ansB = b[i]; } } ans.add(ansA); ans.add(ansB); return ans; 0 natraj20023 months ago //O(n) Simple ArrayList<Integer> lst=new ArrayList<>(); int dsum=0; int max=Integer.MIN_VALUE; for(int i=0;i<n;i++){ dsum+=a[i][i]; } for(int i=0;i<n;i++){ max=Math.max(b[i],max); } lst.add(dsum); lst.add(max); return lst; 0 zentalc7413 months ago class Complete{ public static ArrayList<Integer> array(int a[][], int b[], int n) { int sum=0; ArrayList<Integer> lis=new ArrayList<Integer>(); for(int i=0;i<a.length;i++){ for(int j=0;j<a[i].length;j++){ if(i==j){ sum+=a[i][j]; } } } int max=b[0]; for(int g=0;g<b.length;g++){ if(b[g]>max){ max=b[g]; } } lis.add(sum); lis.add(max); return lis; }} We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab. Make sure you are not using ad-blockers. Disable browser extensions. We recommend using latest version of your browser for best experience. Avoid using static/global variables in coding problems as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases in coding problems does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
[ { "code": null, "e": 452, "s": 226, "text": "Given a integer n. We have n*n values of a 2-d array, and n values of 1-d array. Task is to find the sum of the left diagonal values of the 2-d array and the max element of the 1-d array and print them with space in between." }, { "code": null, "e": 463, "s": 452, "text": "Example 1:" }, { "code": null, "e": 722, "s": 463, "text": "​Input : arr[][] = {{1,2,3}, {4,5,6}, {7, 8,9}} \n and N = 3\nbrr[] = {3, 6, 9}\nOutput : 15 9\nExplanation:\n1 2 3\n4 5 6\n7 8 9\nSo, this sum of left diagonal (1+ 5 + 9) = 15\nThe maximum element in an array brr is 9\nSo, will return {15, 9} as an answer.\n" }, { "code": null, "e": 738, "s": 722, "text": "\n​Example 2:" }, { "code": null, "e": 815, "s": 738, "text": "Input : arr[][] = {{1,2}, {1, 2}} and N = 2\nbrr[] = {10, 1} \nOutput : 3 10 " }, { "code": null, "e": 1218, "s": 817, "text": "Your Task:\nThis is a function problem. The input is already taken care of by the driver code. You only need to complete the function array() that takes a two-dimension array (a), another one dimension array (b), sizeOfArray (n), and return the ArrayList which is having the sum of the diagonal elements of the array a and the maximum number of the array b. The driver code takes care of the printing." }, { "code": null, "e": 1283, "s": 1218, "text": "Expected Time Complexity: O(N2).\nExpected Auxiliary Space: O(1)." }, { "code": null, "e": 1334, "s": 1286, "text": "Constraints\n1 ≤ n ≤ 100\n1 ≤ a[i][j], b[i] ≤ 103" }, { "code": null, "e": 1337, "s": 1334, "text": "+1" }, { "code": null, "e": 1359, "s": 1337, "text": "prashantfp32 days ago" }, { "code": null, "e": 1670, "s": 1359, "text": "class Complete{ public static ArrayList<Integer> array(int a[][], int b[], int n) { // Complete the function int sum=0; for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { if(i==j) { sum=sum+a[i][j]; } } }" }, { "code": null, "e": 1846, "s": 1670, "text": " // Finding Max element from 1D array int max=b[0]; for(int i=1;i<b.length;i++) { if(b[i]>max) { max=b[i]; } }" }, { "code": null, "e": 2039, "s": 1846, "text": " // created ArrayList and stored sum of diagonal elements and max of 1D array ArrayList<Integer> li=new ArrayList<Integer>(); li.add(sum); li.add(max); return li; }}" }, { "code": null, "e": 2041, "s": 2039, "text": "0" }, { "code": null, "e": 2068, "s": 2041, "text": "singhmanjeetsk753 days ago" }, { "code": null, "e": 2085, "s": 2068, "text": "In java solution" }, { "code": null, "e": 2421, "s": 2085, "text": "class Complete{ public static ArrayList<Integer> array(int a[][], int b[], int n) { ArrayList<Integer> c = new ArrayList<Integer>(); int max=Arrays.stream(b).max().getAsInt(); int sum=0; for(int i=0;i<n;i++){ sum=sum+a[i][i]; } c.add(sum); c.add(max); return c; }} " }, { "code": null, "e": 2423, "s": 2421, "text": "0" }, { "code": null, "e": 2446, "s": 2423, "text": "dostdedhoka2 weeks ago" }, { "code": null, "e": 2707, "s": 2446, "text": "int sum=0; for(int i=0;i<n;i++){ sum+=a[i][i]; } int max=-1; for(int i=0;i<n;i++){ max=Math.max(max,b[i]); } ArrayList<Integer> ob=new ArrayList<>(); ob.add(sum); ob.add(max); return ob;" }, { "code": null, "e": 2711, "s": 2709, "text": "0" }, { "code": null, "e": 2738, "s": 2711, "text": "priobratamalik2 months ago" }, { "code": null, "e": 2759, "s": 2738, "text": "/* O(n) Java Code */" }, { "code": null, "e": 3034, "s": 2759, "text": "ArrayList<Integer> ans = new ArrayList<>(); int first=0, second=0; for(int i=0; i<n; i++) { first+=a[i][i]; if(second<b[i]) second=b[i]; } ans.add(first); ans.add(second); return ans;" }, { "code": null, "e": 3036, "s": 3034, "text": "0" }, { "code": null, "e": 3057, "s": 3036, "text": "skpuntri2 months ago" }, { "code": null, "e": 3106, "s": 3057, "text": "li.add(sum); li.add(max); return li;" }, { "code": null, "e": 3109, "s": 3106, "text": "+1" }, { "code": null, "e": 3138, "s": 3109, "text": "jagtapshubham1913 months ago" }, { "code": null, "e": 3524, "s": 3138, "text": "class Complete{ public static ArrayList<Integer> array(int a[][], int b[], int n) { // Complete the function // Addition of left diagonal element of 2D array int sum=0; for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { if(i==j) { sum=sum+a[i][j]; } } }" }, { "code": null, "e": 3709, "s": 3524, "text": " // Finding Max element from 1D array int max=b[0]; for(int i=1;i<b.length;i++) { if(b[i]>max) { max=b[i]; } }" }, { "code": null, "e": 3908, "s": 3709, "text": " // created ArrayList and stored sum of diagonal elements and max of 1D array ArrayList<Integer> li=new ArrayList<Integer>(); li.add(sum); li.add(max); return li; }}" }, { "code": null, "e": 3910, "s": 3908, "text": "0" }, { "code": null, "e": 3936, "s": 3910, "text": "arvind16yadav3 months ago" }, { "code": null, "e": 3954, "s": 3936, "text": "/*JAVA SOLUTION*/" }, { "code": null, "e": 4480, "s": 3954, "text": "public static ArrayList<Integer> array(int a[][], int b[], int n) { // Complete the function int sum_of_left_diagonal = 0; int max_number = b[0]; ArrayList<Integer> ans = new ArrayList<Integer>(); for(int i=0; i<n; i++){ sum_of_left_diagonal += a[i][i]; } ans.add(sum_of_left_diagonal); for(int i=1; i<n; i++){ if(max_number < b[i]){ max_number = b[i]; } } ans.add(max_number);" }, { "code": null, "e": 4511, "s": 4480, "text": " return ans; }" }, { "code": null, "e": 4513, "s": 4511, "text": "0" }, { "code": null, "e": 4545, "s": 4513, "text": "prateekkasaudhan1233 months ago" }, { "code": null, "e": 4562, "s": 4545, "text": "// JAVA SOLUTION" }, { "code": null, "e": 4932, "s": 4562, "text": "ArrayList<Integer> ans = new ArrayList<>(); int ansA = 0; int ansB = 0; for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ if(i==j){ ansA += a[i][j]; } } if(b[i]>ansB){ ansB = b[i]; } } ans.add(ansA); ans.add(ansB); return ans;" }, { "code": null, "e": 4934, "s": 4932, "text": "0" }, { "code": null, "e": 4957, "s": 4934, "text": "natraj20023 months ago" }, { "code": null, "e": 4971, "s": 4957, "text": "//O(n) Simple" }, { "code": null, "e": 5255, "s": 4971, "text": " ArrayList<Integer> lst=new ArrayList<>(); int dsum=0; int max=Integer.MIN_VALUE; for(int i=0;i<n;i++){ dsum+=a[i][i]; } for(int i=0;i<n;i++){ max=Math.max(b[i],max); } lst.add(dsum); lst.add(max); return lst;" }, { "code": null, "e": 5257, "s": 5255, "text": "0" }, { "code": null, "e": 5280, "s": 5257, "text": "zentalc7413 months ago" }, { "code": null, "e": 5786, "s": 5280, "text": "class Complete{ public static ArrayList<Integer> array(int a[][], int b[], int n) { int sum=0; ArrayList<Integer> lis=new ArrayList<Integer>(); for(int i=0;i<a.length;i++){ for(int j=0;j<a[i].length;j++){ if(i==j){ sum+=a[i][j]; } } } int max=b[0]; for(int g=0;g<b.length;g++){ if(b[g]>max){ max=b[g]; } } lis.add(sum); lis.add(max); return lis; }} " }, { "code": null, "e": 5932, "s": 5786, "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": 5968, "s": 5932, "text": " Login to access your submissions. " }, { "code": null, "e": 5978, "s": 5968, "text": "\nProblem\n" }, { "code": null, "e": 5988, "s": 5978, "text": "\nContest\n" }, { "code": null, "e": 6051, "s": 5988, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 6236, "s": 6051, "text": "Avoid using static/global variables in your code as your code is tested \n against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 6520, "s": 6236, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code.\n On submission, your code is tested against multiple test cases consisting of all\n possible corner cases and stress constraints." }, { "code": null, "e": 6666, "s": 6520, "text": "You can access the hints to get an idea about what is expected of you as well as\n the final solution code." }, { "code": null, "e": 6743, "s": 6666, "text": "You can view the solutions submitted by other users from the submission tab." }, { "code": null, "e": 6784, "s": 6743, "text": "Make sure you are not using ad-blockers." }, { "code": null, "e": 6812, "s": 6784, "text": "Disable browser extensions." }, { "code": null, "e": 6883, "s": 6812, "text": "We recommend using latest version of your browser for best experience." }, { "code": null, "e": 7070, "s": 6883, "text": "Avoid using static/global variables in coding problems as your code is tested \n against multiple test cases and these tend to retain their previous values." } ]
Sort elements of an array in increasing order of absolute difference of adjacent elements
28 Jun, 2022 Given an array arr[], the task is to arrange the array in such a way that the absolute difference between the adjacent elements is in increasing order. Examples: Input: arr[] = {8, 1, 2, 3, 0} Output: 2 3 1 8 0 Explanation: |2-3| = 1, |3-1| = 2, |1-8| = 7, |8-0| = 8 The absolute difference between the adjacent elements is in increasing order. Input: -1 -2 3 4 5 Output: 3 4 -1 5 -2 Explanation: |3-4| = 1, |4-(-1)| = 5, |-1-5| = 6, |5-(-2)| = 7 Approach: The idea is to sort the elements of the array and then take the middle element of the array and then repeat this step until the array is not empty. Below is an illustration of the approach with the help of an example: Given Array be - {8, 1, 2, 3, 0} After Sorting the array - {0, 1, 2, 3, 8} Array Middle Ele Output Array --------------- ------------- --------------- {0, 1, 2, 3, 8} 5//2 = 2, 2 2 {0, 1, 3, 8} 4//2 = 2, 3 2, 3 {0, 1, 8} 3//2 = 1, 1 1, 2, 3 {0, 8} 2//2 = 1, 8 1, 2, 3, 8 {0} 1//2 = 0, 0 1, 2, 3, 8, 0 C++ Java Python3 C# Javascript // C++ implementation to sort// the elements of the array in// such a way that absolute// difference between the adjacent// elements are in increasing order#include<bits/stdc++.h>using namespace std; // Function to sort the elements// of the array by differencevoid sortDiff(vector<int> arr, int n){ // Sorting the array sort(arr.begin(), arr.end()); // Array to store the // elements of the array vector<int> out; // Iterating over the length // of the array to include // each middle element of array while(n > 0) { // Appending the middle // element of the array out.push_back(arr[n / 2]); arr.erase(arr.begin() + n / 2); n = n - 1; } for(auto i : out) cout << i << " ";} // Driver Codeint main(){ vector<int> a = {8, 1, 2, 3, 0}; int n = 5; sortDiff(a, n);} // This code is contributed by Chitranayal // Java implementation to sort// the elements of the array in// such a way that absolute// difference between the adjacent// elements are in increasing orderimport java.util.*; class GFG{ // Function to sort the elements// of the array by differencestatic void sortDiff(Vector<Integer> arr, int n){ // Sorting the array Collections.sort(arr); // Array to store the // elements of the array Vector<Integer> out = new Vector<Integer>(); // Iterating over the length // of the array to include // each middle element of array while(n > 0) { // Appending the middle // element of the array out.add(arr.get(n / 2)); arr.remove(n / 2); n = n - 1; } for(int i : out) System.out.print(i + " ");} // Driver Codepublic static void main(String[] args){ Integer []a = { 8, 1, 2, 3, 0 }; Vector<Integer> arr = new Vector<Integer>(Arrays.asList(a)); int n = 5; sortDiff(arr, n);}} // This code is contributed by 29AjayKumar # Python implementation to sort# the elements of the array in# such a way that absolute# difference between the adjacent# elements are in increasing order # Function to sort the elements# of the array by differencedef sortDiff(arr, n): # Sorting the array arr.sort() # Array to store the # elements of the array out = [] # Iterating over the length # of the array to include # each middle element of array while n: # Appending the middle # element of the array out.append(arr.pop(n//2)) n=n-1 print(*out) return out # Driver Codeif __name__ == "__main__": arr = [8, 1, 2, 3, 0] n = 5 sortDiff(arr, n) // C# implementation to sort// the elements of the array in// such a way that absolute// difference between the adjacent// elements are in increasing orderusing System;using System.Collections.Generic;class GFG{ // Function to sort the elements// of the array by differencestatic void sortDiff(List<int> arr, int n){ // Sorting the array arr.Sort(); // Array to store the // elements of the array List<int> Out = new List<int>(); // Iterating over the length // of the array to include // each middle element of array while(n > 0) { // Appending the middle // element of the array Out.Add(arr[n / 2]); arr.RemoveAt(n / 2); n = n - 1; } foreach(int i in Out) Console.Write(i + " ");} // Driver Codepublic static void Main(String[] args){ int []a = { 8, 1, 2, 3, 0 }; List<int> arr = new List<int>(a); int n = 5; sortDiff(arr, n);}} // This code is contributed by sapnasingh4991 <script>// Javascript implementation to sort// the elements of the array in// such a way that absolute// difference between the adjacent// elements are in increasing order // Function to sort the elements// of the array by differencefunction sortDiff(arr,n){ // Sorting the array arr.sort(function(a,b){return a-b;}); // Array to store the // elements of the array let out = []; // Iterating over the length // of the array to include // each middle element of array while(n > 0) { // Appending the middle // element of the array out.push(arr[Math.floor(n / 2)]); arr.splice(Math.floor(n / 2),1); n = n - 1; } for(let i=0;i< out.length;i++) document.write(out[i] + " ");} // Driver Codelet arr=[8, 1, 2, 3, 0 ];let n = 5;sortDiff(arr, n); // This code is contributed by avanitrachhadiya2155</script> 2 3 1 8 0 Time Complexity: O(n2) as erase function takes O(n) time in the worst case.Auxiliary Space: O(n) 29AjayKumar sapnasingh4991 ukasp avanitrachhadiya2155 pushpeshrajdx01 Algorithms Arrays Competitive Programming Sorting Arrays Sorting Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. DSA Sheet by Love Babbar SDE SHEET - A Complete Guide for SDE Preparation What is Hashing | A Complete Tutorial Understanding Time Complexity with Simple Examples CPU Scheduling in Operating Systems Arrays in Java Write a program to reverse an array or string Maximum and minimum of an array using minimum number of comparisons Largest Sum Contiguous Subarray Arrays in C/C++
[ { "code": null, "e": 54, "s": 26, "text": "\n28 Jun, 2022" }, { "code": null, "e": 207, "s": 54, "text": "Given an array arr[], the task is to arrange the array in such a way that the absolute difference between the adjacent elements is in increasing order. " }, { "code": null, "e": 218, "s": 207, "text": "Examples: " }, { "code": null, "e": 402, "s": 218, "text": "Input: arr[] = {8, 1, 2, 3, 0} Output: 2 3 1 8 0 Explanation: |2-3| = 1, |3-1| = 2, |1-8| = 7, |8-0| = 8 The absolute difference between the adjacent elements is in increasing order. " }, { "code": null, "e": 505, "s": 402, "text": "Input: -1 -2 3 4 5 Output: 3 4 -1 5 -2 Explanation: |3-4| = 1, |4-(-1)| = 5, |-1-5| = 6, |5-(-2)| = 7 " }, { "code": null, "e": 734, "s": 505, "text": "Approach: The idea is to sort the elements of the array and then take the middle element of the array and then repeat this step until the array is not empty. Below is an illustration of the approach with the help of an example: " }, { "code": null, "e": 1135, "s": 734, "text": "Given Array be - {8, 1, 2, 3, 0}\n\nAfter Sorting the array - {0, 1, 2, 3, 8}\n\n Array Middle Ele Output Array\n--------------- ------------- ---------------\n{0, 1, 2, 3, 8} 5//2 = 2, 2 2\n{0, 1, 3, 8} 4//2 = 2, 3 2, 3\n{0, 1, 8} 3//2 = 1, 1 1, 2, 3\n{0, 8} 2//2 = 1, 8 1, 2, 3, 8\n{0} 1//2 = 0, 0 1, 2, 3, 8, 0" }, { "code": null, "e": 1139, "s": 1135, "text": "C++" }, { "code": null, "e": 1144, "s": 1139, "text": "Java" }, { "code": null, "e": 1152, "s": 1144, "text": "Python3" }, { "code": null, "e": 1155, "s": 1152, "text": "C#" }, { "code": null, "e": 1166, "s": 1155, "text": "Javascript" }, { "code": "// C++ implementation to sort// the elements of the array in// such a way that absolute// difference between the adjacent// elements are in increasing order#include<bits/stdc++.h>using namespace std; // Function to sort the elements// of the array by differencevoid sortDiff(vector<int> arr, int n){ // Sorting the array sort(arr.begin(), arr.end()); // Array to store the // elements of the array vector<int> out; // Iterating over the length // of the array to include // each middle element of array while(n > 0) { // Appending the middle // element of the array out.push_back(arr[n / 2]); arr.erase(arr.begin() + n / 2); n = n - 1; } for(auto i : out) cout << i << \" \";} // Driver Codeint main(){ vector<int> a = {8, 1, 2, 3, 0}; int n = 5; sortDiff(a, n);} // This code is contributed by Chitranayal", "e": 2086, "s": 1166, "text": null }, { "code": "// Java implementation to sort// the elements of the array in// such a way that absolute// difference between the adjacent// elements are in increasing orderimport java.util.*; class GFG{ // Function to sort the elements// of the array by differencestatic void sortDiff(Vector<Integer> arr, int n){ // Sorting the array Collections.sort(arr); // Array to store the // elements of the array Vector<Integer> out = new Vector<Integer>(); // Iterating over the length // of the array to include // each middle element of array while(n > 0) { // Appending the middle // element of the array out.add(arr.get(n / 2)); arr.remove(n / 2); n = n - 1; } for(int i : out) System.out.print(i + \" \");} // Driver Codepublic static void main(String[] args){ Integer []a = { 8, 1, 2, 3, 0 }; Vector<Integer> arr = new Vector<Integer>(Arrays.asList(a)); int n = 5; sortDiff(arr, n);}} // This code is contributed by 29AjayKumar", "e": 3114, "s": 2086, "text": null }, { "code": "# Python implementation to sort# the elements of the array in# such a way that absolute# difference between the adjacent# elements are in increasing order # Function to sort the elements# of the array by differencedef sortDiff(arr, n): # Sorting the array arr.sort() # Array to store the # elements of the array out = [] # Iterating over the length # of the array to include # each middle element of array while n: # Appending the middle # element of the array out.append(arr.pop(n//2)) n=n-1 print(*out) return out # Driver Codeif __name__ == \"__main__\": arr = [8, 1, 2, 3, 0] n = 5 sortDiff(arr, n)", "e": 3819, "s": 3114, "text": null }, { "code": "// C# implementation to sort// the elements of the array in// such a way that absolute// difference between the adjacent// elements are in increasing orderusing System;using System.Collections.Generic;class GFG{ // Function to sort the elements// of the array by differencestatic void sortDiff(List<int> arr, int n){ // Sorting the array arr.Sort(); // Array to store the // elements of the array List<int> Out = new List<int>(); // Iterating over the length // of the array to include // each middle element of array while(n > 0) { // Appending the middle // element of the array Out.Add(arr[n / 2]); arr.RemoveAt(n / 2); n = n - 1; } foreach(int i in Out) Console.Write(i + \" \");} // Driver Codepublic static void Main(String[] args){ int []a = { 8, 1, 2, 3, 0 }; List<int> arr = new List<int>(a); int n = 5; sortDiff(arr, n);}} // This code is contributed by sapnasingh4991", "e": 4814, "s": 3819, "text": null }, { "code": "<script>// Javascript implementation to sort// the elements of the array in// such a way that absolute// difference between the adjacent// elements are in increasing order // Function to sort the elements// of the array by differencefunction sortDiff(arr,n){ // Sorting the array arr.sort(function(a,b){return a-b;}); // Array to store the // elements of the array let out = []; // Iterating over the length // of the array to include // each middle element of array while(n > 0) { // Appending the middle // element of the array out.push(arr[Math.floor(n / 2)]); arr.splice(Math.floor(n / 2),1); n = n - 1; } for(let i=0;i< out.length;i++) document.write(out[i] + \" \");} // Driver Codelet arr=[8, 1, 2, 3, 0 ];let n = 5;sortDiff(arr, n); // This code is contributed by avanitrachhadiya2155</script>", "e": 5715, "s": 4814, "text": null }, { "code": null, "e": 5725, "s": 5715, "text": "2 3 1 8 0" }, { "code": null, "e": 5824, "s": 5727, "text": "Time Complexity: O(n2) as erase function takes O(n) time in the worst case.Auxiliary Space: O(n)" }, { "code": null, "e": 5836, "s": 5824, "text": "29AjayKumar" }, { "code": null, "e": 5851, "s": 5836, "text": "sapnasingh4991" }, { "code": null, "e": 5857, "s": 5851, "text": "ukasp" }, { "code": null, "e": 5878, "s": 5857, "text": "avanitrachhadiya2155" }, { "code": null, "e": 5894, "s": 5878, "text": "pushpeshrajdx01" }, { "code": null, "e": 5905, "s": 5894, "text": "Algorithms" }, { "code": null, "e": 5912, "s": 5905, "text": "Arrays" }, { "code": null, "e": 5936, "s": 5912, "text": "Competitive Programming" }, { "code": null, "e": 5944, "s": 5936, "text": "Sorting" }, { "code": null, "e": 5951, "s": 5944, "text": "Arrays" }, { "code": null, "e": 5959, "s": 5951, "text": "Sorting" }, { "code": null, "e": 5970, "s": 5959, "text": "Algorithms" }, { "code": null, "e": 6068, "s": 5970, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6093, "s": 6068, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 6142, "s": 6093, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 6180, "s": 6142, "text": "What is Hashing | A Complete Tutorial" }, { "code": null, "e": 6231, "s": 6180, "text": "Understanding Time Complexity with Simple Examples" }, { "code": null, "e": 6267, "s": 6231, "text": "CPU Scheduling in Operating Systems" }, { "code": null, "e": 6282, "s": 6267, "text": "Arrays in Java" }, { "code": null, "e": 6328, "s": 6282, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 6396, "s": 6328, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 6428, "s": 6396, "text": "Largest Sum Contiguous Subarray" } ]
How to Speed Up Gradle build in Android Studio?
22 Mar, 2021 Gradle is one of the most important files or extensions that are present in the Android Project. Gradle handles all the libraries and application IDs and many important components of any Android application. Every time when we run our application or we build our apk we will get to see the message as Gradle build running and many more. In some devices, Gradle works very fast whereas in some devices it takes so much time to load and build your application. 10:03:51 Gradle build finished in 4 min 0 sec 10:04:03 Session 'app': running 10:10:11 Gradle build finished in 3 min 29 sec 10:10:12 Session 'app': running 10:20:24 Gradle build finished in 3 min 42 sec 10:28:18 Gradle build finished in 3 min 40 sec 10:28:19 Session 'app': running 10:31:14 Gradle build finished in 2 min 56 sec 10:31:14 Session 'app': running 10:38:37 Gradle build finished in 3 min 30 sec 10:42:17 Gradle build finished in 3 min 40 sec 10:45:18 Gradle build finished in 3 min 1 sec 10:48:49 Gradle build finished in 3 min 30 sec 10:53:05 Gradle build finished in 3 min 22 sec 10:57:10 Gradle build finished in 3 min 19 sec 10:57:11 Session 'app': running So in this article, we will take a look at optimizing the speed of our Gradle in the Android Studio Project. We are going to discuss 4 different methods for doing this task. Method 1: Offline mode for Gradle Method 2: Using a specific library for google play services Method 3: Removing proxy Method 4: Avoid using more external dependencies in your project Many times when we are building any application or running it on our device or emulator. We will get to see that Gradle connects with our internet and downloads the files from the internet. This process sometimes takes so much time which will depend on your internet connection. So to avoid downloading these files we have to enable offline mode for our android studio for Gradle files to avoid downloading of these files. Below are the steps in which we will be enabling offline mode in our application. Click on the File option which is shown in the top bar of Android Studio. Inside that click on the Settings option. You can get to see the Settings option in the below screen. After clicking on the settings option you will get to see the below dialog. Inside this dialog navigate to the Build, Execution, Deployment option and then click on the Gradle option. After that uncheck the option for Download external annotations and dependencies and after that click on Apply option and then click on the OK option to proceed further. After that we have enabled offline mode for Gradle has been enabled in our android studio project. Now due to offline mode, the loading time for your Gradle will be reduced to a certain extent. When we are adding services provided by google in our application we add the below dependency in our build.gradle file. This dependency is having features of all the services present in it. So this dependency is quite heavy and due to this, it will load several times when we build our application. implementation ‘com.google.android.gms:play-services:8.3.0’ Instead of using this dependency, we should use the dependency of a specific service that we have to use in our application. Let’s suppose we have to use maps service in our application so for that we will be specifically adding the dependency for maps rather than adding the above dependency. This will only provide us the support for using maps. This dependency will take lesser time to load compared to the one which we have used above. implementation ‘com.google.android.gms:play-services-maps:8.3.0’ If Android Studio has a proxy server setting and can’t reach the server then it takes a long time to build, probably it’s trying to reach the proxy server and waiting for a timeout. By removing the proxy server setting it’s working fine. Steps to Removing proxy: File > Settings > Appearance & Behavior > System settings > HTTP Proxy. When we add many dependencies in our Android Studio project it will take much time to compile your android studio project and also manages all the dependencies in your android studio project. As the Gradle file manages all the dependencies of our project so we should use fewer number dependencies which will help us to reduce the time required for the Gradle to sync each time when we create a new apk or run our application in an emulator or device. Android-Studio Picked Android Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Mar, 2021" }, { "code": null, "e": 488, "s": 28, "text": "Gradle is one of the most important files or extensions that are present in the Android Project. Gradle handles all the libraries and application IDs and many important components of any Android application. Every time when we run our application or we build our apk we will get to see the message as Gradle build running and many more. In some devices, Gradle works very fast whereas in some devices it takes so much time to load and build your application. " }, { "code": null, "e": 1196, "s": 488, "text": "10:03:51 Gradle build finished in 4 min 0 sec \n10:04:03 Session 'app': running \n10:10:11 Gradle build finished in 3 min 29 sec \n10:10:12 Session 'app': running \n10:20:24 Gradle build finished in 3 min 42 sec \n10:28:18 Gradle build finished in 3 min 40 sec \n10:28:19 Session 'app': running \n10:31:14 Gradle build finished in 2 min 56 sec \n10:31:14 Session 'app': running \n10:38:37 Gradle build finished in 3 min 30 sec \n10:42:17 Gradle build finished in 3 min 40 sec \n10:45:18 Gradle build finished in 3 min 1 sec \n10:48:49 Gradle build finished in 3 min 30 sec \n10:53:05 Gradle build finished in 3 min 22 sec \n10:57:10 Gradle build finished in 3 min 19 sec \n10:57:11 Session 'app': running " }, { "code": null, "e": 1371, "s": 1196, "text": "So in this article, we will take a look at optimizing the speed of our Gradle in the Android Studio Project. We are going to discuss 4 different methods for doing this task. " }, { "code": null, "e": 1405, "s": 1371, "text": "Method 1: Offline mode for Gradle" }, { "code": null, "e": 1465, "s": 1405, "text": "Method 2: Using a specific library for google play services" }, { "code": null, "e": 1490, "s": 1465, "text": "Method 3: Removing proxy" }, { "code": null, "e": 1555, "s": 1490, "text": "Method 4: Avoid using more external dependencies in your project" }, { "code": null, "e": 2237, "s": 1555, "text": "Many times when we are building any application or running it on our device or emulator. We will get to see that Gradle connects with our internet and downloads the files from the internet. This process sometimes takes so much time which will depend on your internet connection. So to avoid downloading these files we have to enable offline mode for our android studio for Gradle files to avoid downloading of these files. Below are the steps in which we will be enabling offline mode in our application. Click on the File option which is shown in the top bar of Android Studio. Inside that click on the Settings option. You can get to see the Settings option in the below screen. " }, { "code": null, "e": 2786, "s": 2237, "text": "After clicking on the settings option you will get to see the below dialog. Inside this dialog navigate to the Build, Execution, Deployment option and then click on the Gradle option. After that uncheck the option for Download external annotations and dependencies and after that click on Apply option and then click on the OK option to proceed further. After that we have enabled offline mode for Gradle has been enabled in our android studio project. Now due to offline mode, the loading time for your Gradle will be reduced to a certain extent. " }, { "code": null, "e": 3086, "s": 2786, "text": "When we are adding services provided by google in our application we add the below dependency in our build.gradle file. This dependency is having features of all the services present in it. So this dependency is quite heavy and due to this, it will load several times when we build our application. " }, { "code": null, "e": 3146, "s": 3086, "text": "implementation ‘com.google.android.gms:play-services:8.3.0’" }, { "code": null, "e": 3587, "s": 3146, "text": "Instead of using this dependency, we should use the dependency of a specific service that we have to use in our application. Let’s suppose we have to use maps service in our application so for that we will be specifically adding the dependency for maps rather than adding the above dependency. This will only provide us the support for using maps. This dependency will take lesser time to load compared to the one which we have used above. " }, { "code": null, "e": 3652, "s": 3587, "text": "implementation ‘com.google.android.gms:play-services-maps:8.3.0’" }, { "code": null, "e": 3987, "s": 3652, "text": "If Android Studio has a proxy server setting and can’t reach the server then it takes a long time to build, probably it’s trying to reach the proxy server and waiting for a timeout. By removing the proxy server setting it’s working fine. Steps to Removing proxy: File > Settings > Appearance & Behavior > System settings > HTTP Proxy." }, { "code": null, "e": 4439, "s": 3987, "text": "When we add many dependencies in our Android Studio project it will take much time to compile your android studio project and also manages all the dependencies in your android studio project. As the Gradle file manages all the dependencies of our project so we should use fewer number dependencies which will help us to reduce the time required for the Gradle to sync each time when we create a new apk or run our application in an emulator or device." }, { "code": null, "e": 4454, "s": 4439, "text": "Android-Studio" }, { "code": null, "e": 4461, "s": 4454, "text": "Picked" }, { "code": null, "e": 4469, "s": 4461, "text": "Android" }, { "code": null, "e": 4477, "s": 4469, "text": "Android" } ]
Program to print alphabet “A” using stars
15 Apr, 2021 Given the number of lines n, print the alphabet A pattern using stars.Examples : Input : Number of lines : 5 Output : * * * *** * * * * Input : Number of lines : 10 Output : **** * * * * * * * * ****** * * * * * * * * C++ Java Python3 C# PHP Javascript // CPP program to print alphabet A pattern#include <iostream>using namespace std; // Function to display alphabet patternvoid display(int n){ // Outer for loop for number of lines for (int i = 0; i < n; i++) { // Inner for loop for logic execution for (int j = 0; j <= n / 2; j++) { // prints two column lines if ((j == 0 || j == n / 2) && i != 0 || // print first line of alphabet i == 0 && j != 0 && j != n / 2 || // prints middle line i == n / 2) cout << "*"; else cout << " "; } cout << '\n'; }}// Driver Functionint main(){ display(7); return 0;} // Java program to print alphabet A patternimport java.util.Scanner;class PatternA { void display(int n) { // Outer for loop for number of lines for (int i = 0; i < n; i++) { // Inner for loop for logic execution for (int j = 0; j <= n / 2; j++) { // prints two column lines if ((j == 0 || j == n / 2) && i != 0 || // print first line of alphabet i == 0 && j != 0 && j != n / 2 || // prints middle line i == n / 2) System.out.print("*"); else System.out.print(" "); } System.out.println(); } } // Driver Function public static void main(String[] args) { Scanner sc = new Scanner(System.in); PatternA a = new PatternA(); a.display(7); }} # Python3 program to print alphabet A pattern # Function to display alphabet patterndef display(n): # Outer for loop for number of lines for i in range(n): # Inner for loop for logic execution for j in range((n // 2) + 1): # prints two column lines if ((j == 0 or j == n // 2) and i != 0 or # print first line of alphabet i == 0 and j != 0 and j != n // 2 or # prints middle line i == n // 2): print("*", end = "") else: print(" ", end = "") print() # Driver Functiondisplay(7) # This code is contributed by Anant Agarwal. // C# program to print alphabet A patternusing System;class PatternA { void display(int n) { // Outer for loop for number of lines for (int i = 0; i < n; i++) { // Inner for loop for logic execution for (int j = 0; j <= n / 2; j++) { // prints two column lines if ((j == 0 || j == n / 2) && i != 0 || // print first line of alphabet i == 0 && j != 0 && j != n / 2 || // prints middle line i == n / 2) Console.Write("*"); else Console.Write(" "); } Console.WriteLine(); } } // Driver Function public static void Main() { PatternA a = new PatternA(); a.display(7); }}/*This code is contributed by vt_m.*/ <?php// php program to print// alphabet A pattern // Function to display// alphabet patternfunction display($n){ // Outer for loop for // number of lines for ($i = 0; $i < $n; $i++) { // Inner for loop for // logic execution for ($j = 0; $j <= floor($n / 2); $j++) { // prints two column lines // print first line of alphabet // prints middle line if (($j == 0 || $j == floor($n / 2)) && $i != 0 || $i == 0 && $j != 0 && $j != floor($n / 2) || $i == floor($n / 2)) echo "*"; else echo " "; } echo "\n"; }}// Driver Function$n=7;display($n); // This code is contributed by mits?> <script> // JavaScript program to print alphabet A pattern // Function to display alphabet pattern function display(n) { // Outer for loop for number of lines for (var i = 0; i < n; i++) { // Inner for loop for logic execution for (var j = 0; j <= Math.floor(n / 2); j++) { // prints two column lines if ( ((j == 0 || j == Math.floor(n / 2)) && i != 0) || // print first line of alphabet (i == 0 && j != 0 && j != Math.floor(n / 2)) || // prints middle line i == Math.floor(n / 2) ) { document.write("*"); } else document.write(" "); } document.write("<br>"); } } // Driver Function display(7); </script> Output : ** * * * * **** * * * * * * Mithun Kumar rdtank pattern-printing School Programming pattern-printing 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": 111, "s": 28, "text": "Given the number of lines n, print the alphabet A pattern using stars.Examples : " }, { "code": null, "e": 277, "s": 111, "text": "Input : Number of lines : 5\nOutput :\n * \n* *\n***\n* *\n* *\n\nInput : Number of lines : 10\nOutput :\n **** \n* *\n* *\n* *\n* *\n******\n* *\n* *\n* *\n* *" }, { "code": null, "e": 285, "s": 281, "text": "C++" }, { "code": null, "e": 290, "s": 285, "text": "Java" }, { "code": null, "e": 298, "s": 290, "text": "Python3" }, { "code": null, "e": 301, "s": 298, "text": "C#" }, { "code": null, "e": 305, "s": 301, "text": "PHP" }, { "code": null, "e": 316, "s": 305, "text": "Javascript" }, { "code": "// CPP program to print alphabet A pattern#include <iostream>using namespace std; // Function to display alphabet patternvoid display(int n){ // Outer for loop for number of lines for (int i = 0; i < n; i++) { // Inner for loop for logic execution for (int j = 0; j <= n / 2; j++) { // prints two column lines if ((j == 0 || j == n / 2) && i != 0 || // print first line of alphabet i == 0 && j != 0 && j != n / 2 || // prints middle line i == n / 2) cout << \"*\"; else cout << \" \"; } cout << '\\n'; }}// Driver Functionint main(){ display(7); return 0;}", "e": 1039, "s": 316, "text": null }, { "code": "// Java program to print alphabet A patternimport java.util.Scanner;class PatternA { void display(int n) { // Outer for loop for number of lines for (int i = 0; i < n; i++) { // Inner for loop for logic execution for (int j = 0; j <= n / 2; j++) { // prints two column lines if ((j == 0 || j == n / 2) && i != 0 || // print first line of alphabet i == 0 && j != 0 && j != n / 2 || // prints middle line i == n / 2) System.out.print(\"*\"); else System.out.print(\" \"); } System.out.println(); } } // Driver Function public static void main(String[] args) { Scanner sc = new Scanner(System.in); PatternA a = new PatternA(); a.display(7); }}", "e": 1949, "s": 1039, "text": null }, { "code": "# Python3 program to print alphabet A pattern # Function to display alphabet patterndef display(n): # Outer for loop for number of lines for i in range(n): # Inner for loop for logic execution for j in range((n // 2) + 1): # prints two column lines if ((j == 0 or j == n // 2) and i != 0 or # print first line of alphabet i == 0 and j != 0 and j != n // 2 or # prints middle line i == n // 2): print(\"*\", end = \"\") else: print(\" \", end = \"\") print() # Driver Functiondisplay(7) # This code is contributed by Anant Agarwal.", "e": 2642, "s": 1949, "text": null }, { "code": "// C# program to print alphabet A patternusing System;class PatternA { void display(int n) { // Outer for loop for number of lines for (int i = 0; i < n; i++) { // Inner for loop for logic execution for (int j = 0; j <= n / 2; j++) { // prints two column lines if ((j == 0 || j == n / 2) && i != 0 || // print first line of alphabet i == 0 && j != 0 && j != n / 2 || // prints middle line i == n / 2) Console.Write(\"*\"); else Console.Write(\" \"); } Console.WriteLine(); } } // Driver Function public static void Main() { PatternA a = new PatternA(); a.display(7); }}/*This code is contributed by vt_m.*/", "e": 3503, "s": 2642, "text": null }, { "code": "<?php// php program to print// alphabet A pattern // Function to display// alphabet patternfunction display($n){ // Outer for loop for // number of lines for ($i = 0; $i < $n; $i++) { // Inner for loop for // logic execution for ($j = 0; $j <= floor($n / 2); $j++) { // prints two column lines // print first line of alphabet // prints middle line if (($j == 0 || $j == floor($n / 2)) && $i != 0 || $i == 0 && $j != 0 && $j != floor($n / 2) || $i == floor($n / 2)) echo \"*\"; else echo \" \"; } echo \"\\n\"; }}// Driver Function$n=7;display($n); // This code is contributed by mits?>", "e": 4307, "s": 3503, "text": null }, { "code": "<script> // JavaScript program to print alphabet A pattern // Function to display alphabet pattern function display(n) { // Outer for loop for number of lines for (var i = 0; i < n; i++) { // Inner for loop for logic execution for (var j = 0; j <= Math.floor(n / 2); j++) { // prints two column lines if ( ((j == 0 || j == Math.floor(n / 2)) && i != 0) || // print first line of alphabet (i == 0 && j != 0 && j != Math.floor(n / 2)) || // prints middle line i == Math.floor(n / 2) ) { document.write(\"*\"); } else document.write(\" \"); } document.write(\"<br>\"); } } // Driver Function display(7); </script>", "e": 5043, "s": 4307, "text": null }, { "code": null, "e": 5054, "s": 5043, "text": "Output : " }, { "code": null, "e": 5089, "s": 5054, "text": " ** \n* *\n* *\n****\n* *\n* *\n* *" }, { "code": null, "e": 5104, "s": 5091, "text": "Mithun Kumar" }, { "code": null, "e": 5111, "s": 5104, "text": "rdtank" }, { "code": null, "e": 5128, "s": 5111, "text": "pattern-printing" }, { "code": null, "e": 5147, "s": 5128, "text": "School Programming" }, { "code": null, "e": 5164, "s": 5147, "text": "pattern-printing" } ]
Returning Multiple Values in Python
25 Nov, 2020 In Python, we can return multiple values from a function. Following are different ways 1) Using Object: This is similar to C/C++ and Java, we can create a class (in C, struct) to hold multiple values and return an object of the class. # A Python program to return multiple # values from a method using classclass Test: def __init__(self): self.str = "geeksforgeeks" self.x = 20 # This function returns an object of Testdef fun(): return Test() # Driver code to test above methodt = fun() print(t.str)print(t.x) Output: geeksforgeeks 20 Below are interesting methods for somebody shifting C++/Java world. 2) Using Tuple: A Tuple is a comma separated sequence of items. It is created with or without (). Tuples are immutable. See this for details of tuple and list. # A Python program to return multiple # values from a method using tuple # This function returns a tupledef fun(): str = "geeksforgeeks" x = 20 return str, x; # Return tuple, we could also # write (str, x) # Driver code to test above methodstr, x = fun() # Assign returned tupleprint(str)print(x) Output: geeksforgeeks 20 3) Using a list: A list is like an array of items created using square brackets. They are different from arrays as they can contain items of different types. Lists are different from tuples as they are mutable. # A Python program to return multiple # values from a method using list # This function returns a listdef fun(): str = "geeksforgeeks" x = 20 return [str, x]; # Driver code to test above methodlist = fun() print(list) Output: ['geeksforgeeks', 20] 4) Using a Dictionary: A Dictionary is similar to hash or map in other languages. See this for details of dictionary. # A Python program to return multiple # values from a method using dictionary # This function returns a dictionarydef fun(): d = dict(); d['str'] = "GeeksforGeeks" d['x'] = 20 return d # Driver code to test above methodd = fun() print(d) Output: {'x': 20, 'str': 'GeeksforGeeks'} 5) Using Data Class (Python 3.7+): In Python 3.7 and above the Data Class can be used to return a class with automatically added unique methods. The Data Class module has a decorator and functions for automatically adding generated special methods such as __init__() and __repr__() in the user-defined classes. from dataclasses import dataclass @dataclassclass Book_list: name: str perunit_cost: float quantity_available: int = 0 # function to calculate total cost def total_cost(self) -> float: return self.perunit_cost * self.quantity_available book = Book_list("Introduction to programming.", 300, 3)x = book.total_cost() # print the total cost# of the bookprint(x) # print book detailsprint(book) # 900Book_list(name='Python programming.', perunit_cost=200, quantity_available=3) Output: 900 Book_list(name='Introduction to programming.', perunit_cost=300, quantity_available=3) Book_list(name='Python programming.', perunit_cost=200, quantity_available=3) Reference:http://stackoverflow.com/questions/354883/how-do-you-return-multiple-values-in-python This article is contributed by Shubham Agrawal. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above nidhi_biet Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read JSON file using Python Python map() function Adding new column to existing DataFrame in Pandas Python Dictionary How to get column names in Pandas dataframe Different ways to create Pandas Dataframe Taking input in Python Enumerate() in Python Read a file line by line in Python Python String | replace()
[ { "code": null, "e": 52, "s": 24, "text": "\n25 Nov, 2020" }, { "code": null, "e": 139, "s": 52, "text": "In Python, we can return multiple values from a function. Following are different ways" }, { "code": null, "e": 287, "s": 139, "text": "1) Using Object: This is similar to C/C++ and Java, we can create a class (in C, struct) to hold multiple values and return an object of the class." }, { "code": "# A Python program to return multiple # values from a method using classclass Test: def __init__(self): self.str = \"geeksforgeeks\" self.x = 20 # This function returns an object of Testdef fun(): return Test() # Driver code to test above methodt = fun() print(t.str)print(t.x)", "e": 592, "s": 287, "text": null }, { "code": null, "e": 600, "s": 592, "text": "Output:" }, { "code": null, "e": 617, "s": 600, "text": "geeksforgeeks\n20" }, { "code": null, "e": 685, "s": 617, "text": "Below are interesting methods for somebody shifting C++/Java world." }, { "code": null, "e": 847, "s": 687, "text": "2) Using Tuple: A Tuple is a comma separated sequence of items. It is created with or without (). Tuples are immutable. See this for details of tuple and list." }, { "code": "# A Python program to return multiple # values from a method using tuple # This function returns a tupledef fun(): str = \"geeksforgeeks\" x = 20 return str, x; # Return tuple, we could also # write (str, x) # Driver code to test above methodstr, x = fun() # Assign returned tupleprint(str)print(x)", "e": 1177, "s": 847, "text": null }, { "code": null, "e": 1185, "s": 1177, "text": "Output:" }, { "code": null, "e": 1202, "s": 1185, "text": "geeksforgeeks\n20" }, { "code": null, "e": 1415, "s": 1204, "text": "3) Using a list: A list is like an array of items created using square brackets. They are different from arrays as they can contain items of different types. Lists are different from tuples as they are mutable." }, { "code": "# A Python program to return multiple # values from a method using list # This function returns a listdef fun(): str = \"geeksforgeeks\" x = 20 return [str, x]; # Driver code to test above methodlist = fun() print(list)", "e": 1649, "s": 1415, "text": null }, { "code": null, "e": 1657, "s": 1649, "text": "Output:" }, { "code": null, "e": 1679, "s": 1657, "text": "['geeksforgeeks', 20]" }, { "code": null, "e": 1799, "s": 1681, "text": "4) Using a Dictionary: A Dictionary is similar to hash or map in other languages. See this for details of dictionary." }, { "code": "# A Python program to return multiple # values from a method using dictionary # This function returns a dictionarydef fun(): d = dict(); d['str'] = \"GeeksforGeeks\" d['x'] = 20 return d # Driver code to test above methodd = fun() print(d)", "e": 2054, "s": 1799, "text": null }, { "code": null, "e": 2062, "s": 2054, "text": "Output:" }, { "code": null, "e": 2096, "s": 2062, "text": "{'x': 20, 'str': 'GeeksforGeeks'}" }, { "code": null, "e": 2408, "s": 2096, "text": " 5) Using Data Class (Python 3.7+): In Python 3.7 and above the Data Class can be used to return a class with automatically added unique methods. The Data Class module has a decorator and functions for automatically adding generated special methods such as __init__() and __repr__() in the user-defined classes." }, { "code": "from dataclasses import dataclass @dataclassclass Book_list: name: str perunit_cost: float quantity_available: int = 0 # function to calculate total cost def total_cost(self) -> float: return self.perunit_cost * self.quantity_available book = Book_list(\"Introduction to programming.\", 300, 3)x = book.total_cost() # print the total cost# of the bookprint(x) # print book detailsprint(book) # 900Book_list(name='Python programming.', perunit_cost=200, quantity_available=3)", "e": 2944, "s": 2408, "text": null }, { "code": null, "e": 2952, "s": 2944, "text": "Output:" }, { "code": null, "e": 3121, "s": 2952, "text": "900\nBook_list(name='Introduction to programming.', perunit_cost=300, quantity_available=3)\nBook_list(name='Python programming.', perunit_cost=200, quantity_available=3)" }, { "code": null, "e": 3217, "s": 3121, "text": "Reference:http://stackoverflow.com/questions/354883/how-do-you-return-multiple-values-in-python" }, { "code": null, "e": 3486, "s": 3217, "text": "This article is contributed by Shubham Agrawal. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 3610, "s": 3486, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 3621, "s": 3610, "text": "nidhi_biet" }, { "code": null, "e": 3628, "s": 3621, "text": "Python" }, { "code": null, "e": 3726, "s": 3628, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3754, "s": 3726, "text": "Read JSON file using Python" }, { "code": null, "e": 3776, "s": 3754, "text": "Python map() function" }, { "code": null, "e": 3826, "s": 3776, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 3844, "s": 3826, "text": "Python Dictionary" }, { "code": null, "e": 3888, "s": 3844, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 3930, "s": 3888, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 3953, "s": 3930, "text": "Taking input in Python" }, { "code": null, "e": 3975, "s": 3953, "text": "Enumerate() in Python" }, { "code": null, "e": 4010, "s": 3975, "text": "Read a file line by line in Python" } ]
CSS | Font Border
30 Jul, 2021 Sometimes we need to create text and adding the outline to the text. There are mainly two methods to create a border to the fonts which are listed below: Using text-shadow property Using text-stroke property Method 1: Using text-shadow property: The text-shadow property is used to add font border or shadow to the text. Syntax: text-shadow: h-shadow v-shadow blur-radius color|none|initial|inherit; Property Values: h-shadow: It sets horizontal shadow around the font. v-shadow: It sets the vertical shadow around the font. blur-radius: It sets the blur radius around the font. color: It sets color around the font. none: It does not set anything around the font. initial: It sets the font border to its default value. inherit: It inherits the property values from its parent values. Return Value: It returns a font border/shadow around the text.Example 1: This example uses text-shadow property to create shadow to the text. html <!DOCTYPE html><html> <head> <title> CSS text-shadow property </title> <style> h1 { text-shadow: 0 0 3px #FF0000, 0 0 5px #0000FF; } </style></head> <body> <h1>GeeksforGeeks</h1></body> </html> Output: Example 2: This example uses text-shadow property to create bordered text. html <!DOCTYPE html><html> <head> <title> CSS text-shadow property </title> <!-- Style to use text-shadow property --> <style> .GFG { color: white; font-size: 50px; text-shadow: -1px 1px 0 #000, 1px 1px 0 #000, 1px -1px 0 #000, -1px -1px 0 #000; } </style></head> <body> <p class="GFG">GeeksforGeeks</p> </body> </html> Output: Method 2: Using text-stroke property: The text-stroke property is used to add stroke to the text. This property can be used to change the width and color of the text. This property is supported by using the -webkit- prefix.Example: This example uses text-stroke property to create bordered text. html <!DOCTYPE html><html> <head> <title> CSS text-stroke property </title> <!-- Style to use text-stroke property --> <style> .GFG { color: white; font-size: 50px; -webkit-text-stroke-width: 1px; -webkit-text-stroke-color: black; } </style></head> <body> <p class="GFG">GeeksforGeeks</p> </body> </html> Output: Supported Browser: Google Chrome 4.0 Internet Explorer 10.0 Firefox 3.5 Opera 9.6 Safari 4.0 CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples. ajuanjojjj ysachin2314 Picked CSS Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Jul, 2021" }, { "code": null, "e": 183, "s": 28, "text": "Sometimes we need to create text and adding the outline to the text. There are mainly two methods to create a border to the fonts which are listed below: " }, { "code": null, "e": 210, "s": 183, "text": "Using text-shadow property" }, { "code": null, "e": 237, "s": 210, "text": "Using text-stroke property" }, { "code": null, "e": 360, "s": 237, "text": "Method 1: Using text-shadow property: The text-shadow property is used to add font border or shadow to the text. Syntax: " }, { "code": null, "e": 431, "s": 360, "text": "text-shadow: h-shadow v-shadow blur-radius color|none|initial|inherit;" }, { "code": null, "e": 450, "s": 431, "text": "Property Values: " }, { "code": null, "e": 503, "s": 450, "text": "h-shadow: It sets horizontal shadow around the font." }, { "code": null, "e": 558, "s": 503, "text": "v-shadow: It sets the vertical shadow around the font." }, { "code": null, "e": 612, "s": 558, "text": "blur-radius: It sets the blur radius around the font." }, { "code": null, "e": 650, "s": 612, "text": "color: It sets color around the font." }, { "code": null, "e": 698, "s": 650, "text": "none: It does not set anything around the font." }, { "code": null, "e": 753, "s": 698, "text": "initial: It sets the font border to its default value." }, { "code": null, "e": 818, "s": 753, "text": "inherit: It inherits the property values from its parent values." }, { "code": null, "e": 962, "s": 818, "text": "Return Value: It returns a font border/shadow around the text.Example 1: This example uses text-shadow property to create shadow to the text. " }, { "code": null, "e": 967, "s": 962, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> CSS text-shadow property </title> <style> h1 { text-shadow: 0 0 3px #FF0000, 0 0 5px #0000FF; } </style></head> <body> <h1>GeeksforGeeks</h1></body> </html> ", "e": 1237, "s": 967, "text": null }, { "code": null, "e": 1247, "s": 1237, "text": "Output: " }, { "code": null, "e": 1324, "s": 1247, "text": "Example 2: This example uses text-shadow property to create bordered text. " }, { "code": null, "e": 1329, "s": 1324, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> CSS text-shadow property </title> <!-- Style to use text-shadow property --> <style> .GFG { color: white; font-size: 50px; text-shadow: -1px 1px 0 #000, 1px 1px 0 #000, 1px -1px 0 #000, -1px -1px 0 #000; } </style></head> <body> <p class=\"GFG\">GeeksforGeeks</p> </body> </html> ", "e": 1822, "s": 1329, "text": null }, { "code": null, "e": 1832, "s": 1822, "text": "Output: " }, { "code": null, "e": 2130, "s": 1832, "text": "Method 2: Using text-stroke property: The text-stroke property is used to add stroke to the text. This property can be used to change the width and color of the text. This property is supported by using the -webkit- prefix.Example: This example uses text-stroke property to create bordered text. " }, { "code": null, "e": 2135, "s": 2130, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> CSS text-stroke property </title> <!-- Style to use text-stroke property --> <style> .GFG { color: white; font-size: 50px; -webkit-text-stroke-width: 1px; -webkit-text-stroke-color: black; } </style></head> <body> <p class=\"GFG\">GeeksforGeeks</p> </body> </html> ", "e": 2552, "s": 2135, "text": null }, { "code": null, "e": 2562, "s": 2552, "text": "Output: " }, { "code": null, "e": 2581, "s": 2562, "text": "Supported Browser:" }, { "code": null, "e": 2599, "s": 2581, "text": "Google Chrome 4.0" }, { "code": null, "e": 2622, "s": 2599, "text": "Internet Explorer 10.0" }, { "code": null, "e": 2634, "s": 2622, "text": "Firefox 3.5" }, { "code": null, "e": 2644, "s": 2634, "text": "Opera 9.6" }, { "code": null, "e": 2655, "s": 2644, "text": "Safari 4.0" }, { "code": null, "e": 2841, "s": 2655, "text": "CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples." }, { "code": null, "e": 2852, "s": 2841, "text": "ajuanjojjj" }, { "code": null, "e": 2864, "s": 2852, "text": "ysachin2314" }, { "code": null, "e": 2871, "s": 2864, "text": "Picked" }, { "code": null, "e": 2875, "s": 2871, "text": "CSS" }, { "code": null, "e": 2892, "s": 2875, "text": "Web Technologies" }, { "code": null, "e": 2919, "s": 2892, "text": "Web technologies Questions" } ]
Program to reverse a linked list using Stack
18 May, 2022 Given a linked list. The task is to reverse the order of the elements of the Linked List using an auxiliary Stack.Examples: Input : List = 3 -> 2 -> 1 Output : 1 -> 2 -> 3 Input : 9 -> 7 -> 4 -> 2 Output : 2 -> 4 -> 7 -> 9 Algorithm: Traverse the list and push all of its nodes onto a stack.Traverse the list from the head node again and pop a value from the stack top and connect them in reverse order. Traverse the list and push all of its nodes onto a stack. Traverse the list from the head node again and pop a value from the stack top and connect them in reverse order. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C/C++ program to reverse linked list// using stack #include <bits/stdc++.h>using namespace std; /* Link list node */struct Node { int data; struct Node* next;}; /* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */void push(struct Node** head_ref, int new_data){ struct Node* new_node = new Node; new_node->data = new_data; new_node->next = (*head_ref); (*head_ref) = new_node;} // Function to reverse linked listNode *reverseList(Node* head){ // Stack to store elements of list stack<Node *> stk; // Push the elements of list to stack Node* ptr = head; while (ptr->next != NULL) { stk.push(ptr); ptr = ptr->next; } // Pop from stack and replace // current nodes value' head = ptr; while (!stk.empty()) { ptr->next = stk.top(); ptr = ptr->next; stk.pop(); } ptr->next = NULL; return head;} // Function to print the Linked listvoid printList(Node* head){ while (head) { cout << head->data << " "; head = head->next; }} // Driver Codeint main(){ /* Start with the empty list */ struct Node* head = NULL; /* Use push() to construct below list 1->2->3->4->5 */ push(&head, 5); push(&head, 4); push(&head, 3); push(&head, 2); push(&head, 1); head = reverseList(head); printList(head); return 0;} // Java program to reverse linked list // using stack import java.util.*;class GfG { /* Link list node */static class Node{ int data; Node next; }static Node head = null; /* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */static void push( int new_data) { Node new_node = new Node(); new_node.data = new_data; new_node.next = (head); (head) = new_node; } // Function to reverse linked list static Node reverseList(Node head) { // Stack to store elements of list Stack<Node > stk = new Stack<Node> (); // Push the elements of list to stack Node ptr = head; while (ptr.next != null) { stk.push(ptr); ptr = ptr.next; } // Pop from stack and replace // current nodes value' head = ptr; while (!stk.isEmpty()) { ptr.next = stk.peek(); ptr = ptr.next; stk.pop(); } ptr.next = null; return head; } // Function to print the Linked list static void printList(Node head) { while (head != null) { System.out.print(head.data + " "); head = head.next; } } // Driver Code public static void main(String[] args) { /* Start with the empty list */ //Node head = null; /* Use push() to construct below list 1->2->3->4->5 */ push( 5); push( 4); push( 3); push( 2); push( 1); head = reverseList(head); printList(head); }} // This code is contributed by Prerna Saini. # Python3 program to reverse a linked# list using stack # Link list node class Node: def __init__(self, data, next): self.data = data self.next = next class LinkedList: def __init__(self): self.head = None # Function to push a new Node in # the linked list def push(self, new_data): new_node = Node(new_data, self.head) self.head = new_node # Function to reverse linked list def reverseList(self): # Stack to store elements of list stk = [] # Push the elements of list to stack ptr = self.head while ptr.next != None: stk.append(ptr) ptr = ptr.next # Pop from stack and replace # current nodes value' self.head = ptr while len(stk) != 0: ptr.next = stk.pop() ptr = ptr.next ptr.next = None # Function to print the Linked list def printList(self): curr = self.head while curr: print(curr.data, end = " ") curr = curr.next # Driver Code if __name__ == "__main__": # Start with the empty list linkedList = LinkedList() # Use push() to construct below list # 1.2.3.4.5 linkedList.push(5) linkedList.push(4) linkedList.push(3) linkedList.push(2) linkedList.push(1) linkedList.reverseList() linkedList.printList() # This code is contributed by Rituraj Jain // C# program to reverse linked list // using stack using System;using System.Collections.Generic; class GfG { /* Link list node */public class Node { public int data; public Node next; } static Node head = null; /* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */static void push( int new_data) { Node new_node = new Node(); new_node.data = new_data; new_node.next = (head); (head) = new_node; } // Function to reverse linked list static Node reverseList(Node head) { // Stack to store elements of list Stack<Node > stk = new Stack<Node> (); // Push the elements of list to stack Node ptr = head; while (ptr.next != null) { stk.Push(ptr); ptr = ptr.next; } // Pop from stack and replace // current nodes value' head = ptr; while (stk.Count != 0) { ptr.next = stk.Peek(); ptr = ptr.next; stk.Pop(); } ptr.next = null; return head; } // Function to print the Linked list static void printList(Node head) { while (head != null) { Console.Write(head.data + " "); head = head.next; } } // Driver Code public static void Main(String[] args) { /* Start with the empty list */ //Node head = null; /* Use push() to construct below list 1->2->3->4->5 */ push( 5); push( 4); push( 3); push( 2); push( 1); head = reverseList(head); printList(head); } } // This code contributed by Rajput-Ji <script> // JavaScript program to reverse linked list // using stack /* Link list node */ class Node { constructor() { this.data = 0; this.next = null; } } var head = null; /* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */ function push(new_data) { var new_node = new Node(); new_node.data = new_data; new_node.next = head; head = new_node; } // Function to reverse linked list function reverseList(head) { // Stack to store elements of list var stk = []; // Push the elements of list to stack var ptr = head; while (ptr.next != null) { stk.push(ptr); ptr = ptr.next; } // Pop from stack and replace // current nodes value' head = ptr; while (stk.length != 0) { ptr.next = stk[stk.length - 1]; ptr = ptr.next; stk.pop(); } ptr.next = null; return head; } // Function to print the Linked list function printList(head) { while (head != null) { document.write(head.data + " "); head = head.next; } } // Driver Code /* Start with the empty list */ //Node head = null; /* Use push() to construct below list 1->2->3->4->5 */ push(5); push(4); push(3); push(2); push(1); head = reverseList(head); printList(head); </script> 5 4 3 2 1 Time Complexity : O(n), as we are traversing over the linked list of size N using a while loop. Auxiliary Space: O(N), as we are using stack of size N in worst case which is extra space.We can reverse a linked list with O(1) auxiliary space. See more methods to reverse a linked list. prerna saini rituraj_jain VishalBachchas Rajput-Ji rdtank rohitsingh07052 Python DSA-exercises Python LinkedList-exercises Python-Data-Structures Reverse Linked List Stack Linked List Stack Reverse Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Data Structures Linked List vs Array What is Data Structure: Types, Classifications and Applications Implementing a Linked List in Java using Class Find Length of a Linked List (Iterative and Recursive) Stack in Python Stack Class in Java Check for Balanced Brackets in an expression (well-formedness) using Stack Introduction to Data Structures Stack | Set 2 (Infix to Postfix)
[ { "code": null, "e": 54, "s": 26, "text": "\n18 May, 2022" }, { "code": null, "e": 180, "s": 54, "text": "Given a linked list. The task is to reverse the order of the elements of the Linked List using an auxiliary Stack.Examples: " }, { "code": null, "e": 281, "s": 180, "text": "Input : List = 3 -> 2 -> 1\nOutput : 1 -> 2 -> 3\n\nInput : 9 -> 7 -> 4 -> 2\nOutput : 2 -> 4 -> 7 -> 9 " }, { "code": null, "e": 296, "s": 283, "text": "Algorithm: " }, { "code": null, "e": 466, "s": 296, "text": "Traverse the list and push all of its nodes onto a stack.Traverse the list from the head node again and pop a value from the stack top and connect them in reverse order." }, { "code": null, "e": 524, "s": 466, "text": "Traverse the list and push all of its nodes onto a stack." }, { "code": null, "e": 637, "s": 524, "text": "Traverse the list from the head node again and pop a value from the stack top and connect them in reverse order." }, { "code": null, "e": 690, "s": 637, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 694, "s": 690, "text": "C++" }, { "code": null, "e": 699, "s": 694, "text": "Java" }, { "code": null, "e": 707, "s": 699, "text": "Python3" }, { "code": null, "e": 710, "s": 707, "text": "C#" }, { "code": null, "e": 721, "s": 710, "text": "Javascript" }, { "code": "// C/C++ program to reverse linked list// using stack #include <bits/stdc++.h>using namespace std; /* Link list node */struct Node { int data; struct Node* next;}; /* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */void push(struct Node** head_ref, int new_data){ struct Node* new_node = new Node; new_node->data = new_data; new_node->next = (*head_ref); (*head_ref) = new_node;} // Function to reverse linked listNode *reverseList(Node* head){ // Stack to store elements of list stack<Node *> stk; // Push the elements of list to stack Node* ptr = head; while (ptr->next != NULL) { stk.push(ptr); ptr = ptr->next; } // Pop from stack and replace // current nodes value' head = ptr; while (!stk.empty()) { ptr->next = stk.top(); ptr = ptr->next; stk.pop(); } ptr->next = NULL; return head;} // Function to print the Linked listvoid printList(Node* head){ while (head) { cout << head->data << \" \"; head = head->next; }} // Driver Codeint main(){ /* Start with the empty list */ struct Node* head = NULL; /* Use push() to construct below list 1->2->3->4->5 */ push(&head, 5); push(&head, 4); push(&head, 3); push(&head, 2); push(&head, 1); head = reverseList(head); printList(head); return 0;}", "e": 2170, "s": 721, "text": null }, { "code": "// Java program to reverse linked list // using stack import java.util.*;class GfG { /* Link list node */static class Node{ int data; Node next; }static Node head = null; /* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */static void push( int new_data) { Node new_node = new Node(); new_node.data = new_data; new_node.next = (head); (head) = new_node; } // Function to reverse linked list static Node reverseList(Node head) { // Stack to store elements of list Stack<Node > stk = new Stack<Node> (); // Push the elements of list to stack Node ptr = head; while (ptr.next != null) { stk.push(ptr); ptr = ptr.next; } // Pop from stack and replace // current nodes value' head = ptr; while (!stk.isEmpty()) { ptr.next = stk.peek(); ptr = ptr.next; stk.pop(); } ptr.next = null; return head; } // Function to print the Linked list static void printList(Node head) { while (head != null) { System.out.print(head.data + \" \"); head = head.next; } } // Driver Code public static void main(String[] args) { /* Start with the empty list */ //Node head = null; /* Use push() to construct below list 1->2->3->4->5 */ push( 5); push( 4); push( 3); push( 2); push( 1); head = reverseList(head); printList(head); }} // This code is contributed by Prerna Saini.", "e": 3708, "s": 2170, "text": null }, { "code": "# Python3 program to reverse a linked# list using stack # Link list node class Node: def __init__(self, data, next): self.data = data self.next = next class LinkedList: def __init__(self): self.head = None # Function to push a new Node in # the linked list def push(self, new_data): new_node = Node(new_data, self.head) self.head = new_node # Function to reverse linked list def reverseList(self): # Stack to store elements of list stk = [] # Push the elements of list to stack ptr = self.head while ptr.next != None: stk.append(ptr) ptr = ptr.next # Pop from stack and replace # current nodes value' self.head = ptr while len(stk) != 0: ptr.next = stk.pop() ptr = ptr.next ptr.next = None # Function to print the Linked list def printList(self): curr = self.head while curr: print(curr.data, end = \" \") curr = curr.next # Driver Code if __name__ == \"__main__\": # Start with the empty list linkedList = LinkedList() # Use push() to construct below list # 1.2.3.4.5 linkedList.push(5) linkedList.push(4) linkedList.push(3) linkedList.push(2) linkedList.push(1) linkedList.reverseList() linkedList.printList() # This code is contributed by Rituraj Jain ", "e": 5224, "s": 3708, "text": null }, { "code": "// C# program to reverse linked list // using stack using System;using System.Collections.Generic; class GfG { /* Link list node */public class Node { public int data; public Node next; } static Node head = null; /* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */static void push( int new_data) { Node new_node = new Node(); new_node.data = new_data; new_node.next = (head); (head) = new_node; } // Function to reverse linked list static Node reverseList(Node head) { // Stack to store elements of list Stack<Node > stk = new Stack<Node> (); // Push the elements of list to stack Node ptr = head; while (ptr.next != null) { stk.Push(ptr); ptr = ptr.next; } // Pop from stack and replace // current nodes value' head = ptr; while (stk.Count != 0) { ptr.next = stk.Peek(); ptr = ptr.next; stk.Pop(); } ptr.next = null; return head; } // Function to print the Linked list static void printList(Node head) { while (head != null) { Console.Write(head.data + \" \"); head = head.next; } } // Driver Code public static void Main(String[] args) { /* Start with the empty list */ //Node head = null; /* Use push() to construct below list 1->2->3->4->5 */ push( 5); push( 4); push( 3); push( 2); push( 1); head = reverseList(head); printList(head); } } // This code contributed by Rajput-Ji", "e": 6796, "s": 5224, "text": null }, { "code": "<script> // JavaScript program to reverse linked list // using stack /* Link list node */ class Node { constructor() { this.data = 0; this.next = null; } } var head = null; /* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */ function push(new_data) { var new_node = new Node(); new_node.data = new_data; new_node.next = head; head = new_node; } // Function to reverse linked list function reverseList(head) { // Stack to store elements of list var stk = []; // Push the elements of list to stack var ptr = head; while (ptr.next != null) { stk.push(ptr); ptr = ptr.next; } // Pop from stack and replace // current nodes value' head = ptr; while (stk.length != 0) { ptr.next = stk[stk.length - 1]; ptr = ptr.next; stk.pop(); } ptr.next = null; return head; } // Function to print the Linked list function printList(head) { while (head != null) { document.write(head.data + \" \"); head = head.next; } } // Driver Code /* Start with the empty list */ //Node head = null; /* Use push() to construct below list 1->2->3->4->5 */ push(5); push(4); push(3); push(2); push(1); head = reverseList(head); printList(head); </script>", "e": 8394, "s": 6796, "text": null }, { "code": null, "e": 8404, "s": 8394, "text": "5 4 3 2 1" }, { "code": null, "e": 8502, "s": 8406, "text": "Time Complexity : O(n), as we are traversing over the linked list of size N using a while loop." }, { "code": null, "e": 8692, "s": 8502, "text": "Auxiliary Space: O(N), as we are using stack of size N in worst case which is extra space.We can reverse a linked list with O(1) auxiliary space. See more methods to reverse a linked list. " }, { "code": null, "e": 8705, "s": 8692, "text": "prerna saini" }, { "code": null, "e": 8718, "s": 8705, "text": "rituraj_jain" }, { "code": null, "e": 8733, "s": 8718, "text": "VishalBachchas" }, { "code": null, "e": 8743, "s": 8733, "text": "Rajput-Ji" }, { "code": null, "e": 8750, "s": 8743, "text": "rdtank" }, { "code": null, "e": 8766, "s": 8750, "text": "rohitsingh07052" }, { "code": null, "e": 8787, "s": 8766, "text": "Python DSA-exercises" }, { "code": null, "e": 8815, "s": 8787, "text": "Python LinkedList-exercises" }, { "code": null, "e": 8838, "s": 8815, "text": "Python-Data-Structures" }, { "code": null, "e": 8846, "s": 8838, "text": "Reverse" }, { "code": null, "e": 8858, "s": 8846, "text": "Linked List" }, { "code": null, "e": 8864, "s": 8858, "text": "Stack" }, { "code": null, "e": 8876, "s": 8864, "text": "Linked List" }, { "code": null, "e": 8882, "s": 8876, "text": "Stack" }, { "code": null, "e": 8890, "s": 8882, "text": "Reverse" }, { "code": null, "e": 8988, "s": 8890, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9020, "s": 8988, "text": "Introduction to Data Structures" }, { "code": null, "e": 9041, "s": 9020, "text": "Linked List vs Array" }, { "code": null, "e": 9105, "s": 9041, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 9152, "s": 9105, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 9207, "s": 9152, "text": "Find Length of a Linked List (Iterative and Recursive)" }, { "code": null, "e": 9223, "s": 9207, "text": "Stack in Python" }, { "code": null, "e": 9243, "s": 9223, "text": "Stack Class in Java" }, { "code": null, "e": 9318, "s": 9243, "text": "Check for Balanced Brackets in an expression (well-formedness) using Stack" }, { "code": null, "e": 9350, "s": 9318, "text": "Introduction to Data Structures" } ]
Sum of list (with string types) in Python
04 Dec, 2020 In Python, type of behavior will not change for data type. Below example is list containing integer type in string.so, we have to take all int type numbers from list even it is declared in string. Examples: Input : list1 = [12, 'geek', 2, '41', 'for', 10, '8', 6, 4, 'geeks', 7, '10'] Output : 100 Input : list1 = [100, 'geek', 200, '400', 'for', 101, '2018', 64, 74, 'geeks', 27, '7810'] Output :10794 We use type() in Python and isdigit() in Python to achieve this. # Python program to find sum of list with different# types. def calsum(l): # returning sum of list using List comprehension return sum([int(i) for i in l if type(i)== int or i.isdigit()]) # Declaring listlist1 = [12, 'geek', 2, '41', 'for', 10, '8', 6, 4, 'geeks', 7, '10']list2 = [100, 'geek', 200, '400', 'for', 101, '2018', 64, 74, 'geeks', 27, '7810'] # Result of sum of listprint (calsum(list1))print (calsum(list2)) python-list Python python-list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n04 Dec, 2020" }, { "code": null, "e": 225, "s": 28, "text": "In Python, type of behavior will not change for data type. Below example is list containing integer type in string.so, we have to take all int type numbers from list even it is declared in string." }, { "code": null, "e": 235, "s": 225, "text": "Examples:" }, { "code": null, "e": 465, "s": 235, "text": "Input : list1 = [12, 'geek', 2, '41', 'for', 10, '8', 6, 4, 'geeks', 7, '10']\nOutput : 100\n\nInput : list1 = [100, 'geek', 200, '400', 'for', 101, '2018', \n 64, 74, 'geeks', 27, '7810']\nOutput :10794\n" }, { "code": null, "e": 530, "s": 465, "text": "We use type() in Python and isdigit() in Python to achieve this." }, { "code": "# Python program to find sum of list with different# types. def calsum(l): # returning sum of list using List comprehension return sum([int(i) for i in l if type(i)== int or i.isdigit()]) # Declaring listlist1 = [12, 'geek', 2, '41', 'for', 10, '8', 6, 4, 'geeks', 7, '10']list2 = [100, 'geek', 200, '400', 'for', 101, '2018', 64, 74, 'geeks', 27, '7810'] # Result of sum of listprint (calsum(list1))print (calsum(list2))", "e": 964, "s": 530, "text": null }, { "code": null, "e": 976, "s": 964, "text": "python-list" }, { "code": null, "e": 983, "s": 976, "text": "Python" }, { "code": null, "e": 995, "s": 983, "text": "python-list" } ]
SAP GRC - Quick Guide
SAP Governance, Risk and Compliance solution enables organizations to manage regulations and compliance and remove any risk in managing organizations’ key operations. As per changing market situation, organizations are growing and rapidly changing and inappropriate documents, spreadsheets are not acceptable for external auditors and regulators. SAP GRC helps organization to manage their regulations and compliance and perform the following activities − Easy integration of GRC activities into existing process and automating key GRC activities. Easy integration of GRC activities into existing process and automating key GRC activities. Low complexity and managing risk efficiently. Low complexity and managing risk efficiently. Improve risk management activities. Improve risk management activities. Managing fraud in business processed and audit management effectively. Managing fraud in business processed and audit management effectively. Organizations perform better and companies can protect their values. Organizations perform better and companies can protect their values. SAP GRC solution consists of three main areas: Analyze, manage and monitor. SAP GRC solution consists of three main areas: Analyze, manage and monitor. Let us now understand the different modules in SAP GRC − To mitigate risk in an organization, it is required to perform risk control as part of compliance and regulation practice. Responsibilities should be clearly defined, managing role provisioning and managing access for super user is critical for managing risk in an organization. SAP GRC Process Control software solution is used for managing compliance and policy management. The compliance management capabilities allow organizations to manage and monitor their internal control environments. Organizations can proactively fix any identified issues and certify and report on the overall state of the corresponding compliance activities. SAP Process control supports the complete life cycle of policy management, including the distribution and adherence of policies by target groups. These policies help organizations to reduce the cost of compliance and improve management transparency and enables organization to develop compliance management processes and policies in business environment. SAP GRC Risk Management allows you to manage risk management activities. You can do advance planning to identify risk in business and implement measures to manage risk and allow you to make better decision that improves the performance of business. Risks come in many forms − Operational Risk Strategic Risk Compliance Risk Financial Risk This is used to improve the audit management process in an organization by documenting artifacts, organizing work papers, and creating audit reports. You can easily integrate with other governance, risk and compliance solution and enable organizations to align audit management policies with business goals. SAP GRC audit management helps auditor in making things simple by providing the following capabilities − You can instantly capture the artifacts for audit management and other evidences using mobile capabilities drag-drop feature. You can instantly capture the artifacts for audit management and other evidences using mobile capabilities drag-drop feature. You can easily create, track, and manage audit issues with global monitoring and follow up. You can easily create, track, and manage audit issues with global monitoring and follow up. You can perform search using search capabilities that allows to get more information from legacy and working papers. You can perform search using search capabilities that allows to get more information from legacy and working papers. You can engage auditors with a user-friendly interface and collaboration tools. You can engage auditors with a user-friendly interface and collaboration tools. Easy integration of audit management with SAP Fraud Management, SAP Risk Management, and SAP Process Control to align audit process with business goals. Easy integration of audit management with SAP Fraud Management, SAP Risk Management, and SAP Process Control to align audit process with business goals. Quick resolution of issues using automated tracking tool. Quick resolution of issues using automated tracking tool. Enhance the staff utilization, and less travel costs resulted from internal audit planning, resource management, and scheduling. Enhance the staff utilization, and less travel costs resulted from internal audit planning, resource management, and scheduling. Easy integration with SAP Business Objects reporting and data visualization tool to visualize audit reports using Lumira and other BI reporting. Easy integration with SAP Business Objects reporting and data visualization tool to visualize audit reports using Lumira and other BI reporting. Use of pre-established templates to standardize audit artifacts and reporting process. Use of pre-established templates to standardize audit artifacts and reporting process. SAP GRC fraud management tool helps organizations to detect and prevent frauds at early stage and hence reducing minimizing the business loss. Scans can be performed on huge amount of data in real time with more accuracy and fraudent activities can be easily identified. SAP fraud management software can help organizations with following capabilities − Easy investigation and documentation of fraud cases. Easy investigation and documentation of fraud cases. Increase the system alert and responsiveness to prevent fraudent activities to happen more frequently in future. Increase the system alert and responsiveness to prevent fraudent activities to happen more frequently in future. Easy scanning of high volumes of transactions and business data. Easy scanning of high volumes of transactions and business data. SAP GRC GTS software helps organizations to enhance cross border supply within limits of international trade management. It helps in reducing the penalty of risks from International Trade Regulation authorities. It provides centralize global trade management process with a single repository for all compliance master data and content irrespective of size of an organization. SAP BusinessObjects GRC solution consists of three main capabilities − Analyze, Manage and Monitor. In the following diagram, you can see the SAP GRC Capability Model that covers all the key features of SAP GRC software. Using GRC, organizations can check for all potential risks and compliance findings and can take correct decision to mitigate them. In older versions of SAP GRC, to use access control, process control and risk management, there was a separate navigation for each component. This means that users, to perform cross component duties, had to login to each module separately and login multiple times. This resulted in a tough process to manage multiple windows and documents to search was also tough. SAP GRC 10.0 provides direct navigation to access control, process control and risk management components for a single user as per authorization and removes the management of multiple windows. Step 1 − To perform customizing activities and maintain configuration settings for GRC solution, go to T-code − SPRO → SAP Reference IMG Step 2 − Expand Governance, Risk and Compliance node − Step 3 − Logon to NetWeaver Business Client − Run the transaction for NWBC in SAP Easy access. It will open NetWeaver Business Client screen and you will receive the following url − http://ep5crgrc.renterpserver.com:8070/nwbc/~launch/ You can use Work Centers to provide a central access point for GRC 10.0. They can be organized based on what the customer has been licensed to operate. Step 1 − To access Work Centers, open NetWeaver Business Client as mentioned above. Go to /nwbc option at the top to open Work Centers. Step 2 − Once you click, you will be directed to the home screen of SAP NetWeaver Business client. Depending on the products that you have licensed, different components of the GRC solution are displayed − Access Control, Process Control, or Risk Management. SAP GRC access control helps organizations to automatically detect, manage and prevent access risk violations and reduce unauthorized access to company data and information. Users can use automatic self-service to access request submission, workflow driven access request and approvals of access. Automatic reviews of user access, role authorization and risk violations can be used using SAP GRC Access Control. SAP GRC Access Control handles key challenges by allowing business to manage access risk. It helps organizations to prevent unauthorized access by defining segregation of duties SoD and critical access and minimizing the time and cost of access risk management. The following are the key features of SAP GRC Access Control − To perform audit and compliance as per legal requirements with different audit standards like SOX, BSI and ISO standards. To perform audit and compliance as per legal requirements with different audit standards like SOX, BSI and ISO standards. To automatically detect access risk violations across SAP and non-SAP systems in an organization. To automatically detect access risk violations across SAP and non-SAP systems in an organization. As mentioned, it empowers users with self-service access submission, workflowdriven access requests and approvals of the request. As mentioned, it empowers users with self-service access submission, workflowdriven access requests and approvals of the request. To automate reviews of user access, role authorizations, risk violations, and control assignments in a small and large scale organization. To automate reviews of user access, role authorizations, risk violations, and control assignments in a small and large scale organization. To efficiently manage the super-user access and avoiding risk violations and unauthorized access to data and application in SAP and non-SAP system. To efficiently manage the super-user access and avoiding risk violations and unauthorized access to data and application in SAP and non-SAP system. Run the transaction for NWBC in SAP Easy access. It will open NetWeaver Business Client screen and you will receive the following url − http://ep5crgrc.renterpserver.com:8070/nwbc/~launch/ Step 1 − To access Work Centers, open NetWeaver Business Client as mentioned above. Go to /nwbc option at the top to open Work Centers. Step 2 − Once you click, you will be directed to the home screen of SAP NetWeaver Business client. Step 3 − Go to setup work center and explore the work set. Click some of the links under each one and explore the various screens. Step 4 − The Setup work center is available in Access Control and provides links to the following sections − Access Rule Maintenance Exception Access Rules Critical Access Rules Generated Rules Organizations Mitigating Controls Superuser Assignment Superuser Maintenance Access Owners Step 5 − You can use the above listed functions in the following ways − Using Access Rule Maintenance section, you can manage access rule sets, functions, and the access risks used to identify access violations. Using Access Rule Maintenance section, you can manage access rule sets, functions, and the access risks used to identify access violations. Using Exception Access Rules, you can manage rules that supplement access rules. Using Exception Access Rules, you can manage rules that supplement access rules. Using critical access rules section, you can define additional rules that identify access to critical roles and profiles. Using critical access rules section, you can define additional rules that identify access to critical roles and profiles. Using generated rules section, you can find and view generated access rules. Using generated rules section, you can find and view generated access rules. Under Organizations, you can maintain the company's organization structure for compliance and risk management with related assignments. Under Organizations, you can maintain the company's organization structure for compliance and risk management with related assignments. The Mitigating Controls section allows you to manage controls to mitigate segregation of duty, critical action, and critical permission access violations. The Mitigating Controls section allows you to manage controls to mitigate segregation of duty, critical action, and critical permission access violations. Superuser Assignment is where you assign owners to firefighter IDs and assign firefighter IDs to users. Superuser Assignment is where you assign owners to firefighter IDs and assign firefighter IDs to users. Superuser Maintenance is where you maintain firefighter, controller, and reason code assignments. Superuser Maintenance is where you maintain firefighter, controller, and reason code assignments. Under Access Owners, you manage owner privileges for access management capabilities. Under Access Owners, you manage owner privileges for access management capabilities. As per GRC software license, you can navigate Access Management Work Center. It has multiple sections to manage access control activities. When you click on Access Management Work Center, you can see the following sections − GRC Role Assignments Access Risk Analysis Mitigated Access Access Requests Administration Role Management Role Mining Role Mass Maintenance Superuser Assignment Superuser Maintenance Access Request Creation Compliance Certification Reviews Alerts Scheduling The above sections help you in the following ways − When you go to access risk analysis section, you can evaluate your systems for access risks across users, roles, HR objects and organization levels. An access risk is two or more actions or permissions that, when available to a single user or single role, profile, organizational level, or HR Object, creates the possibility of error or irregularity. When you go to access risk analysis section, you can evaluate your systems for access risks across users, roles, HR objects and organization levels. An access risk is two or more actions or permissions that, when available to a single user or single role, profile, organizational level, or HR Object, creates the possibility of error or irregularity. Using mitigated access section, you can identify access risks, assess the level of those risks, and assign mitigating controls to users, roles, and profiles to mitigate the access rule violations. Using mitigated access section, you can identify access risks, assess the level of those risks, and assign mitigating controls to users, roles, and profiles to mitigate the access rule violations. In access request administration section, you can manage access assignments, accounts, and review processes. In access request administration section, you can manage access assignments, accounts, and review processes. Using role management, you manage roles from multiple systems in a single unified repository. Using role management, you manage roles from multiple systems in a single unified repository. In role mining group feature, you can target roles of interest, analyze them, and take action. In role mining group feature, you can target roles of interest, analyze them, and take action. Using role mass maintenance, you can import and change authorizations and attributes for multiple roles. Using role mass maintenance, you can import and change authorizations and attributes for multiple roles. In Superuser Assignment section, you can assign firefighter IDs to owners and assign firefighters and controllers to firefighter IDs. In Superuser Assignment section, you can assign firefighter IDs to owners and assign firefighters and controllers to firefighter IDs. In Superuser Maintenance section, you can perform activities such as researching and maintaining firefighters and controllers, and assigning reason codes by system. In Superuser Maintenance section, you can perform activities such as researching and maintaining firefighters and controllers, and assigning reason codes by system. Using access request creation, you can create access assignments and accounts. Using access request creation, you can create access assignments and accounts. Compliance certification reviews supports reviews of users’ access, risk violations and role assignments. Compliance certification reviews supports reviews of users’ access, risk violations and role assignments. Using alerts, you can generate by the application for execution of critical or conflicting actions. Using alerts, you can generate by the application for execution of critical or conflicting actions. Using Scheduling section of the Rule Setup Work Center, you can maintain schedules for continuous control monitoring and automated testing, and to track related job progress. Using Scheduling section of the Rule Setup Work Center, you can maintain schedules for continuous control monitoring and automated testing, and to track related job progress. In SAP GRC solution, you can manage authorization objects to limit the items and data that a user can access. Authorization controls what a user can access in regards to work centers and reports in SAP system. To access GRC solution, you should have following access − Portal authorization Applicable PFCG roles PFCG roles for access control, process control and risk management The authorization types listed below are required as per GRC components − AC, PC and RM. In SAP GRC 10.0 solution, work centers are defined in PCD roles for the Portal component and in PFCG roles for NWBC (NetWeaver Business Client). The work centers are fixed in each base role. SAP delivers these roles however; these roles can be modified by the customer as per requirement. The locations of application folders and subordinate applications within the service map are controlled by the SAP NetWeaver Launchpad application. Service map is controlled by user authorization so if user doesn’t have authorization to see any application they will be hidden in NetWeaver Business client. Follow these steps to review role assignments − Step 1 − Go to Access Management Work Center in NetWeaver Business Client. Step 2 − Select business process under GRC Role assignment and go to sub-process role level. Click next to continue to assign role sections. Step 1 − Go to Master Data Work Center → Organizations Step 2 − In next window, select any organization from the list, then click Open. Step 3 − Note that the triangle next to the organization means that there are suborganizations and the dot next to the organization means that it is the lowest level. Step 4 − Click on subprocess tab → Assign subprocess. Now select one or two subprocesses and click on Next. Step 5 − Without making any changes, click Finish on the Select Controls step. Step 6 − Choose the first subprocess from the list, then click Open. You should see the subprocess details. Step 7 − Click the Roles Tab. Choose a role from the list, then click Assign. SAP GRC Access Control uses UME roles to control the user authorization in the system. An administrator can use actions which represent the smallest entity of UME role that a user can use to build access rights. One UME role can contain actions from one or more applications. You have to assign UME roles to users in User Management Engine (UME). When a user does not have access to a certain tab, the tab will not display upon user logon when the user tries to access that tab. When a UME action for a tab is assigned to that particular user, only then he will be able to access that function. All available standard UME actions for CC tabs can be found in the tab “Assigned Actions” of the Admin User. You should create an administrator role and this role should be assigned to Superuser to perform SAP compliance calibrator related activities. There are various CC roles that can be created under SAP GRC Access control at the time of implementation − CC.ReportingView Description − Compliance Calibrator Display and Reporting Description − Compliance Calibrator Display and Reporting CC.RuleMaintenance Description − Compliance Calibrator Rule Maintenance Description − Compliance Calibrator Rule Maintenance CC.MitMaintenance Description − Compliance Calibrator Mitigation Maintenance Description − Compliance Calibrator Mitigation Maintenance CC.Administration Description − Compliance Calibrator Administration and Basis Configuration Description − Compliance Calibrator Administration and Basis Configuration Using UME, you can perform various key activities under Access Control − You can perform user and role maintenance It can be used for user data source configuration You can apply security settings and password rules To open UME, you should use the following URL − http://<hostname>:<port>/useradmin In SAP GRC 10.0, you can use Access Control Launch Pad to maintain key functionalities under GRC Access Control. It is a single web page that can be used for Risk Analysis and Remediation (RAR). In GRC Access Control, you can use Risk Analysis and Remediation (RAR) capability to perform security audit and segregation of duties (SoD) analysis. It is a tool which can be used to identify, analyze, and resolve risk and audit issues linked to the following regulatory compliance. Here, you can also colloaboratively define the following − Enterprise Role Management (ERM) Compliant User Provisioning (CUP) Superuser Privilege Management Follow these steps to create a new Launchpad in NWBC − Step 1 − Go to PFCG roles, and open the role SAP_GRAC_NWBC Step 2 − When you right click My Home item, you can see the application being called is grfn_service_map?WDCONFIGURATIONID=GRAC_FPM_AC_LPD_HOME and the configuration id is GRAC_FPM_AC_LPD_HOME. Step 3 − Select application config button and you can see the application configuration screen → display button. Step 4 − When you click on Display, you can see this screen − Step 5 − Now open the Component Configuration button. Step 6 − Click on Configure UIBB button in this screen. You will be directed to the following screen − Step 7 − You can select the Launchpad to which you want to map. If you want to create a new Launchpad, you can also map it to a new role. Step 8 − To create a new Launchpad, define the following − Create a new launchpad with menu items that you want. Create a new launchpad with menu items that you want. Create a new configuration of the application GRFN_SERVICE_MAP or you can copy configuration id GRAC_FPM_AC_LPD_HOME and customize it further. Create a new configuration of the application GRFN_SERVICE_MAP or you can copy configuration id GRAC_FPM_AC_LPD_HOME and customize it further. In the new configuration select the launchpad that you want to associate. In the new configuration select the launchpad that you want to associate. Create a new role and add webdynpro application GRFN_SERVICE_MAP to it with the custom configuration id created in the previous step. Create a new role and add webdynpro application GRFN_SERVICE_MAP to it with the custom configuration id created in the previous step. In SAP GRC 10.0 solution, the master data and organization structure is shared across access control, process control and risk management. Process Control also shares certain capabilities with risk management process. Following are the key features shared with Access Control − Access control and process control shares the compliance structure in below areas − In process control solution, controls are used as mitigation control in access control under SAP GRC 10.0 solution. Access control and process control share same organization. In process control, processes are used as business processes in access control. Process control and access control are integrated with access risk analysis to monitor segregation of duties SoD. Access control and process control shares the compliance structure in below areas − In process control solution, controls are used as mitigation control in access control under SAP GRC 10.0 solution. In process control solution, controls are used as mitigation control in access control under SAP GRC 10.0 solution. Access control and process control share same organization. Access control and process control share same organization. In process control, processes are used as business processes in access control. In process control, processes are used as business processes in access control. Process control and access control are integrated with access risk analysis to monitor segregation of duties SoD. Process control and access control are integrated with access risk analysis to monitor segregation of duties SoD. The menu areas common to both Process Control and Risk Management are − GRC Role Assignment Process Control Planner Risk Management Planner Central Delegation The following are the key integration points between Process Control and Risk Management − New control points can be purposed for Process Control in Risk Management. New control points can be purposed for Process Control in Risk Management. When a new control is proposed, Process Control needs to evaluate the request from Risk Management. When a new control is proposed, Process Control needs to evaluate the request from Risk Management. Risk Management uses results from Process Control to evaluate new controls. Risk Management uses results from Process Control to evaluate new controls. Risk Management can also use existing controls from Process Control as responses in Risk Management. Risk Management can also use existing controls from Process Control as responses in Risk Management. Internal Audit Management allows you to process the information from Risk Management and Process Control to use in audit planning. Audit proposal can be transferred to audit management for processing when required and audit items can be used to generate issues for reporting. IAM provides you a place where you can perform complete audit planning, create audit items, define audit universe and create and view audit reports and audit issues. Internal Audit Management Work Center provides a central location for the following activities − Define the audit universe for your organization Audit risk rating Audit planning to define procedure for audit compliance Audit issues from audit actions Audit reports to see what risks are there on auditable entities Audit Universe contains audit entities which can be classified as business units, lines of business or departments. Audit entities define the audit planning strategy and these can be linked to Process Control and Risk Management to find risks, controls, etc. Let us now understand how to create an auditable enity. Step 1 − Go to /nwbc option at the top to open Work Centers Step 2 − In SAP NetWeaver Business Client, go to IAM Work Center. Step 3 − Navigate to Internal Audit Management → Audit Universe Step 4 − Click on Create button and go to General tab. Step 5 − Enter the following details for auditable entity − Name Description Type Status Notes to add any additional information Step 6 − Go to Audit Plan tab to view audit proposals and audit plan proposals with the transfer date. Step 7 − Select the attachments and links tab to add any type of files or links. Step 8 − When you enter the required details, you can select from the following options − Select Save to save the entity. Select Close to exit without saving. Audit Risk rating is used to define the criteria for an organization to find risk rating and establish ranking for risk rating. Each auditable entity is rated as per management feedback in ARR. You can use ARR to perform the following functions − You can find the set of auditable entities and risk factors. You can find the set of auditable entities and risk factors. Define and evaluate risk scores for risk factor in each auditable entity. Define and evaluate risk scores for risk factor in each auditable entity. As per risk score, you can rate the auditable entity. As per risk score, you can rate the auditable entity. You can also generate an audit plan from ARR by comparing risk scores for different auditable entities. In addition to this, you can select the high risk score auditable entities and generate audit proposal and audit plan proposal. You can also generate an audit plan from ARR by comparing risk scores for different auditable entities. In addition to this, you can select the high risk score auditable entities and generate audit proposal and audit plan proposal. Let us now understand the steps to create an Audit Risk Rating Step 1 − In SAP NetWeaver Business Client, go to IAM Work Center. Step 2 − Navigate to Internal Audit Management → Audit Risk Rating → Create Step 3 − In General tab, enter the following details − Name Description Valid from Valid to Responsible person Status Step 4 − Go to Auditable Entities and click Add button to choose from auditable entities. Step 5 − Go to Risk Factor tab, and select ARR risk factor. Select Add to add a risk factor → OK. Step 6 − Go to Risk Scores tab, select entity and input risk scores on risk factor table. Click Calculate button to view average score. Go to Risk level and risk priority column to enter the details. Go to Audit Plan Proposal tab, to ensure that you are creating an audit plan proposal. Select export to create an excel spreadsheet to view information in table form for your ARR. Select Save button to save audit risk rating for auditable entity. Work centers provide a central access point for the entire GRC functionality. They are organized to provide easy access to application activities, and contain menu groups and links to further activities. The following work centers are shared by Access Control, Process Control and Risk Management − My Home Master Data Rule Setup Assessments Access Management Reports and Analytics Let us discuss the major work centers. My Home Work Center is shared by Process Control, Risk management and Access Control. This provides a centralized location where you can manage assigned tasks and accessible objects in GRC application. My Home comes with a number of sections. Let us now understand the Work Inbox section − Using Work Inbox, you can view the tasks that you have to process in GRC software. If you want to process a task, click on task in the table. It will open the workflow window wherein, you can process the task. Master Data Work Center is shared by Process Control, Risk management and access control. The Process Control Master Data Work center contains the following sections − Organizations Regulations and Policies Objectives Activities and Processes Risks and Responses Accounts Reports Let us now discuss the major work centers under Master Data Work Center − Organizations − Maintain the company's organization structure for compliance and risk management with related assignments Mitigation Controls − Maintain controls to mitigate segregation of duty, critical action and critical permission access violations To create mitigation control, click Create button. You will be directed to a new window, enter the details for mitigation control and click Save button. Reports and Analytics Work Center is shared by Process Control, Risk management and Access Control. The Process Control Reports and Analytics Work Center consists of Compliance section in GRC application. In compliance section, you can create the following reports under Process Control − Shows a high-level picture of the overall status of corporate compliance throughout different business entities and provides analytics and drilldown capabilities to view data on different levels and dimensions. Displays the results of surveys. Provides comprehensive information on master data, evaluation, and remediation activities for subprocesses and controls. The following roles that use the datasheet functionality − Internal Auditors − They can use datasheets to get a picture of the controls and subprocesses in an organization under GRC. Internal Auditors − They can use datasheets to get a picture of the controls and subprocesses in an organization under GRC. Process Owners − In GRC application, Process Owners and Control Owners can request datasheets to get an overview of their subprocesses. Datasheet information provides the definition of the subprocess, assessments completed on subprocess, controls encompassed by the subprocess, and the assessments and testing done on these controls. Process Owners − In GRC application, Process Owners and Control Owners can request datasheets to get an overview of their subprocesses. Datasheet information provides the definition of the subprocess, assessments completed on subprocess, controls encompassed by the subprocess, and the assessments and testing done on these controls. Control Owners − Control owners can use datasheets to check the design of their controls. Control owner can assess controls to check the controls and their effectiveness. Control Owners − Control owners can use datasheets to check the design of their controls. Control owner can assess controls to check the controls and their effectiveness. External Auditors − Datasheets can be used by external auditors; this can be used to request the information to research controls or subprocesses. External Auditors − Datasheets can be used by external auditors; this can be used to request the information to research controls or subprocesses. Note − Other work centers like access management, assessments and rule set up are also share by process control, access control and risk management. The Process Control Access Management Work Center has the GRC Role Assignments section. In every business, it is required to perform Segregation of Duties (SoD) Risk Management - starting from risk recognition to rule building validation and various other risk management activities to follow continuous compliance. As per different roles, there is a need to perform Segregation of Duties in GRC system. SAP GRC defines various roles and responsibilities under SoD Risk Management − Business Process Owners perform the following tasks − Identify risks and approve risks for monitoring Approve remediation involving user access Design controls to mitigate conflicts Communicate access assignments or role changes Perform proactive continuous compliance Senior Officers perform the following tasks − Approve or reject risks between business areas Approve mitigation controls for selected risks Security Administrators perform the following tasks − Assume ownership of GRC tools and security process Design and maintain rules to identify risk conditions Customize GRC roles to enforce roles and responsibilities Analyze and remediate SoD conflicts at role level Auditors perform the following tasks − Risk assessment on a regular basis Provide specific requirements for audit purposes Periodic testing of rules and mitigation controls Act as liaison between external auditors SoD Rule Keeper performs the following tasks − GRC tool configuration and administration Maintains controls over rules to ensure integrity Acts as liaison bet ween basis and GRC support center SAP Risk Management in GRC is used to manage risk-adjusted management of enterprise performance that empowers an organization to optimize efficiency, increase effectiveness, and maximize visibility across risk initiatives. The following are the key functions under Risk Management − Risk management emphasizes on organizational alignment towards top risks, associated thresholds, and risk mitigation. Risk management emphasizes on organizational alignment towards top risks, associated thresholds, and risk mitigation. Risk analysis includes performing qualitative and quantitative analysis. Risk analysis includes performing qualitative and quantitative analysis. Risk management involves Identification of key risks in an organization. Risk management involves Identification of key risks in an organization. Risk management also includes resolution/remediation strategies for risks. Risk management also includes resolution/remediation strategies for risks. Risk management performs the alignment of key risk and performance indicators across all business functions permitting earlier risk identification and dynamic risk mitigation. Risk management performs the alignment of key risk and performance indicators across all business functions permitting earlier risk identification and dynamic risk mitigation. Risk management also involves proactive monitoring into existing business processes and strategies. Let us now discuss the various phases in Risk Management. The following are the various phases in risk management − Risk Recognition Rule Building and Validation Analysis Remediation Mitigation Continuous Compliance In a risk recognition process under risk management, the following steps can be performed − Identify authorization risks and approve exceptions Clarify and classify risk as high, medium or low Identify new risks and conditions for monitoring in the future Perform the following tasks under Rule Building and Validation − Reference the best practices rules for environment Validate the rules Customize rules and test Verify against test user and role cases Perform the following tasks under Analysis − Run the analytical reports Estimate cleanup efforts Analyze roles and users Modify rules based on analysis Set alerts to distinguish executed risks From the management aspect, you can see compact view of risk violations that are grouped by severity and time. Step 1 − Go to Virsa Compliance Calibrator → Informer tab Step 2 − For SoD violations, you can display a pie chart and a bar chart to represent current and past violations in the system landscape. The following are the two different views to these violations − Violations by risk level Violations by process Perform the following tasks under remediation − Determine alternatives for eliminating risks Present analysis and select corrective actions Document approval of corrective actions Modify or create roles or user assignments Perform the following tasks under mitigation − Determine alternative controls to mitigate risk Educate management about conflict approval and monitoring Document a process to monitor mitigation controls Implement controls Perform the following tasks under Continuous Compliance − Communicate changes in roles and user assignments Simulate changes to roles and users Implement alerts to monitor for selected risks and mitigate control testing Risks should be classified as per the company policy. The following are the various risk classifications that you can define as per risk priority and company policy − Critical classification is done for risks that contain company’s critical assets that are very likely to be compromised by fraud or system disruptions. This includes physical or monetary loss or system-wide disruption that includes fraud, loss of any asset or failure of a system. This includes multiple system disruption like overwriting master data in the system. This includes risk where the productivity losses or system failures compromised by fraud or system disruptions and loss is minimum. In SAP GRC 10.0 Risk Management, risk remediation phase determines the method to eliminate risks in roles. The purpose of the remediation phase is to determine alternatives for eliminating issues under risk management. The following approaches are recommended to resolve issues in roles − You can start with single roles as it is easy and simplest way to start. You can start with single roles as it is easy and simplest way to start. You can check for any Segregation of Duties SoD violations from being reintroduced. You can check for any Segregation of Duties SoD violations from being reintroduced. You can perform various analysis to check the user assignment on the assignment or removal of user actions. You can perform various analysis to check the user assignment on the assignment or removal of user actions. You can use Management view or Risk Analysis reports for analysis as mentioned in previous topic. You can use Management view or Risk Analysis reports for analysis as mentioned in previous topic. In Risk Remediation, Security Administrators should document the plan and Business Process Owners should be involved and approve the plan. You can generate different Risk Analysis reports as per the required analysis − Action Level − You can use it to perform SoD analysis at action level. Action Level − You can use it to perform SoD analysis at action level. Permission Level − This can be used to perform SoD analysis at action and permission levels. Permission Level − This can be used to perform SoD analysis at action and permission levels. Critical Actions − This can be used to analyze the users who have access to one of the critical functions. Critical Actions − This can be used to analyze the users who have access to one of the critical functions. Critical Permissions − This can be used to analyze users having access to one critical function. Critical Permissions − This can be used to analyze users having access to one critical function. Critical Roles/Profiles − This can be used to analyze the users who has access to critical roles or profiles. Critical Roles/Profiles − This can be used to analyze the users who has access to critical roles or profiles. In SAP GRC 10.0, you can use mitigation controls when it is not possible to separate Segregation of duties SoD from the business process. In an organization, consider a scenario where a person takes care of roles within business processes that cause a missing SoD conflict. There are different examples that are possible for mitigation controls − Release strategies and authorization limits Review of user logs Review of exception reports Detailed variance analysis Establish insurance to cover impact of a security incident There are two types of mitigation control under SAP GRC Risk management − Preventive Detective Preventive mitigation control is used to reduce the impact of risk before it actually occurs. There are various activities that you can perform under preventive mitigation control − Configuration User Exits Security Defining workflow Custom Objects Detective mitigation control is used when an alert is received and a risk occurs. In this case, the person who is responsible to initiate corrective measure mitigates the risk. There are various activities that you can perform under detective mitigation control − Activity Reports Comparison of plan vs actual review Budget review Alerts Follow these steps to set up migration controls − Step 1 − Login to SAP GRC Access control. Step 2 − Perform a risk analysis on user level. Enter the below details − Report Type Report Format Step 3 − Click Execute Step 4 − You can toggle between different report types as in the following screenshot − Step 5 − Logon to SAP GRC Access Control and schedule a risk analysis background job on role level. Enter the following details − Report Type − Permission Level Report Format − Summary Step 6 − Click Run in Background as shown in the following screenshot − Step 7 − In the next window, you can select Start Immediately. Then, click OK. In SAP GRC 10.0, Superuser Privilege Management needs to be implemented in your organization to eliminate the excessive authorizations and risks that your company experiences with the current emergency user approach. The following are the key features in Superuser Privilege − You can allow Superuser to perform emergency activities within a controlled and auditable environment You can allow Superuser to perform emergency activities within a controlled and auditable environment Using Superuser, you can report all the user activities accessing higher authorization privileges. Using Superuser, you can report all the user activities accessing higher authorization privileges. You can generate an audit trail, which can be used to document reasons for using higher access privileges. You can generate an audit trail, which can be used to document reasons for using higher access privileges. This audit trail can be used for SOX compliance. This audit trail can be used for SOX compliance. Superuser can act as firefighter and have the following additional capabilities − It can be used to perform tasks outside of their normal role or profile in an emergency situation. Only certain individuals (owners) can assign Firefighter IDs. It provides an extended capability to users while creating an auditing layer to monitor and record usage. Superuser can act as firefighter and have the following additional capabilities − It can be used to perform tasks outside of their normal role or profile in an emergency situation. It can be used to perform tasks outside of their normal role or profile in an emergency situation. Only certain individuals (owners) can assign Firefighter IDs. Only certain individuals (owners) can assign Firefighter IDs. It provides an extended capability to users while creating an auditing layer to monitor and record usage. It provides an extended capability to users while creating an auditing layer to monitor and record usage. You can use the following standard roles for Superuser Privilege Management − This has the Ability to configure Firefighter Assign Firefighter role owners and controllers to Firefighter IDs Run Reports Assign Firefighter IDs to Firefighter users Upload, download, and view Firefighter history log Access the firefighter program Let us now understand how to implement Superuser. You can implement firefighter IDs by working on the following steps − Step 1 − Create Firefighter IDs for each business process area Step 2 − Assign necessary roles and profiles to carry firefighting tasks. You shouldn’t assign profile SAP_ALL Step 3 − Use T-Code – SU01 Step 4 − Click Create button to create a new user. Step 5 − Assign Firefighter roles as mentioned above to user id − Assign Firefighter roles to applicable user IDs. Assign Firefighter roles to applicable user IDs. Assign administrator role /VIRSA/Z_VFAT_ADMINISTRATOR to superuser privilege management administrator. Assign administrator role /VIRSA/Z_VFAT_ADMINISTRATOR to superuser privilege management administrator. Administrator user should not be assigned any firefighting Administrator user should not be assigned any firefighting Assign the standard role /VIRSA/ Z_VFAT_FIREFIGHTER to − Firefighter ID − Service user used for logon Firefighter user − Standard user acting as a Firefighter in case Assign the standard role /VIRSA/ Z_VFAT_FIREFIGHTER to − Firefighter ID − Service user used for logon Firefighter user − Standard user acting as a Firefighter in case Assign the ID owner role /VIRSA/Z_VFAT_ID_OWNER to − Owner − Responsible for determining who will be assigned to Controller − Receives notification when the Firefighter ID is responsibilities of emergency Firefighter IDs for his or her business area used. Assign the ID owner role /VIRSA/Z_VFAT_ID_OWNER to − Owner − Responsible for determining who will be assigned to Owner − Responsible for determining who will be assigned to Controller − Receives notification when the Firefighter ID is responsibilities of emergency Firefighter IDs for his or her business area used. Controller − Receives notification when the Firefighter ID is responsibilities of emergency Firefighter IDs for his or her business area used. Step 6 − Go to Roles tab and select the mentioned roles as per the requirement. Step 7 − Create RFC destination for internal switch to Firefighter ID − Name − Enter RFC connection name Name − Enter RFC connection name Connection Type − 3 Connection Type − 3 Enter a Description (No username, passwords, or other logon data are required) Enter a Description (No username, passwords, or other logon data are required) Enter passwords for each Firefighter ID in the Security table: Passwords are stored as hash values and are unreadable after the administrator saves the value. Enter passwords for each Firefighter ID in the Security table: Passwords are stored as hash values and are unreadable after the administrator saves the value. Step 8 − To create firefighter log, you can schedule a background job. Name the job /VIRSA/ZVFATBAK as in the following screenshot − Let us understand these steps for Superuser Log. Step 1 − Use T-Code − Transaction − /n/VIRSA/ZVFAT_V01 Step 2 − You can now find the logs in the toolbox area. Step 3 − You can use transaction code — SM37 to review the logs for individual user. You can also use the web GUI to access all Firefighter information. Go to SAP GRC Access control → Superuser privilege management. So it is possible to access the data of different Firefighter installations on different SAP backend systems. And it is not necessary to log on to each system anymore. You can implement enhanced risk analysis using organization rules. In shared service business units, you can use organization rules to achieve procedures for risk analysis and management of user groups. Consider a case where a user has created a fictitious vendor and invoices have been generated to gain financial benefit. You can create an organization rule with company code enabled to eliminate this scenario. Following steps should be performed to prevent this situation − Enable organization level fields in functions Create org rules Update org user mapping table Configure risk analysis web service Follow these steps to enable organization level fields in functions − Find out functions to be segregated by organization level in shared service environment. Find out functions to be segregated by organization level in shared service environment. Maintain permissions for affected transactions. Maintain permissions for affected transactions. Follow these steps to create organization rules − Step 1 − Create organization rules for every possible value of organization field. Step 2 − Go to rule architect → Organization level → Create Step 3 − Enter the organization rule ID field. Step 4 − Enter the related task. Step 5 − Define organization level field and combine them with Boolean operators. Step 6 − Click Save button to save the Organization rule. Let us now understand th benefits of using organization rules. You can use organizational rules for companies to implement following features − You can use organization rules to implement shared services. They segregate duties with the help of organizational restrictions. You can use organization rules to implement shared services. They segregate duties with the help of organizational restrictions. Go to Risk Analysis → Org Level Go to Risk Analysis → Org Level Perform a risk analysis of analysis type Org Rule against a user Perform a risk analysis of analysis type Org Rule against a user You will receive the following output − The risk analysis will only show a risk if the user has access to the same specific company code in each of the conflicting functions. You will receive the following output − The risk analysis will only show a risk if the user has access to the same specific company code in each of the conflicting functions. The risk analysis will only show a risk if the user has access to the same specific company code in each of the conflicting functions. In an organization, you have control owners at different organization hierarchy levels. Risk should be managed and mitigated as per level of access. The following are the control owners in an organization − One control owner for global level Different control owners for regional levels Multiple control owners for local level You have to assign mitigation controls to different levels of responsibility. Now if there is a risk violation at region and local level, you should perform risk mitigation at highest level. To use mitigation control at organization hierarchy, let us say you have performed risk analysis at organization level and the user violates all child organization rules and meets the condition of parent rule and only parent rule shows up; you can perform risk mitigation in the following ways − Mitigation on user level Mitigation on organization level In SAO GRC 10.0, a workflow is triggered in the following situations − To create or update risks. To create or update mitigation controls. To assign mitigation controls. As you follow workflow-based change management approach in risk analysis and remediation, you have to perform the following steps − Go to Configuration tab → workflow options Set the below parameters − Set parameter Risk Maintenance to YES Set parameter Mitigation Control Maintenance to YES Set parameter Mitigation to YES Set up the Workflow Web Service URL − http://<server>:<port>/AEWFRequestSubmissionService_5_2/Config1?wsdl&style=document Customize the workflows need to be performed inside the Workflow Engine. When you maintain a risk or a control is in SAP GRC, you perform the following steps − Step 1 − In Access Control, a workflow is triggered to perform a risk or a control workflow. Step 2 − When you get the required approvals, approval steps depend on customer requirement. Step 3 − Get an audit trail documenting the complete approval process. Using SAP GRC Global Trade Services, you can improve cross-border supply chain of goods in an organization. This application allows you to automate the trade processes and helps you to control the cost and reduce the risk of penalties and also to manage inbound and outbound processes. Using GTS, you can create centralize single repository that is used to contain all compliance master data and content. The following are the key advantages of using Global Trade Services − It helps in reducing the cost and effort of managing compliance for global trading. It helps in reducing the cost and effort of managing compliance for global trading. It can ease time-consuming manual tasks and helps in improving productivity. It can ease time-consuming manual tasks and helps in improving productivity. Reduces the penalties for trade compliance violations. Reduces the penalties for trade compliance violations. It helps you to create and improve the brand and image and avoid trade with sanctioned or denied parties. It helps you to create and improve the brand and image and avoid trade with sanctioned or denied parties. Paves way for customer satisfaction and improves the quality of service. Paves way for customer satisfaction and improves the quality of service. It fastens the inbound and outbound processes by performing customs clearance and also helps in removing unnecessary delays. It fastens the inbound and outbound processes by performing customs clearance and also helps in removing unnecessary delays. The following illustration shows the process flow of integration between SAP ERP and SAP Global Trade Services − When you install SAP GRC, there are various configuration and settings that you need to perform in GRC. The key activities include − Creating connectors in GRC Creating connectors in GRC Configuring AMF to use the connectors Configuring AMF to use the connectors Creating callback connectors Creating callback connectors Creating connections in GRC is standard process of creating RFC connection using T-Code − SM59 Creating connections in GRC is standard process of creating RFC connection using T-Code − SM59 SAP GRC is available in SAP Easy Access → under Governance Risk Compliance folder. Step 1 − Open SAP Easy access menu and use T-Code − SPRO Step 2 − Go to Governance, Risk and Compliance under SAP Reference IMG → Common Component Settings → Integration Framework → Create Connectors Step 3 − Create connector is shortcut for creating SM59 connection. Step 4 − To see existing connections, go to Maintain Connectors and Connection Types − You can see connector types as shown below. These connector types can be used for configuration for different purposes − Local system connectors are used to integrate with the SAP BusinessObjects Access Control application for monitoring segregation of duty violations Local system connectors are used to integrate with the SAP BusinessObjects Access Control application for monitoring segregation of duty violations Web service connectors are used for external partner data sources (see section) Web service connectors are used for external partner data sources (see section) SAP system connectors are used in all other cases. SAP system connectors are used in all other cases. Step 5 − Go to Connection Type Definition tab − Step 6 − Define which of the connectors previously defined in SM59 can be used in monitoring. Go to define Connectors Step 7 − In the screen you can see a connector name — SMEA5_100. This is a connector which shows a connector to an ECC system. The third column that lists the name of a connector which is defined in the monitored system, and which is configured to point back to the GRC system being configured here. SMEA5_100 is another connector in the GRC system and it points to an ERP system which is to be monitored. SM2 is a connector on the ECC system and it points back to GRC system. Step 8 − Define Connector Group Screen on the left side. Step 9 − Here you have to ensure that all the connector configurations for automated monitoring should belong to the configuration group called Automated Monitoring as shown above under define automated monitoring connector group. Step 10 − Go to assign connectors to connector group on the left side. Step 11 − Assign the connector to AM connector group as mentioned in the above screenshot. Step 12 − Go to Maintain Connection Settings in main menu as in the following screenshot. Step 13 − You need to enter the integration scenario you want, enter AM as in the following screenshot − Step 14 − Click on the green tick mark as shown in the above screenshot; you will be directed to the following screen with nine sub-scenarios. The highlighted box shows nine entries called sub-scenarios and they represent the different types of data sources and business rules supported under Process Control 10. Step 15 − For the System to be monitored, you need to link the corresponding connector to that sub-scenario. Step 16 − Select the sub-scenario you want configurable and then choose Scenario Connector Link in the left side as shown below − Step 17 − You will be directed to the following screen − Step 18 − Now the connector you want to use for that scenario is not already in the list for that sub-scenario, You can click on New Entries button at the top to add it. You can follow these recommendations to add subscenarios − ABAP Applications − ABAP report, SAP query, configurable program SAP BW − BW query Non SAP System − External Partner Process Integrator − PI GRC System − SoD integration ABAP Applications − ABAP report, SAP query, configurable program SAP BW − BW query Non SAP System − External Partner Process Integrator − PI GRC System − SoD integration In SAP GRC Process Control, you can create data sources. Here, the design time user interfaces are under Rule Setup option in Business client. Go to continuous monitoring section where you can find Data Sources and Business Rules option. To create a new Data Source, click on Data Sources → Create. In the next field, you can see three different tabs to define the data source. General Tab Object Field Link and Attachment In General tab, enter the following details − Name of data source Start date of the validity period End date of the validity period Status Go to Object Field tab, select the following fields − In SAP GRC 10.0, you can use Business Rules to filter the data stream that is coming from the data sources and you can apply the user configured conditions/calculations against that data to determine if there is a problem which requires attention. The Business Rule type purely depends on the Data Source type. Go to Business Rules under Rule Setup. To create new business rules, there is a list of steps that you need to follow with few of the Data Source types. You need to define details in each tab. For example, in the General tab, you need to enter the basic information about business rule. Business rule gives you data to filter the deficiencies. In Data for Analysis tab, you will see a list of available fields. Go to filter criterial to pass the filter condition on available objects. You can select from different operators. When you define all the steps, you have an option to save the rule. If you want to apply the rule to Process Control, you can do by clicking Apply button. To assign business rule to a process control, go to Business rule assignment under Continuous Monitoring in Rule Setup. Select the control and search for the Business rule to apply. We have now understood how to create Data Sources and Business Rules to apply filter on Data Sources and how to assign business rules to process controls.
[ { "code": null, "e": 2749, "s": 2402, "text": "SAP Governance, Risk and Compliance solution enables organizations to manage regulations and compliance and remove any risk in managing organizations’ key operations. As per changing market situation, organizations are growing and rapidly changing and inappropriate documents, spreadsheets are not acceptable for external auditors and regulators." }, { "code": null, "e": 2858, "s": 2749, "text": "SAP GRC helps organization to manage their regulations and compliance and perform the following activities −" }, { "code": null, "e": 2950, "s": 2858, "text": "Easy integration of GRC activities into existing process and automating key GRC activities." }, { "code": null, "e": 3042, "s": 2950, "text": "Easy integration of GRC activities into existing process and automating key GRC activities." }, { "code": null, "e": 3088, "s": 3042, "text": "Low complexity and managing risk efficiently." }, { "code": null, "e": 3134, "s": 3088, "text": "Low complexity and managing risk efficiently." }, { "code": null, "e": 3170, "s": 3134, "text": "Improve risk management activities." }, { "code": null, "e": 3206, "s": 3170, "text": "Improve risk management activities." }, { "code": null, "e": 3277, "s": 3206, "text": "Managing fraud in business processed and audit management effectively." }, { "code": null, "e": 3348, "s": 3277, "text": "Managing fraud in business processed and audit management effectively." }, { "code": null, "e": 3417, "s": 3348, "text": "Organizations perform better and companies can protect their values." }, { "code": null, "e": 3486, "s": 3417, "text": "Organizations perform better and companies can protect their values." }, { "code": null, "e": 3562, "s": 3486, "text": "SAP GRC solution consists of three main areas: Analyze, manage and monitor." }, { "code": null, "e": 3638, "s": 3562, "text": "SAP GRC solution consists of three main areas: Analyze, manage and monitor." }, { "code": null, "e": 3695, "s": 3638, "text": "Let us now understand the different modules in SAP GRC −" }, { "code": null, "e": 3974, "s": 3695, "text": "To mitigate risk in an organization, it is required to perform risk control as part of compliance and regulation practice. Responsibilities should be clearly defined, managing role provisioning and managing access for super user is critical for managing risk in an organization." }, { "code": null, "e": 4333, "s": 3974, "text": "SAP GRC Process Control software solution is used for managing compliance and policy management. The compliance management capabilities allow organizations to manage and monitor their internal control environments. Organizations can proactively fix any identified issues and certify and report on the overall state of the corresponding compliance activities." }, { "code": null, "e": 4688, "s": 4333, "text": "SAP Process control supports the complete life cycle of policy management, including the distribution and adherence of policies by target groups. These policies help organizations to reduce the cost of compliance and improve management transparency and enables organization to develop compliance management processes and policies in business environment." }, { "code": null, "e": 4937, "s": 4688, "text": "SAP GRC Risk Management allows you to manage risk management activities. You can do advance planning to identify risk in business and implement measures to manage risk and allow you to make better decision that improves the performance of business." }, { "code": null, "e": 4964, "s": 4937, "text": "Risks come in many forms −" }, { "code": null, "e": 4981, "s": 4964, "text": "Operational Risk" }, { "code": null, "e": 4996, "s": 4981, "text": "Strategic Risk" }, { "code": null, "e": 5012, "s": 4996, "text": "Compliance Risk" }, { "code": null, "e": 5027, "s": 5012, "text": "Financial Risk" }, { "code": null, "e": 5335, "s": 5027, "text": "This is used to improve the audit management process in an organization by documenting artifacts, organizing work papers, and creating audit reports. You can easily integrate with other governance, risk and compliance solution and enable organizations to align audit management policies with business goals." }, { "code": null, "e": 5440, "s": 5335, "text": "SAP GRC audit management helps auditor in making things simple by providing the following capabilities −" }, { "code": null, "e": 5566, "s": 5440, "text": "You can instantly capture the artifacts for audit management and other evidences using mobile capabilities drag-drop feature." }, { "code": null, "e": 5692, "s": 5566, "text": "You can instantly capture the artifacts for audit management and other evidences using mobile capabilities drag-drop feature." }, { "code": null, "e": 5784, "s": 5692, "text": "You can easily create, track, and manage audit issues with global monitoring and follow up." }, { "code": null, "e": 5876, "s": 5784, "text": "You can easily create, track, and manage audit issues with global monitoring and follow up." }, { "code": null, "e": 5993, "s": 5876, "text": "You can perform search using search capabilities that allows to get more information from legacy and working papers." }, { "code": null, "e": 6110, "s": 5993, "text": "You can perform search using search capabilities that allows to get more information from legacy and working papers." }, { "code": null, "e": 6190, "s": 6110, "text": "You can engage auditors with a user-friendly interface and collaboration tools." }, { "code": null, "e": 6270, "s": 6190, "text": "You can engage auditors with a user-friendly interface and collaboration tools." }, { "code": null, "e": 6423, "s": 6270, "text": "Easy integration of audit management with SAP Fraud Management, SAP Risk Management, and SAP Process Control to align audit process with business goals." }, { "code": null, "e": 6576, "s": 6423, "text": "Easy integration of audit management with SAP Fraud Management, SAP Risk Management, and SAP Process Control to align audit process with business goals." }, { "code": null, "e": 6634, "s": 6576, "text": "Quick resolution of issues using automated tracking tool." }, { "code": null, "e": 6692, "s": 6634, "text": "Quick resolution of issues using automated tracking tool." }, { "code": null, "e": 6821, "s": 6692, "text": "Enhance the staff utilization, and less travel costs resulted from internal audit planning, resource management, and scheduling." }, { "code": null, "e": 6950, "s": 6821, "text": "Enhance the staff utilization, and less travel costs resulted from internal audit planning, resource management, and scheduling." }, { "code": null, "e": 7095, "s": 6950, "text": "Easy integration with SAP Business Objects reporting and data visualization tool to visualize audit reports using Lumira and other BI reporting." }, { "code": null, "e": 7240, "s": 7095, "text": "Easy integration with SAP Business Objects reporting and data visualization tool to visualize audit reports using Lumira and other BI reporting." }, { "code": null, "e": 7327, "s": 7240, "text": "Use of pre-established templates to standardize audit artifacts and reporting process." }, { "code": null, "e": 7414, "s": 7327, "text": "Use of pre-established templates to standardize audit artifacts and reporting process." }, { "code": null, "e": 7685, "s": 7414, "text": "SAP GRC fraud management tool helps organizations to detect and prevent frauds at early stage and hence reducing minimizing the business loss. Scans can be performed on huge amount of data in real time with more accuracy and fraudent activities can be easily identified." }, { "code": null, "e": 7768, "s": 7685, "text": "SAP fraud management software can help organizations with following capabilities −" }, { "code": null, "e": 7821, "s": 7768, "text": "Easy investigation and documentation of fraud cases." }, { "code": null, "e": 7874, "s": 7821, "text": "Easy investigation and documentation of fraud cases." }, { "code": null, "e": 7987, "s": 7874, "text": "Increase the system alert and responsiveness to prevent fraudent activities to happen more frequently in future." }, { "code": null, "e": 8100, "s": 7987, "text": "Increase the system alert and responsiveness to prevent fraudent activities to happen more frequently in future." }, { "code": null, "e": 8165, "s": 8100, "text": "Easy scanning of high volumes of transactions and business data." }, { "code": null, "e": 8230, "s": 8165, "text": "Easy scanning of high volumes of transactions and business data." }, { "code": null, "e": 8442, "s": 8230, "text": "SAP GRC GTS software helps organizations to enhance cross border supply within limits of international trade management. It helps in reducing the penalty of risks from International Trade Regulation authorities." }, { "code": null, "e": 8606, "s": 8442, "text": "It provides centralize global trade management process with a single repository for all compliance master data and content irrespective of size of an organization." }, { "code": null, "e": 8706, "s": 8606, "text": "SAP BusinessObjects GRC solution consists of three main capabilities − Analyze, Manage and Monitor." }, { "code": null, "e": 8958, "s": 8706, "text": "In the following diagram, you can see the SAP GRC Capability Model that covers all the key features of SAP GRC software. Using GRC, organizations can check for all potential risks and compliance findings and can take correct decision to mitigate them." }, { "code": null, "e": 9323, "s": 8958, "text": "In older versions of SAP GRC, to use access control, process control and risk management, there was a separate navigation for each component. This means that users, to perform cross component duties, had to login to each module separately and login multiple times. This resulted in a tough process to manage multiple windows and documents to search was also tough." }, { "code": null, "e": 9516, "s": 9323, "text": "SAP GRC 10.0 provides direct navigation to access control, process control and risk management components for a single user as per authorization and removes the management of multiple windows." }, { "code": null, "e": 9653, "s": 9516, "text": "Step 1 − To perform customizing activities and maintain configuration settings for GRC solution, go to T-code − SPRO → SAP Reference IMG" }, { "code": null, "e": 9708, "s": 9653, "text": "Step 2 − Expand Governance, Risk and Compliance node −" }, { "code": null, "e": 9754, "s": 9708, "text": "Step 3 − Logon to NetWeaver Business Client −" }, { "code": null, "e": 9803, "s": 9754, "text": "Run the transaction for NWBC in SAP Easy access." }, { "code": null, "e": 9945, "s": 9803, "text": "It will open NetWeaver Business Client screen and you will receive the following url − \nhttp://ep5crgrc.renterpserver.com:8070/nwbc/~launch/" }, { "code": null, "e": 10097, "s": 9945, "text": "You can use Work Centers to provide a central access point for GRC 10.0. They can be organized based on what the customer has been licensed to operate." }, { "code": null, "e": 10233, "s": 10097, "text": "Step 1 − To access Work Centers, open NetWeaver Business Client as mentioned above. Go to /nwbc option at the top to open Work Centers." }, { "code": null, "e": 10332, "s": 10233, "text": "Step 2 − Once you click, you will be directed to the home screen of SAP NetWeaver Business client." }, { "code": null, "e": 10492, "s": 10332, "text": "Depending on the products that you have licensed, different components of the GRC solution are displayed − Access Control, Process Control, or Risk Management." }, { "code": null, "e": 10904, "s": 10492, "text": "SAP GRC access control helps organizations to automatically detect, manage and prevent access risk violations and reduce unauthorized access to company data and information. Users can use automatic self-service to access request submission, workflow driven access request and approvals of access. Automatic reviews of user access, role authorization and risk violations can be used using SAP GRC Access Control." }, { "code": null, "e": 11166, "s": 10904, "text": "SAP GRC Access Control handles key challenges by allowing business to manage access risk. It helps organizations to prevent unauthorized access by defining segregation of duties SoD and critical access and minimizing the time and cost of access risk management." }, { "code": null, "e": 11229, "s": 11166, "text": "The following are the key features of SAP GRC Access Control −" }, { "code": null, "e": 11351, "s": 11229, "text": "To perform audit and compliance as per legal requirements with different audit standards like SOX, BSI and ISO standards." }, { "code": null, "e": 11473, "s": 11351, "text": "To perform audit and compliance as per legal requirements with different audit standards like SOX, BSI and ISO standards." }, { "code": null, "e": 11571, "s": 11473, "text": "To automatically detect access risk violations across SAP and non-SAP systems in an organization." }, { "code": null, "e": 11669, "s": 11571, "text": "To automatically detect access risk violations across SAP and non-SAP systems in an organization." }, { "code": null, "e": 11799, "s": 11669, "text": "As mentioned, it empowers users with self-service access submission, workflowdriven access requests and approvals of the request." }, { "code": null, "e": 11929, "s": 11799, "text": "As mentioned, it empowers users with self-service access submission, workflowdriven access requests and approvals of the request." }, { "code": null, "e": 12068, "s": 11929, "text": "To automate reviews of user access, role authorizations, risk violations, and control assignments in a small and large scale organization." }, { "code": null, "e": 12207, "s": 12068, "text": "To automate reviews of user access, role authorizations, risk violations, and control assignments in a small and large scale organization." }, { "code": null, "e": 12355, "s": 12207, "text": "To efficiently manage the super-user access and avoiding risk violations and unauthorized access to data and application in SAP and non-SAP system." }, { "code": null, "e": 12503, "s": 12355, "text": "To efficiently manage the super-user access and avoiding risk violations and unauthorized access to data and application in SAP and non-SAP system." }, { "code": null, "e": 12552, "s": 12503, "text": "Run the transaction for NWBC in SAP Easy access." }, { "code": null, "e": 12694, "s": 12552, "text": "It will open NetWeaver Business Client screen and you will receive the following url − \nhttp://ep5crgrc.renterpserver.com:8070/nwbc/~launch/" }, { "code": null, "e": 12830, "s": 12694, "text": "Step 1 − To access Work Centers, open NetWeaver Business Client as mentioned above. Go to /nwbc option at the top to open Work Centers." }, { "code": null, "e": 12929, "s": 12830, "text": "Step 2 − Once you click, you will be directed to the home screen of SAP NetWeaver Business client." }, { "code": null, "e": 13060, "s": 12929, "text": "Step 3 − Go to setup work center and explore the work set. Click some of the links under each one and explore the various screens." }, { "code": null, "e": 13169, "s": 13060, "text": "Step 4 − The Setup work center is available in Access Control and provides links to the following sections −" }, { "code": null, "e": 13193, "s": 13169, "text": "Access Rule Maintenance" }, { "code": null, "e": 13216, "s": 13193, "text": "Exception Access Rules" }, { "code": null, "e": 13238, "s": 13216, "text": "Critical Access Rules" }, { "code": null, "e": 13254, "s": 13238, "text": "Generated Rules" }, { "code": null, "e": 13268, "s": 13254, "text": "Organizations" }, { "code": null, "e": 13288, "s": 13268, "text": "Mitigating Controls" }, { "code": null, "e": 13309, "s": 13288, "text": "Superuser Assignment" }, { "code": null, "e": 13331, "s": 13309, "text": "Superuser Maintenance" }, { "code": null, "e": 13345, "s": 13331, "text": "Access Owners" }, { "code": null, "e": 13417, "s": 13345, "text": "Step 5 − You can use the above listed functions in the following ways −" }, { "code": null, "e": 13557, "s": 13417, "text": "Using Access Rule Maintenance section, you can manage access rule sets, functions, and the access risks used to identify access violations." }, { "code": null, "e": 13697, "s": 13557, "text": "Using Access Rule Maintenance section, you can manage access rule sets, functions, and the access risks used to identify access violations." }, { "code": null, "e": 13778, "s": 13697, "text": "Using Exception Access Rules, you can manage rules that supplement access rules." }, { "code": null, "e": 13859, "s": 13778, "text": "Using Exception Access Rules, you can manage rules that supplement access rules." }, { "code": null, "e": 13981, "s": 13859, "text": "Using critical access rules section, you can define additional rules that identify access to critical roles and profiles." }, { "code": null, "e": 14103, "s": 13981, "text": "Using critical access rules section, you can define additional rules that identify access to critical roles and profiles." }, { "code": null, "e": 14180, "s": 14103, "text": "Using generated rules section, you can find and view generated access rules." }, { "code": null, "e": 14257, "s": 14180, "text": "Using generated rules section, you can find and view generated access rules." }, { "code": null, "e": 14393, "s": 14257, "text": "Under Organizations, you can maintain the company's organization structure for compliance and risk management with related assignments." }, { "code": null, "e": 14529, "s": 14393, "text": "Under Organizations, you can maintain the company's organization structure for compliance and risk management with related assignments." }, { "code": null, "e": 14684, "s": 14529, "text": "The Mitigating Controls section allows you to manage controls to mitigate segregation of duty, critical action, and critical permission access violations." }, { "code": null, "e": 14839, "s": 14684, "text": "The Mitigating Controls section allows you to manage controls to mitigate segregation of duty, critical action, and critical permission access violations." }, { "code": null, "e": 14943, "s": 14839, "text": "Superuser Assignment is where you assign owners to firefighter IDs and assign firefighter IDs to users." }, { "code": null, "e": 15047, "s": 14943, "text": "Superuser Assignment is where you assign owners to firefighter IDs and assign firefighter IDs to users." }, { "code": null, "e": 15145, "s": 15047, "text": "Superuser Maintenance is where you maintain firefighter, controller, and reason code assignments." }, { "code": null, "e": 15243, "s": 15145, "text": "Superuser Maintenance is where you maintain firefighter, controller, and reason code assignments." }, { "code": null, "e": 15328, "s": 15243, "text": "Under Access Owners, you manage owner privileges for access management capabilities." }, { "code": null, "e": 15413, "s": 15328, "text": "Under Access Owners, you manage owner privileges for access management capabilities." }, { "code": null, "e": 15552, "s": 15413, "text": "As per GRC software license, you can navigate Access Management Work Center. It has multiple sections to manage access control activities." }, { "code": null, "e": 15638, "s": 15552, "text": "When you click on Access Management Work Center, you can see the following sections −" }, { "code": null, "e": 15659, "s": 15638, "text": "GRC Role Assignments" }, { "code": null, "e": 15680, "s": 15659, "text": "Access Risk Analysis" }, { "code": null, "e": 15697, "s": 15680, "text": "Mitigated Access" }, { "code": null, "e": 15728, "s": 15697, "text": "Access Requests Administration" }, { "code": null, "e": 15744, "s": 15728, "text": "Role Management" }, { "code": null, "e": 15756, "s": 15744, "text": "Role Mining" }, { "code": null, "e": 15778, "s": 15756, "text": "Role Mass Maintenance" }, { "code": null, "e": 15799, "s": 15778, "text": "Superuser Assignment" }, { "code": null, "e": 15821, "s": 15799, "text": "Superuser Maintenance" }, { "code": null, "e": 15845, "s": 15821, "text": "Access Request Creation" }, { "code": null, "e": 15878, "s": 15845, "text": "Compliance Certification Reviews" }, { "code": null, "e": 15885, "s": 15878, "text": "Alerts" }, { "code": null, "e": 15896, "s": 15885, "text": "Scheduling" }, { "code": null, "e": 15948, "s": 15896, "text": "The above sections help you in the following ways −" }, { "code": null, "e": 16299, "s": 15948, "text": "When you go to access risk analysis section, you can evaluate your systems for access risks across users, roles, HR objects and organization levels. An access risk is two or more actions or permissions that, when available to a single user or single role, profile, organizational level, or HR Object, creates the possibility of error or irregularity." }, { "code": null, "e": 16650, "s": 16299, "text": "When you go to access risk analysis section, you can evaluate your systems for access risks across users, roles, HR objects and organization levels. An access risk is two or more actions or permissions that, when available to a single user or single role, profile, organizational level, or HR Object, creates the possibility of error or irregularity." }, { "code": null, "e": 16847, "s": 16650, "text": "Using mitigated access section, you can identify access risks, assess the level of those risks, and assign mitigating controls to users, roles, and profiles to mitigate the access rule violations." }, { "code": null, "e": 17044, "s": 16847, "text": "Using mitigated access section, you can identify access risks, assess the level of those risks, and assign mitigating controls to users, roles, and profiles to mitigate the access rule violations." }, { "code": null, "e": 17153, "s": 17044, "text": "In access request administration section, you can manage access assignments, accounts, and review processes." }, { "code": null, "e": 17262, "s": 17153, "text": "In access request administration section, you can manage access assignments, accounts, and review processes." }, { "code": null, "e": 17356, "s": 17262, "text": "Using role management, you manage roles from multiple systems in a single unified repository." }, { "code": null, "e": 17450, "s": 17356, "text": "Using role management, you manage roles from multiple systems in a single unified repository." }, { "code": null, "e": 17545, "s": 17450, "text": "In role mining group feature, you can target roles of interest, analyze them, and take action." }, { "code": null, "e": 17640, "s": 17545, "text": "In role mining group feature, you can target roles of interest, analyze them, and take action." }, { "code": null, "e": 17745, "s": 17640, "text": "Using role mass maintenance, you can import and change authorizations and attributes for multiple roles." }, { "code": null, "e": 17850, "s": 17745, "text": "Using role mass maintenance, you can import and change authorizations and attributes for multiple roles." }, { "code": null, "e": 17984, "s": 17850, "text": "In Superuser Assignment section, you can assign firefighter IDs to owners and assign firefighters and controllers to firefighter IDs." }, { "code": null, "e": 18118, "s": 17984, "text": "In Superuser Assignment section, you can assign firefighter IDs to owners and assign firefighters and controllers to firefighter IDs." }, { "code": null, "e": 18283, "s": 18118, "text": "In Superuser Maintenance section, you can perform activities such as researching and maintaining firefighters and controllers, and assigning reason codes by system." }, { "code": null, "e": 18448, "s": 18283, "text": "In Superuser Maintenance section, you can perform activities such as researching and maintaining firefighters and controllers, and assigning reason codes by system." }, { "code": null, "e": 18527, "s": 18448, "text": "Using access request creation, you can create access assignments and accounts." }, { "code": null, "e": 18606, "s": 18527, "text": "Using access request creation, you can create access assignments and accounts." }, { "code": null, "e": 18712, "s": 18606, "text": "Compliance certification reviews supports reviews of users’ access, risk violations and role assignments." }, { "code": null, "e": 18818, "s": 18712, "text": "Compliance certification reviews supports reviews of users’ access, risk violations and role assignments." }, { "code": null, "e": 18918, "s": 18818, "text": "Using alerts, you can generate by the application for execution of critical or conflicting actions." }, { "code": null, "e": 19018, "s": 18918, "text": "Using alerts, you can generate by the application for execution of critical or conflicting actions." }, { "code": null, "e": 19193, "s": 19018, "text": "Using Scheduling section of the Rule Setup Work Center, you can maintain schedules for continuous control monitoring and automated testing, and to track related job progress." }, { "code": null, "e": 19368, "s": 19193, "text": "Using Scheduling section of the Rule Setup Work Center, you can maintain schedules for continuous control monitoring and automated testing, and to track related job progress." }, { "code": null, "e": 19578, "s": 19368, "text": "In SAP GRC solution, you can manage authorization objects to limit the items and data that a user can access. Authorization controls what a user can access in regards to work centers and reports in SAP system." }, { "code": null, "e": 19637, "s": 19578, "text": "To access GRC solution, you should have following access −" }, { "code": null, "e": 19658, "s": 19637, "text": "Portal authorization" }, { "code": null, "e": 19680, "s": 19658, "text": "Applicable PFCG roles" }, { "code": null, "e": 19747, "s": 19680, "text": "PFCG roles for access control, process control and risk management" }, { "code": null, "e": 19836, "s": 19747, "text": "The authorization types listed below are required as per GRC components − AC, PC and RM." }, { "code": null, "e": 20125, "s": 19836, "text": "In SAP GRC 10.0 solution, work centers are defined in PCD roles for the Portal component and in PFCG roles for NWBC (NetWeaver Business Client). The work centers are fixed in each base role. SAP delivers these roles however; these roles can be modified by the customer as per requirement." }, { "code": null, "e": 20432, "s": 20125, "text": "The locations of application folders and subordinate applications within the service map are controlled by the SAP NetWeaver Launchpad application. Service map is controlled by user authorization so if user doesn’t have authorization to see any application they will be hidden in NetWeaver Business client." }, { "code": null, "e": 20480, "s": 20432, "text": "Follow these steps to review role assignments −" }, { "code": null, "e": 20555, "s": 20480, "text": "Step 1 − Go to Access Management Work Center in NetWeaver Business Client." }, { "code": null, "e": 20696, "s": 20555, "text": "Step 2 − Select business process under GRC Role assignment and go to sub-process role level. Click next to continue to assign role sections." }, { "code": null, "e": 20751, "s": 20696, "text": "Step 1 − Go to Master Data Work Center → Organizations" }, { "code": null, "e": 20832, "s": 20751, "text": "Step 2 − In next window, select any organization from the list, then click Open." }, { "code": null, "e": 20999, "s": 20832, "text": "Step 3 − Note that the triangle next to the organization means that there are suborganizations and the dot next to the organization means that it is the lowest level." }, { "code": null, "e": 21107, "s": 20999, "text": "Step 4 − Click on subprocess tab → Assign subprocess. Now select one or two subprocesses and click on Next." }, { "code": null, "e": 21186, "s": 21107, "text": "Step 5 − Without making any changes, click Finish on the Select Controls step." }, { "code": null, "e": 21294, "s": 21186, "text": "Step 6 − Choose the first subprocess from the list, then click Open. You should see the subprocess details." }, { "code": null, "e": 21372, "s": 21294, "text": "Step 7 − Click the Roles Tab. Choose a role from the list, then click Assign." }, { "code": null, "e": 21584, "s": 21372, "text": "SAP GRC Access Control uses UME roles to control the user authorization in the system. An administrator can use actions which represent the smallest entity of UME role that a user can use to build access rights." }, { "code": null, "e": 21719, "s": 21584, "text": "One UME role can contain actions from one or more applications. You have to assign UME roles to users in User Management Engine (UME)." }, { "code": null, "e": 21967, "s": 21719, "text": "When a user does not have access to a certain tab, the tab will not display upon user logon when the user tries to access that tab. When a UME action for a tab is assigned to that particular user, only then he will be able to access that function." }, { "code": null, "e": 22076, "s": 21967, "text": "All available standard UME actions for CC tabs can be found in the tab “Assigned Actions” of the Admin User." }, { "code": null, "e": 22327, "s": 22076, "text": "You should create an administrator role and this role should be assigned to Superuser to perform SAP compliance calibrator related activities. There are various CC roles that can be created under SAP GRC Access control at the time of implementation −" }, { "code": null, "e": 22403, "s": 22327, "text": "CC.ReportingView\nDescription − Compliance Calibrator Display and Reporting\n" }, { "code": null, "e": 22461, "s": 22403, "text": "Description − Compliance Calibrator Display and Reporting" }, { "code": null, "e": 22534, "s": 22461, "text": "CC.RuleMaintenance\nDescription − Compliance Calibrator Rule Maintenance\n" }, { "code": null, "e": 22587, "s": 22534, "text": "Description − Compliance Calibrator Rule Maintenance" }, { "code": null, "e": 22665, "s": 22587, "text": "CC.MitMaintenance\nDescription − Compliance Calibrator Mitigation Maintenance\n" }, { "code": null, "e": 22724, "s": 22665, "text": "Description − Compliance Calibrator Mitigation Maintenance" }, { "code": null, "e": 22818, "s": 22724, "text": "CC.Administration\nDescription − Compliance Calibrator Administration and Basis Configuration\n" }, { "code": null, "e": 22893, "s": 22818, "text": "Description − Compliance Calibrator Administration and Basis Configuration" }, { "code": null, "e": 22966, "s": 22893, "text": "Using UME, you can perform various key activities under Access Control −" }, { "code": null, "e": 23008, "s": 22966, "text": "You can perform user and role maintenance" }, { "code": null, "e": 23058, "s": 23008, "text": "It can be used for user data source configuration" }, { "code": null, "e": 23109, "s": 23058, "text": "You can apply security settings and password rules" }, { "code": null, "e": 23157, "s": 23109, "text": "To open UME, you should use the following URL −" }, { "code": null, "e": 23192, "s": 23157, "text": "http://<hostname>:<port>/useradmin" }, { "code": null, "e": 23387, "s": 23192, "text": "In SAP GRC 10.0, you can use Access Control Launch Pad to maintain key functionalities under GRC Access Control. It is a single web page that can be used for Risk Analysis and Remediation (RAR)." }, { "code": null, "e": 23730, "s": 23387, "text": "In GRC Access Control, you can use Risk Analysis and Remediation (RAR) capability to perform security audit and segregation of duties (SoD) analysis. It is a tool which can be used to identify, analyze, and resolve risk and audit issues linked to the following regulatory compliance. Here, you can also colloaboratively define the following −" }, { "code": null, "e": 23763, "s": 23730, "text": "Enterprise Role Management (ERM)" }, { "code": null, "e": 23797, "s": 23763, "text": "Compliant User Provisioning (CUP)" }, { "code": null, "e": 23828, "s": 23797, "text": "Superuser Privilege Management" }, { "code": null, "e": 23883, "s": 23828, "text": "Follow these steps to create a new Launchpad in NWBC −" }, { "code": null, "e": 23942, "s": 23883, "text": "Step 1 − Go to PFCG roles, and open the role SAP_GRAC_NWBC" }, { "code": null, "e": 24136, "s": 23942, "text": "Step 2 − When you right click My Home item, you can see the application being called is grfn_service_map?WDCONFIGURATIONID=GRAC_FPM_AC_LPD_HOME and the configuration id is GRAC_FPM_AC_LPD_HOME." }, { "code": null, "e": 24249, "s": 24136, "text": "Step 3 − Select application config button and you can see the application configuration screen → display button." }, { "code": null, "e": 24311, "s": 24249, "text": "Step 4 − When you click on Display, you can see this screen −" }, { "code": null, "e": 24366, "s": 24311, "text": "Step 5 − Now open the Component Configuration button." }, { "code": null, "e": 24469, "s": 24366, "text": "Step 6 − Click on Configure UIBB button in this screen. You will be directed to the following screen −" }, { "code": null, "e": 24607, "s": 24469, "text": "Step 7 − You can select the Launchpad to which you want to map. If you want to create a new Launchpad, you can also map it to a new role." }, { "code": null, "e": 24666, "s": 24607, "text": "Step 8 − To create a new Launchpad, define the following −" }, { "code": null, "e": 24720, "s": 24666, "text": "Create a new launchpad with menu items that you want." }, { "code": null, "e": 24774, "s": 24720, "text": "Create a new launchpad with menu items that you want." }, { "code": null, "e": 24917, "s": 24774, "text": "Create a new configuration of the application GRFN_SERVICE_MAP or you can copy configuration id GRAC_FPM_AC_LPD_HOME and customize it further." }, { "code": null, "e": 25060, "s": 24917, "text": "Create a new configuration of the application GRFN_SERVICE_MAP or you can copy configuration id GRAC_FPM_AC_LPD_HOME and customize it further." }, { "code": null, "e": 25134, "s": 25060, "text": "In the new configuration select the launchpad that you want to associate." }, { "code": null, "e": 25208, "s": 25134, "text": "In the new configuration select the launchpad that you want to associate." }, { "code": null, "e": 25342, "s": 25208, "text": "Create a new role and add webdynpro application GRFN_SERVICE_MAP to it with the custom configuration id created in the previous step." }, { "code": null, "e": 25476, "s": 25342, "text": "Create a new role and add webdynpro application GRFN_SERVICE_MAP to it with the custom configuration id created in the previous step." }, { "code": null, "e": 25694, "s": 25476, "text": "In SAP GRC 10.0 solution, the master data and organization structure is shared across access control, process control and risk management. Process Control also shares certain capabilities with risk management process." }, { "code": null, "e": 25754, "s": 25694, "text": "Following are the key features shared with Access Control −" }, { "code": null, "e": 26211, "s": 25754, "text": "Access control and process control shares the compliance structure in below areas −\n\nIn process control solution, controls are used as mitigation control in access control under SAP GRC 10.0 solution.\nAccess control and process control share same organization.\nIn process control, processes are used as business processes in access control.\nProcess control and access control are integrated with access risk analysis to monitor segregation of duties SoD.\n\n" }, { "code": null, "e": 26295, "s": 26211, "text": "Access control and process control shares the compliance structure in below areas −" }, { "code": null, "e": 26411, "s": 26295, "text": "In process control solution, controls are used as mitigation control in access control under SAP GRC 10.0 solution." }, { "code": null, "e": 26527, "s": 26411, "text": "In process control solution, controls are used as mitigation control in access control under SAP GRC 10.0 solution." }, { "code": null, "e": 26587, "s": 26527, "text": "Access control and process control share same organization." }, { "code": null, "e": 26647, "s": 26587, "text": "Access control and process control share same organization." }, { "code": null, "e": 26727, "s": 26647, "text": "In process control, processes are used as business processes in access control." }, { "code": null, "e": 26807, "s": 26727, "text": "In process control, processes are used as business processes in access control." }, { "code": null, "e": 26921, "s": 26807, "text": "Process control and access control are integrated with access risk analysis to monitor segregation of duties SoD." }, { "code": null, "e": 27035, "s": 26921, "text": "Process control and access control are integrated with access risk analysis to monitor segregation of duties SoD." }, { "code": null, "e": 27107, "s": 27035, "text": "The menu areas common to both Process Control and Risk Management are −" }, { "code": null, "e": 27127, "s": 27107, "text": "GRC Role Assignment" }, { "code": null, "e": 27151, "s": 27127, "text": "Process Control Planner" }, { "code": null, "e": 27175, "s": 27151, "text": "Risk Management Planner" }, { "code": null, "e": 27194, "s": 27175, "text": "Central Delegation" }, { "code": null, "e": 27285, "s": 27194, "text": "The following are the key integration points between Process Control and Risk Management −" }, { "code": null, "e": 27360, "s": 27285, "text": "New control points can be purposed for Process Control in Risk Management." }, { "code": null, "e": 27435, "s": 27360, "text": "New control points can be purposed for Process Control in Risk Management." }, { "code": null, "e": 27535, "s": 27435, "text": "When a new control is proposed, Process Control needs to evaluate the request from Risk Management." }, { "code": null, "e": 27635, "s": 27535, "text": "When a new control is proposed, Process Control needs to evaluate the request from Risk Management." }, { "code": null, "e": 27711, "s": 27635, "text": "Risk Management uses results from Process Control to evaluate new controls." }, { "code": null, "e": 27787, "s": 27711, "text": "Risk Management uses results from Process Control to evaluate new controls." }, { "code": null, "e": 27888, "s": 27787, "text": "Risk Management can also use existing controls from Process Control as responses in Risk Management." }, { "code": null, "e": 27989, "s": 27888, "text": "Risk Management can also use existing controls from Process Control as responses in Risk Management." }, { "code": null, "e": 28431, "s": 27989, "text": "Internal Audit Management allows you to process the information from Risk Management and Process Control to use in audit planning. Audit proposal can be transferred to audit management for processing when required and audit items can be used to generate issues for reporting. IAM provides you a place where you can perform complete audit planning, create audit items, define audit universe and create and view audit reports and audit issues." }, { "code": null, "e": 28528, "s": 28431, "text": "Internal Audit Management Work Center provides a central location for the following activities −" }, { "code": null, "e": 28576, "s": 28528, "text": "Define the audit universe for your organization" }, { "code": null, "e": 28594, "s": 28576, "text": "Audit risk rating" }, { "code": null, "e": 28650, "s": 28594, "text": "Audit planning to define procedure for audit compliance" }, { "code": null, "e": 28682, "s": 28650, "text": "Audit issues from audit actions" }, { "code": null, "e": 28746, "s": 28682, "text": "Audit reports to see what risks are there on auditable entities" }, { "code": null, "e": 29005, "s": 28746, "text": "Audit Universe contains audit entities which can be classified as business units, lines of business or departments. Audit entities define the audit planning strategy and these can be linked to Process Control and Risk Management to find risks, controls, etc." }, { "code": null, "e": 29061, "s": 29005, "text": "Let us now understand how to create an auditable enity." }, { "code": null, "e": 29121, "s": 29061, "text": "Step 1 − Go to /nwbc option at the top to open Work Centers" }, { "code": null, "e": 29187, "s": 29121, "text": "Step 2 − In SAP NetWeaver Business Client, go to IAM Work Center." }, { "code": null, "e": 29251, "s": 29187, "text": "Step 3 − Navigate to Internal Audit Management → Audit Universe" }, { "code": null, "e": 29306, "s": 29251, "text": "Step 4 − Click on Create button and go to General tab." }, { "code": null, "e": 29366, "s": 29306, "text": "Step 5 − Enter the following details for auditable entity −" }, { "code": null, "e": 29371, "s": 29366, "text": "Name" }, { "code": null, "e": 29383, "s": 29371, "text": "Description" }, { "code": null, "e": 29388, "s": 29383, "text": "Type" }, { "code": null, "e": 29395, "s": 29388, "text": "Status" }, { "code": null, "e": 29435, "s": 29395, "text": "Notes to add any additional information" }, { "code": null, "e": 29538, "s": 29435, "text": "Step 6 − Go to Audit Plan tab to view audit proposals and audit plan proposals with the transfer date." }, { "code": null, "e": 29619, "s": 29538, "text": "Step 7 − Select the attachments and links tab to add any type of files or links." }, { "code": null, "e": 29709, "s": 29619, "text": "Step 8 − When you enter the required details, you can select from the following options −" }, { "code": null, "e": 29741, "s": 29709, "text": "Select Save to save the entity." }, { "code": null, "e": 29778, "s": 29741, "text": "Select Close to exit without saving." }, { "code": null, "e": 30025, "s": 29778, "text": "Audit Risk rating is used to define the criteria for an organization to find risk rating and establish ranking for risk rating. Each auditable entity is rated as per management feedback in ARR. You can use ARR to perform the following functions −" }, { "code": null, "e": 30086, "s": 30025, "text": "You can find the set of auditable entities and risk factors." }, { "code": null, "e": 30147, "s": 30086, "text": "You can find the set of auditable entities and risk factors." }, { "code": null, "e": 30221, "s": 30147, "text": "Define and evaluate risk scores for risk factor in each auditable entity." }, { "code": null, "e": 30295, "s": 30221, "text": "Define and evaluate risk scores for risk factor in each auditable entity." }, { "code": null, "e": 30349, "s": 30295, "text": "As per risk score, you can rate the auditable entity." }, { "code": null, "e": 30403, "s": 30349, "text": "As per risk score, you can rate the auditable entity." }, { "code": null, "e": 30635, "s": 30403, "text": "You can also generate an audit plan from ARR by comparing risk scores for different auditable entities. In addition to this, you can select the high risk score auditable entities and generate audit proposal and audit plan proposal." }, { "code": null, "e": 30867, "s": 30635, "text": "You can also generate an audit plan from ARR by comparing risk scores for different auditable entities. In addition to this, you can select the high risk score auditable entities and generate audit proposal and audit plan proposal." }, { "code": null, "e": 30930, "s": 30867, "text": "Let us now understand the steps to create an Audit Risk Rating" }, { "code": null, "e": 30996, "s": 30930, "text": "Step 1 − In SAP NetWeaver Business Client, go to IAM Work Center." }, { "code": null, "e": 31072, "s": 30996, "text": "Step 2 − Navigate to Internal Audit Management → Audit Risk Rating → Create" }, { "code": null, "e": 31127, "s": 31072, "text": "Step 3 − In General tab, enter the following details −" }, { "code": null, "e": 31132, "s": 31127, "text": "Name" }, { "code": null, "e": 31144, "s": 31132, "text": "Description" }, { "code": null, "e": 31155, "s": 31144, "text": "Valid from" }, { "code": null, "e": 31164, "s": 31155, "text": "Valid to" }, { "code": null, "e": 31183, "s": 31164, "text": "Responsible person" }, { "code": null, "e": 31190, "s": 31183, "text": "Status" }, { "code": null, "e": 31280, "s": 31190, "text": "Step 4 − Go to Auditable Entities and click Add button to choose from auditable entities." }, { "code": null, "e": 31378, "s": 31280, "text": "Step 5 − Go to Risk Factor tab, and select ARR risk factor. Select Add to add a risk factor → OK." }, { "code": null, "e": 31578, "s": 31378, "text": "Step 6 − Go to Risk Scores tab, select entity and input risk scores on risk factor table. Click Calculate button to view average score. Go to Risk level and risk priority column to enter the details." }, { "code": null, "e": 31758, "s": 31578, "text": "Go to Audit Plan Proposal tab, to ensure that you are creating an audit plan proposal. Select export to create an excel spreadsheet to view information in table form for your ARR." }, { "code": null, "e": 31825, "s": 31758, "text": "Select Save button to save audit risk rating for auditable entity." }, { "code": null, "e": 32029, "s": 31825, "text": "Work centers provide a central access point for the entire GRC functionality. They are organized to provide easy access to application activities, and contain menu groups and links to further activities." }, { "code": null, "e": 32124, "s": 32029, "text": "The following work centers are shared by Access Control, Process Control and Risk Management −" }, { "code": null, "e": 32132, "s": 32124, "text": "My Home" }, { "code": null, "e": 32144, "s": 32132, "text": "Master Data" }, { "code": null, "e": 32155, "s": 32144, "text": "Rule Setup" }, { "code": null, "e": 32167, "s": 32155, "text": "Assessments" }, { "code": null, "e": 32185, "s": 32167, "text": "Access Management" }, { "code": null, "e": 32207, "s": 32185, "text": "Reports and Analytics" }, { "code": null, "e": 32246, "s": 32207, "text": "Let us discuss the major work centers." }, { "code": null, "e": 32536, "s": 32246, "text": "My Home Work Center is shared by Process Control, Risk management and Access Control. This provides a centralized location where you can manage assigned tasks and accessible objects in GRC application. My Home comes with a number of sections. Let us now understand the Work Inbox section −" }, { "code": null, "e": 32619, "s": 32536, "text": "Using Work Inbox, you can view the tasks that you have to process in GRC software." }, { "code": null, "e": 32678, "s": 32619, "text": "If you want to process a task, click on task in the table." }, { "code": null, "e": 32746, "s": 32678, "text": "It will open the workflow window wherein, you can process the task." }, { "code": null, "e": 32915, "s": 32746, "text": "Master Data Work Center is shared by Process Control, Risk management and access control. The Process Control Master Data Work center contains the following sections −" }, { "code": null, "e": 32929, "s": 32915, "text": "Organizations" }, { "code": null, "e": 32954, "s": 32929, "text": "Regulations and Policies" }, { "code": null, "e": 32965, "s": 32954, "text": "Objectives" }, { "code": null, "e": 32990, "s": 32965, "text": "Activities and Processes" }, { "code": null, "e": 33010, "s": 32990, "text": "Risks and Responses" }, { "code": null, "e": 33019, "s": 33010, "text": "Accounts" }, { "code": null, "e": 33027, "s": 33019, "text": "Reports" }, { "code": null, "e": 33101, "s": 33027, "text": "Let us now discuss the major work centers under Master Data Work Center −" }, { "code": null, "e": 33223, "s": 33101, "text": "Organizations − Maintain the company's organization structure for compliance and risk management with related assignments" }, { "code": null, "e": 33354, "s": 33223, "text": "Mitigation Controls − Maintain controls to mitigate segregation of duty, critical action and critical permission access violations" }, { "code": null, "e": 33405, "s": 33354, "text": "To create mitigation control, click Create button." }, { "code": null, "e": 33507, "s": 33405, "text": "You will be directed to a new window, enter the details for mitigation control and click Save button." }, { "code": null, "e": 33712, "s": 33507, "text": "Reports and Analytics Work Center is shared by Process Control, Risk management and Access Control. The Process Control Reports and Analytics Work Center consists of Compliance section in GRC application." }, { "code": null, "e": 33796, "s": 33712, "text": "In compliance section, you can create the following reports under Process Control −" }, { "code": null, "e": 34007, "s": 33796, "text": "Shows a high-level picture of the overall status of corporate compliance throughout different business entities and provides analytics and drilldown capabilities to view data on different levels and dimensions." }, { "code": null, "e": 34040, "s": 34007, "text": "Displays the results of surveys." }, { "code": null, "e": 34161, "s": 34040, "text": "Provides comprehensive information on master data, evaluation, and remediation activities for subprocesses and controls." }, { "code": null, "e": 34220, "s": 34161, "text": "The following roles that use the datasheet functionality −" }, { "code": null, "e": 34344, "s": 34220, "text": "Internal Auditors − They can use datasheets to get a picture of the controls and subprocesses in an organization under GRC." }, { "code": null, "e": 34468, "s": 34344, "text": "Internal Auditors − They can use datasheets to get a picture of the controls and subprocesses in an organization under GRC." }, { "code": null, "e": 34802, "s": 34468, "text": "Process Owners − In GRC application, Process Owners and Control Owners can request datasheets to get an overview of their subprocesses. Datasheet information provides the definition of the subprocess, assessments completed on subprocess, controls encompassed by the subprocess, and the assessments and testing done on these controls." }, { "code": null, "e": 35136, "s": 34802, "text": "Process Owners − In GRC application, Process Owners and Control Owners can request datasheets to get an overview of their subprocesses. Datasheet information provides the definition of the subprocess, assessments completed on subprocess, controls encompassed by the subprocess, and the assessments and testing done on these controls." }, { "code": null, "e": 35307, "s": 35136, "text": "Control Owners − Control owners can use datasheets to check the design of their controls. Control owner can assess controls to check the controls and their effectiveness." }, { "code": null, "e": 35478, "s": 35307, "text": "Control Owners − Control owners can use datasheets to check the design of their controls. Control owner can assess controls to check the controls and their effectiveness." }, { "code": null, "e": 35625, "s": 35478, "text": "External Auditors − Datasheets can be used by external auditors; this can be used to request the information to research controls or subprocesses." }, { "code": null, "e": 35772, "s": 35625, "text": "External Auditors − Datasheets can be used by external auditors; this can be used to request the information to research controls or subprocesses." }, { "code": null, "e": 35921, "s": 35772, "text": "Note − Other work centers like access management, assessments and rule set up are also share by process control, access control and risk management." }, { "code": null, "e": 36009, "s": 35921, "text": "The Process Control Access Management Work Center has the GRC Role Assignments section." }, { "code": null, "e": 36237, "s": 36009, "text": "In every business, it is required to perform Segregation of Duties (SoD) Risk Management - starting from risk recognition to rule building validation and various other risk management activities to follow continuous compliance." }, { "code": null, "e": 36404, "s": 36237, "text": "As per different roles, there is a need to perform Segregation of Duties in GRC system. SAP GRC defines various roles and responsibilities under SoD Risk Management −" }, { "code": null, "e": 36458, "s": 36404, "text": "Business Process Owners perform the following tasks −" }, { "code": null, "e": 36506, "s": 36458, "text": "Identify risks and approve risks for monitoring" }, { "code": null, "e": 36548, "s": 36506, "text": "Approve remediation involving user access" }, { "code": null, "e": 36586, "s": 36548, "text": "Design controls to mitigate conflicts" }, { "code": null, "e": 36633, "s": 36586, "text": "Communicate access assignments or role changes" }, { "code": null, "e": 36673, "s": 36633, "text": "Perform proactive continuous compliance" }, { "code": null, "e": 36719, "s": 36673, "text": "Senior Officers perform the following tasks −" }, { "code": null, "e": 36766, "s": 36719, "text": "Approve or reject risks between business areas" }, { "code": null, "e": 36813, "s": 36766, "text": "Approve mitigation controls for selected risks" }, { "code": null, "e": 36867, "s": 36813, "text": "Security Administrators perform the following tasks −" }, { "code": null, "e": 36918, "s": 36867, "text": "Assume ownership of GRC tools and security process" }, { "code": null, "e": 36972, "s": 36918, "text": "Design and maintain rules to identify risk conditions" }, { "code": null, "e": 37030, "s": 36972, "text": "Customize GRC roles to enforce roles and responsibilities" }, { "code": null, "e": 37080, "s": 37030, "text": "Analyze and remediate SoD conflicts at role level" }, { "code": null, "e": 37119, "s": 37080, "text": "Auditors perform the following tasks −" }, { "code": null, "e": 37154, "s": 37119, "text": "Risk assessment on a regular basis" }, { "code": null, "e": 37203, "s": 37154, "text": "Provide specific requirements for audit purposes" }, { "code": null, "e": 37253, "s": 37203, "text": "Periodic testing of rules and mitigation controls" }, { "code": null, "e": 37294, "s": 37253, "text": "Act as liaison between external auditors" }, { "code": null, "e": 37341, "s": 37294, "text": "SoD Rule Keeper performs the following tasks −" }, { "code": null, "e": 37383, "s": 37341, "text": "GRC tool configuration and administration" }, { "code": null, "e": 37433, "s": 37383, "text": "Maintains controls over rules to ensure integrity" }, { "code": null, "e": 37487, "s": 37433, "text": "Acts as liaison bet ween basis and GRC support center" }, { "code": null, "e": 37710, "s": 37487, "text": "SAP Risk Management in GRC is used to manage risk-adjusted management of enterprise performance that empowers an organization to optimize efficiency, increase effectiveness, and maximize visibility across risk initiatives." }, { "code": null, "e": 37770, "s": 37710, "text": "The following are the key functions under Risk Management −" }, { "code": null, "e": 37888, "s": 37770, "text": "Risk management emphasizes on organizational alignment towards top risks, associated thresholds, and risk mitigation." }, { "code": null, "e": 38006, "s": 37888, "text": "Risk management emphasizes on organizational alignment towards top risks, associated thresholds, and risk mitigation." }, { "code": null, "e": 38079, "s": 38006, "text": "Risk analysis includes performing qualitative and quantitative analysis." }, { "code": null, "e": 38152, "s": 38079, "text": "Risk analysis includes performing qualitative and quantitative analysis." }, { "code": null, "e": 38225, "s": 38152, "text": "Risk management involves Identification of key risks in an organization." }, { "code": null, "e": 38298, "s": 38225, "text": "Risk management involves Identification of key risks in an organization." }, { "code": null, "e": 38373, "s": 38298, "text": "Risk management also includes resolution/remediation strategies for risks." }, { "code": null, "e": 38448, "s": 38373, "text": "Risk management also includes resolution/remediation strategies for risks." }, { "code": null, "e": 38624, "s": 38448, "text": "Risk management performs the alignment of key risk and performance indicators across all business functions permitting earlier risk identification and dynamic risk mitigation." }, { "code": null, "e": 38800, "s": 38624, "text": "Risk management performs the alignment of key risk and performance indicators across all business functions permitting earlier risk identification and dynamic risk mitigation." }, { "code": null, "e": 38900, "s": 38800, "text": "Risk management also involves proactive monitoring into existing business processes and strategies." }, { "code": null, "e": 39016, "s": 38900, "text": "Let us now discuss the various phases in Risk Management. The following are the various phases in risk management −" }, { "code": null, "e": 39033, "s": 39016, "text": "Risk Recognition" }, { "code": null, "e": 39062, "s": 39033, "text": "Rule Building and Validation" }, { "code": null, "e": 39071, "s": 39062, "text": "Analysis" }, { "code": null, "e": 39083, "s": 39071, "text": "Remediation" }, { "code": null, "e": 39094, "s": 39083, "text": "Mitigation" }, { "code": null, "e": 39116, "s": 39094, "text": "Continuous Compliance" }, { "code": null, "e": 39208, "s": 39116, "text": "In a risk recognition process under risk management, the following steps can be performed −" }, { "code": null, "e": 39260, "s": 39208, "text": "Identify authorization risks and approve exceptions" }, { "code": null, "e": 39309, "s": 39260, "text": "Clarify and classify risk as high, medium or low" }, { "code": null, "e": 39372, "s": 39309, "text": "Identify new risks and conditions for monitoring in the future" }, { "code": null, "e": 39437, "s": 39372, "text": "Perform the following tasks under Rule Building and Validation −" }, { "code": null, "e": 39488, "s": 39437, "text": "Reference the best practices rules for environment" }, { "code": null, "e": 39507, "s": 39488, "text": "Validate the rules" }, { "code": null, "e": 39532, "s": 39507, "text": "Customize rules and test" }, { "code": null, "e": 39572, "s": 39532, "text": "Verify against test user and role cases" }, { "code": null, "e": 39617, "s": 39572, "text": "Perform the following tasks under Analysis −" }, { "code": null, "e": 39644, "s": 39617, "text": "Run the analytical reports" }, { "code": null, "e": 39669, "s": 39644, "text": "Estimate cleanup efforts" }, { "code": null, "e": 39693, "s": 39669, "text": "Analyze roles and users" }, { "code": null, "e": 39724, "s": 39693, "text": "Modify rules based on analysis" }, { "code": null, "e": 39765, "s": 39724, "text": "Set alerts to distinguish executed risks" }, { "code": null, "e": 39876, "s": 39765, "text": "From the management aspect, you can see compact view of risk violations that are grouped by severity and time." }, { "code": null, "e": 39934, "s": 39876, "text": "Step 1 − Go to Virsa Compliance Calibrator → Informer tab" }, { "code": null, "e": 40073, "s": 39934, "text": "Step 2 − For SoD violations, you can display a pie chart and a bar chart to represent current and past violations in the system landscape." }, { "code": null, "e": 40137, "s": 40073, "text": "The following are the two different views to these violations −" }, { "code": null, "e": 40162, "s": 40137, "text": "Violations by risk level" }, { "code": null, "e": 40184, "s": 40162, "text": "Violations by process" }, { "code": null, "e": 40232, "s": 40184, "text": "Perform the following tasks under remediation −" }, { "code": null, "e": 40277, "s": 40232, "text": "Determine alternatives for eliminating risks" }, { "code": null, "e": 40324, "s": 40277, "text": "Present analysis and select corrective actions" }, { "code": null, "e": 40364, "s": 40324, "text": "Document approval of corrective actions" }, { "code": null, "e": 40407, "s": 40364, "text": "Modify or create roles or user assignments" }, { "code": null, "e": 40454, "s": 40407, "text": "Perform the following tasks under mitigation −" }, { "code": null, "e": 40502, "s": 40454, "text": "Determine alternative controls to mitigate risk" }, { "code": null, "e": 40560, "s": 40502, "text": "Educate management about conflict approval and monitoring" }, { "code": null, "e": 40610, "s": 40560, "text": "Document a process to monitor mitigation controls" }, { "code": null, "e": 40629, "s": 40610, "text": "Implement controls" }, { "code": null, "e": 40687, "s": 40629, "text": "Perform the following tasks under Continuous Compliance −" }, { "code": null, "e": 40737, "s": 40687, "text": "Communicate changes in roles and user assignments" }, { "code": null, "e": 40773, "s": 40737, "text": "Simulate changes to roles and users" }, { "code": null, "e": 40849, "s": 40773, "text": "Implement alerts to monitor for selected risks and mitigate control testing" }, { "code": null, "e": 41016, "s": 40849, "text": "Risks should be classified as per the company policy. The following are the various risk classifications that you can define as per risk priority and company policy −" }, { "code": null, "e": 41168, "s": 41016, "text": "Critical classification is done for risks that contain company’s critical assets that are very likely to be compromised by fraud or system disruptions." }, { "code": null, "e": 41297, "s": 41168, "text": "This includes physical or monetary loss or system-wide disruption that includes fraud, loss of any asset or failure of a system." }, { "code": null, "e": 41382, "s": 41297, "text": "This includes multiple system disruption like overwriting master data in the system." }, { "code": null, "e": 41514, "s": 41382, "text": "This includes risk where the productivity losses or system failures compromised by fraud or system disruptions and loss is minimum." }, { "code": null, "e": 41733, "s": 41514, "text": "In SAP GRC 10.0 Risk Management, risk remediation phase determines the method to eliminate risks in roles. The purpose of the remediation phase is to determine alternatives for eliminating issues under risk management." }, { "code": null, "e": 41803, "s": 41733, "text": "The following approaches are recommended to resolve issues in roles −" }, { "code": null, "e": 41876, "s": 41803, "text": "You can start with single roles as it is easy and simplest way to start." }, { "code": null, "e": 41949, "s": 41876, "text": "You can start with single roles as it is easy and simplest way to start." }, { "code": null, "e": 42033, "s": 41949, "text": "You can check for any Segregation of Duties SoD violations from being reintroduced." }, { "code": null, "e": 42117, "s": 42033, "text": "You can check for any Segregation of Duties SoD violations from being reintroduced." }, { "code": null, "e": 42225, "s": 42117, "text": "You can perform various analysis to check the user assignment on the assignment or removal of user actions." }, { "code": null, "e": 42333, "s": 42225, "text": "You can perform various analysis to check the user assignment on the assignment or removal of user actions." }, { "code": null, "e": 42431, "s": 42333, "text": "You can use Management view or Risk Analysis reports for analysis as mentioned in previous topic." }, { "code": null, "e": 42529, "s": 42431, "text": "You can use Management view or Risk Analysis reports for analysis as mentioned in previous topic." }, { "code": null, "e": 42668, "s": 42529, "text": "In Risk Remediation, Security Administrators should document the plan and Business Process Owners should be involved and approve the plan." }, { "code": null, "e": 42748, "s": 42668, "text": "You can generate different Risk Analysis reports as per the required analysis −" }, { "code": null, "e": 42819, "s": 42748, "text": "Action Level − You can use it to perform SoD analysis at action level." }, { "code": null, "e": 42890, "s": 42819, "text": "Action Level − You can use it to perform SoD analysis at action level." }, { "code": null, "e": 42983, "s": 42890, "text": "Permission Level − This can be used to perform SoD analysis at action and permission levels." }, { "code": null, "e": 43076, "s": 42983, "text": "Permission Level − This can be used to perform SoD analysis at action and permission levels." }, { "code": null, "e": 43183, "s": 43076, "text": "Critical Actions − This can be used to analyze the users who have access to one of the critical functions." }, { "code": null, "e": 43290, "s": 43183, "text": "Critical Actions − This can be used to analyze the users who have access to one of the critical functions." }, { "code": null, "e": 43387, "s": 43290, "text": "Critical Permissions − This can be used to analyze users having access to one critical function." }, { "code": null, "e": 43484, "s": 43387, "text": "Critical Permissions − This can be used to analyze users having access to one critical function." }, { "code": null, "e": 43594, "s": 43484, "text": "Critical Roles/Profiles − This can be used to analyze the users who has access to critical roles or profiles." }, { "code": null, "e": 43704, "s": 43594, "text": "Critical Roles/Profiles − This can be used to analyze the users who has access to critical roles or profiles." }, { "code": null, "e": 43842, "s": 43704, "text": "In SAP GRC 10.0, you can use mitigation controls when it is not possible to separate Segregation of duties SoD from the business process." }, { "code": null, "e": 43978, "s": 43842, "text": "In an organization, consider a scenario where a person takes care of roles within business processes that cause a missing SoD conflict." }, { "code": null, "e": 44051, "s": 43978, "text": "There are different examples that are possible for mitigation controls −" }, { "code": null, "e": 44095, "s": 44051, "text": "Release strategies and authorization limits" }, { "code": null, "e": 44115, "s": 44095, "text": "Review of user logs" }, { "code": null, "e": 44143, "s": 44115, "text": "Review of exception reports" }, { "code": null, "e": 44170, "s": 44143, "text": "Detailed variance analysis" }, { "code": null, "e": 44229, "s": 44170, "text": "Establish insurance to cover impact of a security incident" }, { "code": null, "e": 44303, "s": 44229, "text": "There are two types of mitigation control under SAP GRC Risk management −" }, { "code": null, "e": 44314, "s": 44303, "text": "Preventive" }, { "code": null, "e": 44324, "s": 44314, "text": "Detective" }, { "code": null, "e": 44506, "s": 44324, "text": "Preventive mitigation control is used to reduce the impact of risk before it actually occurs. There are various activities that you can perform under preventive mitigation control −" }, { "code": null, "e": 44520, "s": 44506, "text": "Configuration" }, { "code": null, "e": 44531, "s": 44520, "text": "User Exits" }, { "code": null, "e": 44540, "s": 44531, "text": "Security" }, { "code": null, "e": 44558, "s": 44540, "text": "Defining workflow" }, { "code": null, "e": 44573, "s": 44558, "text": "Custom Objects" }, { "code": null, "e": 44750, "s": 44573, "text": "Detective mitigation control is used when an alert is received and a risk occurs. In this case, the person who is responsible to initiate corrective measure mitigates the risk." }, { "code": null, "e": 44837, "s": 44750, "text": "There are various activities that you can perform under detective mitigation control −" }, { "code": null, "e": 44854, "s": 44837, "text": "Activity Reports" }, { "code": null, "e": 44890, "s": 44854, "text": "Comparison of plan vs actual review" }, { "code": null, "e": 44904, "s": 44890, "text": "Budget review" }, { "code": null, "e": 44911, "s": 44904, "text": "Alerts" }, { "code": null, "e": 44961, "s": 44911, "text": "Follow these steps to set up migration controls −" }, { "code": null, "e": 45003, "s": 44961, "text": "Step 1 − Login to SAP GRC Access control." }, { "code": null, "e": 45077, "s": 45003, "text": "Step 2 − Perform a risk analysis on user level. Enter the below details −" }, { "code": null, "e": 45089, "s": 45077, "text": "Report Type" }, { "code": null, "e": 45103, "s": 45089, "text": "Report Format" }, { "code": null, "e": 45126, "s": 45103, "text": "Step 3 − Click Execute" }, { "code": null, "e": 45214, "s": 45126, "text": "Step 4 − You can toggle between different report types as in the following screenshot −" }, { "code": null, "e": 45314, "s": 45214, "text": "Step 5 − Logon to SAP GRC Access Control and schedule a risk analysis background job on role level." }, { "code": null, "e": 45344, "s": 45314, "text": "Enter the following details −" }, { "code": null, "e": 45375, "s": 45344, "text": "Report Type − Permission Level" }, { "code": null, "e": 45399, "s": 45375, "text": "Report Format − Summary" }, { "code": null, "e": 45471, "s": 45399, "text": "Step 6 − Click Run in Background as shown in the following screenshot −" }, { "code": null, "e": 45550, "s": 45471, "text": "Step 7 − In the next window, you can select Start Immediately. Then, click OK." }, { "code": null, "e": 45767, "s": 45550, "text": "In SAP GRC 10.0, Superuser Privilege Management needs to be implemented in your organization to eliminate the excessive authorizations and risks that your company experiences with the current emergency user approach." }, { "code": null, "e": 45827, "s": 45767, "text": "The following are the key features in Superuser Privilege −" }, { "code": null, "e": 45929, "s": 45827, "text": "You can allow Superuser to perform emergency activities within a controlled and auditable environment" }, { "code": null, "e": 46031, "s": 45929, "text": "You can allow Superuser to perform emergency activities within a controlled and auditable environment" }, { "code": null, "e": 46130, "s": 46031, "text": "Using Superuser, you can report all the user activities accessing higher authorization privileges." }, { "code": null, "e": 46229, "s": 46130, "text": "Using Superuser, you can report all the user activities accessing higher authorization privileges." }, { "code": null, "e": 46336, "s": 46229, "text": "You can generate an audit trail, which can be used to document reasons for using higher access privileges." }, { "code": null, "e": 46443, "s": 46336, "text": "You can generate an audit trail, which can be used to document reasons for using higher access privileges." }, { "code": null, "e": 46492, "s": 46443, "text": "This audit trail can be used for SOX compliance." }, { "code": null, "e": 46541, "s": 46492, "text": "This audit trail can be used for SOX compliance." }, { "code": null, "e": 46893, "s": 46541, "text": "Superuser can act as firefighter and have the following additional capabilities −\n\nIt can be used to perform tasks outside of their normal role or profile in an emergency situation.\nOnly certain individuals (owners) can assign Firefighter IDs.\nIt provides an extended capability to users while creating an auditing layer to monitor and record usage.\n\n" }, { "code": null, "e": 46975, "s": 46893, "text": "Superuser can act as firefighter and have the following additional capabilities −" }, { "code": null, "e": 47074, "s": 46975, "text": "It can be used to perform tasks outside of their normal role or profile in an emergency situation." }, { "code": null, "e": 47173, "s": 47074, "text": "It can be used to perform tasks outside of their normal role or profile in an emergency situation." }, { "code": null, "e": 47235, "s": 47173, "text": "Only certain individuals (owners) can assign Firefighter IDs." }, { "code": null, "e": 47297, "s": 47235, "text": "Only certain individuals (owners) can assign Firefighter IDs." }, { "code": null, "e": 47403, "s": 47297, "text": "It provides an extended capability to users while creating an auditing layer to monitor and record usage." }, { "code": null, "e": 47509, "s": 47403, "text": "It provides an extended capability to users while creating an auditing layer to monitor and record usage." }, { "code": null, "e": 47587, "s": 47509, "text": "You can use the following standard roles for Superuser Privilege Management −" }, { "code": null, "e": 47633, "s": 47587, "text": "This has the Ability to configure Firefighter" }, { "code": null, "e": 47699, "s": 47633, "text": "Assign Firefighter role owners and controllers to Firefighter IDs" }, { "code": null, "e": 47711, "s": 47699, "text": "Run Reports" }, { "code": null, "e": 47755, "s": 47711, "text": "Assign Firefighter IDs to Firefighter users" }, { "code": null, "e": 47806, "s": 47755, "text": "Upload, download, and view Firefighter history log" }, { "code": null, "e": 47837, "s": 47806, "text": "Access the firefighter program" }, { "code": null, "e": 47887, "s": 47837, "text": "Let us now understand how to implement Superuser." }, { "code": null, "e": 47957, "s": 47887, "text": "You can implement firefighter IDs by working on the following steps −" }, { "code": null, "e": 48020, "s": 47957, "text": "Step 1 − Create Firefighter IDs for each business process area" }, { "code": null, "e": 48094, "s": 48020, "text": "Step 2 − Assign necessary roles and profiles to carry firefighting tasks." }, { "code": null, "e": 48131, "s": 48094, "text": "You shouldn’t assign profile SAP_ALL" }, { "code": null, "e": 48158, "s": 48131, "text": "Step 3 − Use T-Code – SU01" }, { "code": null, "e": 48209, "s": 48158, "text": "Step 4 − Click Create button to create a new user." }, { "code": null, "e": 48275, "s": 48209, "text": "Step 5 − Assign Firefighter roles as mentioned above to user id −" }, { "code": null, "e": 48324, "s": 48275, "text": "Assign Firefighter roles to applicable user IDs." }, { "code": null, "e": 48373, "s": 48324, "text": "Assign Firefighter roles to applicable user IDs." }, { "code": null, "e": 48476, "s": 48373, "text": "Assign administrator role /VIRSA/Z_VFAT_ADMINISTRATOR to superuser privilege management administrator." }, { "code": null, "e": 48579, "s": 48476, "text": "Assign administrator role /VIRSA/Z_VFAT_ADMINISTRATOR to superuser privilege management administrator." }, { "code": null, "e": 48638, "s": 48579, "text": "Administrator user should not be assigned any firefighting" }, { "code": null, "e": 48697, "s": 48638, "text": "Administrator user should not be assigned any firefighting" }, { "code": null, "e": 48867, "s": 48697, "text": "Assign the standard role /VIRSA/ Z_VFAT_FIREFIGHTER to −\n\nFirefighter ID − Service user used for logon\nFirefighter user − Standard user acting as a Firefighter in case\n\n" }, { "code": null, "e": 48924, "s": 48867, "text": "Assign the standard role /VIRSA/ Z_VFAT_FIREFIGHTER to −" }, { "code": null, "e": 48969, "s": 48924, "text": "Firefighter ID − Service user used for logon" }, { "code": null, "e": 49034, "s": 48969, "text": "Firefighter user − Standard user acting as a Firefighter in case" }, { "code": null, "e": 49293, "s": 49034, "text": "Assign the ID owner role /VIRSA/Z_VFAT_ID_OWNER to −\n\nOwner − Responsible for determining who will be assigned to\nController − Receives notification when the Firefighter ID is responsibilities of emergency Firefighter IDs for his or her business area used.\n\n" }, { "code": null, "e": 49346, "s": 49293, "text": "Assign the ID owner role /VIRSA/Z_VFAT_ID_OWNER to −" }, { "code": null, "e": 49406, "s": 49346, "text": "Owner − Responsible for determining who will be assigned to" }, { "code": null, "e": 49466, "s": 49406, "text": "Owner − Responsible for determining who will be assigned to" }, { "code": null, "e": 49609, "s": 49466, "text": "Controller − Receives notification when the Firefighter ID is responsibilities of emergency Firefighter IDs for his or her business area used." }, { "code": null, "e": 49752, "s": 49609, "text": "Controller − Receives notification when the Firefighter ID is responsibilities of emergency Firefighter IDs for his or her business area used." }, { "code": null, "e": 49832, "s": 49752, "text": "Step 6 − Go to Roles tab and select the mentioned roles as per the requirement." }, { "code": null, "e": 49904, "s": 49832, "text": "Step 7 − Create RFC destination for internal switch to Firefighter ID −" }, { "code": null, "e": 49937, "s": 49904, "text": "Name − Enter RFC connection name" }, { "code": null, "e": 49970, "s": 49937, "text": "Name − Enter RFC connection name" }, { "code": null, "e": 49990, "s": 49970, "text": "Connection Type − 3" }, { "code": null, "e": 50010, "s": 49990, "text": "Connection Type − 3" }, { "code": null, "e": 50089, "s": 50010, "text": "Enter a Description\n(No username, passwords, or other logon data are required)" }, { "code": null, "e": 50109, "s": 50089, "text": "Enter a Description" }, { "code": null, "e": 50168, "s": 50109, "text": "(No username, passwords, or other logon data are required)" }, { "code": null, "e": 50327, "s": 50168, "text": "Enter passwords for each Firefighter ID in the Security table: Passwords are stored as hash values and are unreadable after the administrator saves the value." }, { "code": null, "e": 50486, "s": 50327, "text": "Enter passwords for each Firefighter ID in the Security table: Passwords are stored as hash values and are unreadable after the administrator saves the value." }, { "code": null, "e": 50557, "s": 50486, "text": "Step 8 − To create firefighter log, you can schedule a background job." }, { "code": null, "e": 50619, "s": 50557, "text": "Name the job /VIRSA/ZVFATBAK as in the following screenshot −" }, { "code": null, "e": 50668, "s": 50619, "text": "Let us understand these steps for Superuser Log." }, { "code": null, "e": 50723, "s": 50668, "text": "Step 1 − Use T-Code − Transaction − /n/VIRSA/ZVFAT_V01" }, { "code": null, "e": 50780, "s": 50723, "text": "Step 2 − You can now find the logs in the toolbox area. " }, { "code": null, "e": 50865, "s": 50780, "text": "Step 3 − You can use transaction code — SM37 to review the logs for individual user." }, { "code": null, "e": 50996, "s": 50865, "text": "You can also use the web GUI to access all Firefighter information. Go to SAP GRC Access control → Superuser privilege management." }, { "code": null, "e": 51164, "s": 50996, "text": "So it is possible to access the data of different Firefighter installations on different SAP backend systems. And it is not necessary to log on to each system anymore." }, { "code": null, "e": 51367, "s": 51164, "text": "You can implement enhanced risk analysis using organization rules. In shared service business units, you can use organization rules to achieve procedures for risk analysis and management of user groups." }, { "code": null, "e": 51488, "s": 51367, "text": "Consider a case where a user has created a fictitious vendor and invoices have been generated to gain financial benefit." }, { "code": null, "e": 51578, "s": 51488, "text": "You can create an organization rule with company code enabled to eliminate this scenario." }, { "code": null, "e": 51642, "s": 51578, "text": "Following steps should be performed to prevent this situation −" }, { "code": null, "e": 51688, "s": 51642, "text": "Enable organization level fields in functions" }, { "code": null, "e": 51705, "s": 51688, "text": "Create org rules" }, { "code": null, "e": 51735, "s": 51705, "text": "Update org user mapping table" }, { "code": null, "e": 51771, "s": 51735, "text": "Configure risk analysis web service" }, { "code": null, "e": 51841, "s": 51771, "text": "Follow these steps to enable organization level fields in functions −" }, { "code": null, "e": 51930, "s": 51841, "text": "Find out functions to be segregated by organization level in shared service environment." }, { "code": null, "e": 52019, "s": 51930, "text": "Find out functions to be segregated by organization level in shared service environment." }, { "code": null, "e": 52067, "s": 52019, "text": "Maintain permissions for affected transactions." }, { "code": null, "e": 52115, "s": 52067, "text": "Maintain permissions for affected transactions." }, { "code": null, "e": 52165, "s": 52115, "text": "Follow these steps to create organization rules −" }, { "code": null, "e": 52248, "s": 52165, "text": "Step 1 − Create organization rules for every possible value of organization field." }, { "code": null, "e": 52308, "s": 52248, "text": "Step 2 − Go to rule architect → Organization level → Create" }, { "code": null, "e": 52355, "s": 52308, "text": "Step 3 − Enter the organization rule ID field." }, { "code": null, "e": 52388, "s": 52355, "text": "Step 4 − Enter the related task." }, { "code": null, "e": 52470, "s": 52388, "text": "Step 5 − Define organization level field and combine them with Boolean operators." }, { "code": null, "e": 52528, "s": 52470, "text": "Step 6 − Click Save button to save the Organization rule." }, { "code": null, "e": 52591, "s": 52528, "text": "Let us now understand th benefits of using organization rules." }, { "code": null, "e": 52672, "s": 52591, "text": "You can use organizational rules for companies to implement following features −" }, { "code": null, "e": 52801, "s": 52672, "text": "You can use organization rules to implement shared services. They segregate duties with the help of organizational restrictions." }, { "code": null, "e": 52930, "s": 52801, "text": "You can use organization rules to implement shared services. They segregate duties with the help of organizational restrictions." }, { "code": null, "e": 52962, "s": 52930, "text": "Go to Risk Analysis → Org Level" }, { "code": null, "e": 52994, "s": 52962, "text": "Go to Risk Analysis → Org Level" }, { "code": null, "e": 53059, "s": 52994, "text": "Perform a risk analysis of analysis type Org Rule against a user" }, { "code": null, "e": 53124, "s": 53059, "text": "Perform a risk analysis of analysis type Org Rule against a user" }, { "code": null, "e": 53302, "s": 53124, "text": "You will receive the following output −\n\nThe risk analysis will only show a risk if the user has access to the same specific company code in each of the conflicting functions.\n\n" }, { "code": null, "e": 53342, "s": 53302, "text": "You will receive the following output −" }, { "code": null, "e": 53477, "s": 53342, "text": "The risk analysis will only show a risk if the user has access to the same specific company code in each of the conflicting functions." }, { "code": null, "e": 53612, "s": 53477, "text": "The risk analysis will only show a risk if the user has access to the same specific company code in each of the conflicting functions." }, { "code": null, "e": 53761, "s": 53612, "text": "In an organization, you have control owners at different organization hierarchy levels. Risk should be managed and mitigated as per level of access." }, { "code": null, "e": 53819, "s": 53761, "text": "The following are the control owners in an organization −" }, { "code": null, "e": 53854, "s": 53819, "text": "One control owner for global level" }, { "code": null, "e": 53899, "s": 53854, "text": "Different control owners for regional levels" }, { "code": null, "e": 53939, "s": 53899, "text": "Multiple control owners for local level" }, { "code": null, "e": 54130, "s": 53939, "text": "You have to assign mitigation controls to different levels of responsibility. Now if there is a risk violation at region and local level, you should perform risk mitigation at highest level." }, { "code": null, "e": 54426, "s": 54130, "text": "To use mitigation control at organization hierarchy, let us say you have performed risk analysis at organization level and the user violates all child organization rules and meets the condition of parent rule and only parent rule shows up; you can perform risk mitigation in the following ways −" }, { "code": null, "e": 54451, "s": 54426, "text": "Mitigation on user level" }, { "code": null, "e": 54484, "s": 54451, "text": "Mitigation on organization level" }, { "code": null, "e": 54555, "s": 54484, "text": "In SAO GRC 10.0, a workflow is triggered in the following situations −" }, { "code": null, "e": 54582, "s": 54555, "text": "To create or update risks." }, { "code": null, "e": 54623, "s": 54582, "text": "To create or update mitigation controls." }, { "code": null, "e": 54654, "s": 54623, "text": "To assign mitigation controls." }, { "code": null, "e": 54786, "s": 54654, "text": "As you follow workflow-based change management approach in risk analysis and remediation, you have to perform the following steps −" }, { "code": null, "e": 54829, "s": 54786, "text": "Go to Configuration tab → workflow options" }, { "code": null, "e": 54856, "s": 54829, "text": "Set the below parameters −" }, { "code": null, "e": 54894, "s": 54856, "text": "Set parameter Risk Maintenance to YES" }, { "code": null, "e": 54946, "s": 54894, "text": "Set parameter Mitigation Control Maintenance to YES" }, { "code": null, "e": 54978, "s": 54946, "text": "Set parameter Mitigation to YES" }, { "code": null, "e": 55016, "s": 54978, "text": "Set up the Workflow Web Service URL −" }, { "code": null, "e": 55101, "s": 55016, "text": "http://<server>:<port>/AEWFRequestSubmissionService_5_2/Config1?wsdl&style=document\n" }, { "code": null, "e": 55174, "s": 55101, "text": "Customize the workflows need to be performed inside the Workflow Engine." }, { "code": null, "e": 55261, "s": 55174, "text": "When you maintain a risk or a control is in SAP GRC, you perform the following steps −" }, { "code": null, "e": 55354, "s": 55261, "text": "Step 1 − In Access Control, a workflow is triggered to perform a risk or a control workflow." }, { "code": null, "e": 55447, "s": 55354, "text": "Step 2 − When you get the required approvals, approval steps depend on customer requirement." }, { "code": null, "e": 55518, "s": 55447, "text": "Step 3 − Get an audit trail documenting the complete approval process." }, { "code": null, "e": 55804, "s": 55518, "text": "Using SAP GRC Global Trade Services, you can improve cross-border supply chain of goods in an organization. This application allows you to automate the trade processes and helps you to control the cost and reduce the risk of penalties and also to manage inbound and outbound processes." }, { "code": null, "e": 55923, "s": 55804, "text": "Using GTS, you can create centralize single repository that is used to contain all compliance master data and content." }, { "code": null, "e": 55993, "s": 55923, "text": "The following are the key advantages of using Global Trade Services −" }, { "code": null, "e": 56077, "s": 55993, "text": "It helps in reducing the cost and effort of managing compliance for global trading." }, { "code": null, "e": 56161, "s": 56077, "text": "It helps in reducing the cost and effort of managing compliance for global trading." }, { "code": null, "e": 56238, "s": 56161, "text": "It can ease time-consuming manual tasks and helps in improving productivity." }, { "code": null, "e": 56315, "s": 56238, "text": "It can ease time-consuming manual tasks and helps in improving productivity." }, { "code": null, "e": 56370, "s": 56315, "text": "Reduces the penalties for trade compliance violations." }, { "code": null, "e": 56425, "s": 56370, "text": "Reduces the penalties for trade compliance violations." }, { "code": null, "e": 56531, "s": 56425, "text": "It helps you to create and improve the brand and image and avoid trade with sanctioned or denied parties." }, { "code": null, "e": 56637, "s": 56531, "text": "It helps you to create and improve the brand and image and avoid trade with sanctioned or denied parties." }, { "code": null, "e": 56710, "s": 56637, "text": "Paves way for customer satisfaction and improves the quality of service." }, { "code": null, "e": 56783, "s": 56710, "text": "Paves way for customer satisfaction and improves the quality of service." }, { "code": null, "e": 56908, "s": 56783, "text": "It fastens the inbound and outbound processes by performing customs clearance and also helps in removing unnecessary delays." }, { "code": null, "e": 57033, "s": 56908, "text": "It fastens the inbound and outbound processes by performing customs clearance and also helps in removing unnecessary delays." }, { "code": null, "e": 57146, "s": 57033, "text": "The following illustration shows the process flow of integration between SAP ERP and SAP Global Trade Services −" }, { "code": null, "e": 57279, "s": 57146, "text": "When you install SAP GRC, there are various configuration and settings that you need to perform in GRC. The key activities include −" }, { "code": null, "e": 57306, "s": 57279, "text": "Creating connectors in GRC" }, { "code": null, "e": 57333, "s": 57306, "text": "Creating connectors in GRC" }, { "code": null, "e": 57371, "s": 57333, "text": "Configuring AMF to use the connectors" }, { "code": null, "e": 57409, "s": 57371, "text": "Configuring AMF to use the connectors" }, { "code": null, "e": 57438, "s": 57409, "text": "Creating callback connectors" }, { "code": null, "e": 57467, "s": 57438, "text": "Creating callback connectors" }, { "code": null, "e": 57562, "s": 57467, "text": "Creating connections in GRC is standard process of creating RFC connection using T-Code − SM59" }, { "code": null, "e": 57657, "s": 57562, "text": "Creating connections in GRC is standard process of creating RFC connection using T-Code − SM59" }, { "code": null, "e": 57740, "s": 57657, "text": "SAP GRC is available in SAP Easy Access → under Governance Risk Compliance folder." }, { "code": null, "e": 57797, "s": 57740, "text": "Step 1 − Open SAP Easy access menu and use T-Code − SPRO" }, { "code": null, "e": 57940, "s": 57797, "text": "Step 2 − Go to Governance, Risk and Compliance under SAP Reference IMG → Common Component Settings → Integration Framework → Create Connectors" }, { "code": null, "e": 58008, "s": 57940, "text": "Step 3 − Create connector is shortcut for creating SM59 connection." }, { "code": null, "e": 58095, "s": 58008, "text": "Step 4 − To see existing connections, go to Maintain Connectors and Connection Types −" }, { "code": null, "e": 58216, "s": 58095, "text": "You can see connector types as shown below. These connector types can be used for configuration for different purposes −" }, { "code": null, "e": 58364, "s": 58216, "text": "Local system connectors are used to integrate with the SAP BusinessObjects Access Control application for monitoring segregation of duty violations" }, { "code": null, "e": 58512, "s": 58364, "text": "Local system connectors are used to integrate with the SAP BusinessObjects Access Control application for monitoring segregation of duty violations" }, { "code": null, "e": 58592, "s": 58512, "text": "Web service connectors are used for external partner data sources (see section)" }, { "code": null, "e": 58672, "s": 58592, "text": "Web service connectors are used for external partner data sources (see section)" }, { "code": null, "e": 58723, "s": 58672, "text": "SAP system connectors are used in all other cases." }, { "code": null, "e": 58774, "s": 58723, "text": "SAP system connectors are used in all other cases." }, { "code": null, "e": 58822, "s": 58774, "text": "Step 5 − Go to Connection Type Definition tab −" }, { "code": null, "e": 58940, "s": 58822, "text": "Step 6 − Define which of the connectors previously defined in SM59 can be used in monitoring. Go to define Connectors" }, { "code": null, "e": 59067, "s": 58940, "text": "Step 7 − In the screen you can see a connector name — SMEA5_100. This is a connector which shows a connector to an ECC system." }, { "code": null, "e": 59240, "s": 59067, "text": "The third column that lists the name of a connector which is defined in the monitored system, and which is configured to point back to the GRC system being configured here." }, { "code": null, "e": 59417, "s": 59240, "text": "SMEA5_100 is another connector in the GRC system and it points to an ERP system which is to be monitored. SM2 is a connector on the ECC system and it points back to GRC system." }, { "code": null, "e": 59474, "s": 59417, "text": "Step 8 − Define Connector Group Screen on the left side." }, { "code": null, "e": 59705, "s": 59474, "text": "Step 9 − Here you have to ensure that all the connector configurations for automated monitoring should belong to the configuration group called Automated Monitoring as shown above under define automated monitoring connector group." }, { "code": null, "e": 59776, "s": 59705, "text": "Step 10 − Go to assign connectors to connector group on the left side." }, { "code": null, "e": 59867, "s": 59776, "text": "Step 11 − Assign the connector to AM connector group as mentioned in the above screenshot." }, { "code": null, "e": 59957, "s": 59867, "text": "Step 12 − Go to Maintain Connection Settings in main menu as in the following screenshot." }, { "code": null, "e": 60062, "s": 59957, "text": "Step 13 − You need to enter the integration scenario you want, enter AM as in the following screenshot −" }, { "code": null, "e": 60205, "s": 60062, "text": "Step 14 − Click on the green tick mark as shown in the above screenshot; you will be directed to the following screen with nine sub-scenarios." }, { "code": null, "e": 60375, "s": 60205, "text": "The highlighted box shows nine entries called sub-scenarios and they represent the different types of data sources and business rules supported under Process Control 10." }, { "code": null, "e": 60484, "s": 60375, "text": "Step 15 − For the System to be monitored, you need to link the corresponding connector to that sub-scenario." }, { "code": null, "e": 60614, "s": 60484, "text": "Step 16 − Select the sub-scenario you want configurable and then choose Scenario Connector Link in the left side as shown below −" }, { "code": null, "e": 60671, "s": 60614, "text": "Step 17 − You will be directed to the following screen −" }, { "code": null, "e": 60783, "s": 60671, "text": "Step 18 − Now the connector you want to use for that scenario is not already in the list for that sub-scenario," }, { "code": null, "e": 60841, "s": 60783, "text": "You can click on New Entries button at the top to add it." }, { "code": null, "e": 61073, "s": 60841, "text": "You can follow these recommendations to add subscenarios −\n\nABAP Applications − ABAP report, SAP query, configurable program\nSAP BW − BW query\nNon SAP System − External Partner\nProcess Integrator − PI\nGRC System − SoD integration\n\n" }, { "code": null, "e": 61138, "s": 61073, "text": "ABAP Applications − ABAP report, SAP query, configurable program" }, { "code": null, "e": 61156, "s": 61138, "text": "SAP BW − BW query" }, { "code": null, "e": 61190, "s": 61156, "text": "Non SAP System − External Partner" }, { "code": null, "e": 61214, "s": 61190, "text": "Process Integrator − PI" }, { "code": null, "e": 61243, "s": 61214, "text": "GRC System − SoD integration" }, { "code": null, "e": 61386, "s": 61243, "text": "In SAP GRC Process Control, you can create data sources. Here, the design time user interfaces are under Rule Setup option in Business client." }, { "code": null, "e": 61481, "s": 61386, "text": "Go to continuous monitoring section where you can find Data Sources and Business Rules option." }, { "code": null, "e": 61542, "s": 61481, "text": "To create a new Data Source, click on Data Sources → Create." }, { "code": null, "e": 61621, "s": 61542, "text": "In the next field, you can see three different tabs to define the data source." }, { "code": null, "e": 61633, "s": 61621, "text": "General Tab" }, { "code": null, "e": 61646, "s": 61633, "text": "Object Field" }, { "code": null, "e": 61666, "s": 61646, "text": "Link and Attachment" }, { "code": null, "e": 61712, "s": 61666, "text": "In General tab, enter the following details −" }, { "code": null, "e": 61732, "s": 61712, "text": "Name of data source" }, { "code": null, "e": 61766, "s": 61732, "text": "Start date of the validity period" }, { "code": null, "e": 61798, "s": 61766, "text": "End date of the validity period" }, { "code": null, "e": 61805, "s": 61798, "text": "Status" }, { "code": null, "e": 61859, "s": 61805, "text": "Go to Object Field tab, select the following fields −" }, { "code": null, "e": 62107, "s": 61859, "text": "In SAP GRC 10.0, you can use Business Rules to filter the data stream that is coming from the data sources and you can apply the user configured conditions/calculations against that data to determine if there is a problem which requires attention." }, { "code": null, "e": 62170, "s": 62107, "text": "The Business Rule type purely depends on the Data Source type." }, { "code": null, "e": 62209, "s": 62170, "text": "Go to Business Rules under Rule Setup." }, { "code": null, "e": 62323, "s": 62209, "text": "To create new business rules, there is a list of steps that you need to follow with few of the Data Source types." }, { "code": null, "e": 62514, "s": 62323, "text": "You need to define details in each tab. For example, in the General tab, you need to enter the basic information about business rule. Business rule gives you data to filter the deficiencies." }, { "code": null, "e": 62581, "s": 62514, "text": "In Data for Analysis tab, you will see a list of available fields." }, { "code": null, "e": 62696, "s": 62581, "text": "Go to filter criterial to pass the filter condition on available objects. You can select from different operators." }, { "code": null, "e": 62851, "s": 62696, "text": "When you define all the steps, you have an option to save the rule. If you want to apply the rule to Process Control, you can do by clicking Apply button." }, { "code": null, "e": 62971, "s": 62851, "text": "To assign business rule to a process control, go to Business rule assignment under Continuous Monitoring in Rule Setup." }, { "code": null, "e": 63033, "s": 62971, "text": "Select the control and search for the Business rule to apply." } ]
Features of C++ 17
20 Nov, 2021 C++17 enables writing simple, clearer, and more expressive code. Some of the features introduced in C++17 are: Nested Namespaces Variable declaration in if and switch if constexpr statement Structured bindings Fold Expressions Direct list initialization of enums Namespaces are a very convenient tool to organize and to structure the code base, putting together components like classes and functions that logically belong to the same group. Let’s consider a hypothetical code base of a video game engine. Here, defined a namespace for the whole game engine, so all the classes and the functions implemented in this Game Engine will be declared under this common namespace. To do more clear definitions you can define another namespace under the global namespace lets say Graphics which is a sub-namespace, now put all classes that perform graphics operations under that namespace and so on. Before C++17:Below is the syntax used for nested namespace: C++ // Below is the syntax for using// the nested namespace namespace Game { namespace Graphics { namespace Physics { class 2D { .......... }; } }} When C++17: Before C++17 you have to use this verbose syntax for declaring classes in nested namespaces, but C++17 has introduced a new feature that makes it possible to open nested namespaces without this hectic syntax that require repeated namespace keyword and keeping track of opening and closing braces. In C++17 there a simple and concise syntax using double colons to introduce nested namespaces. The syntax is as follows: C++ // Below is the syntax to use the// nested namespace in one line namespace Game::Graphics::Physics { class 2D { .......... };} This makes the code less error-prone as there is no need to pay attention to several levels of braces. Before C++17: Suppose a vector of strings and you want to replace a string “abc” with “$$$” if it is present in the vector. To do that you can invoke the standard find() function to search for an item in a vector as shown below: C++ // Below is the approach for replace// any string with another string// in vector of string vector<string> str // Find and replace abc with $$$ const auto it = find(begin(str), end(str), "abc"); if (it != end(str)) { *it = "$$$"; } Explanation: The find algorithm will return an iterator pointing to the matched string. Now, if again we want to replace another string with some other string in the same vector, then for this, follow the same approach as shown above, and as you will repeat the same code to just have to change the name of the iterator to something else. As declaring more than two iterators with the same name in the same scope will give a compilation error. The name changing option will work but if there are several strings that need to be replaced, but this approach is not efficient. When C++17: For dealing with such cases C++17 gives a better option by declaring variables inside if statements as shown below: C++ // Below is the syntax for replacing a// string in vector of string in C++17 if (const auto it = find(begin(str), end(str), "abc"); it != end(str)) { *it = "$$$";} Now the scope of the iterator “it” is within the if statement itself, and the same iterator name can be used to replace other strings too.The same thing can be done using a switch statement to using the syntax given below: switch (initial-statement; variable) { .... // Cases } Below is the program that replaces some defined strings in the given vector that runs only in C++17: C++ // C++ 17 code to demonstrate if constexpr #include <algorithm>#include <iostream>#include <string>#include <vector>using namespace std; // Helper function to print content// of string vectorvoid print(const string& str, const vector<string>& vec){ cout << str; for (const auto& i : vec) { cout << i << " "; } cout << endl;} // Driver Codeint main(){ // Declare vector of string vector<string> vec{ "abc", "xyz", "def", "ghi" }; // Invoke print helper function print("Initial vector: ", vec); // abc -> $$$, and the scope of "it" // Function invoked for passing // iterators from begin to end if (const auto it = find(begin(vec), end(vec), "abc"); // Check if the iterator reaches // to the end or not it != end(vec)) { // Replace the string if an // iterator doesn't reach end *it = "$$$"; } // def -> ### // Replace another string using // the same iterator name if (const auto it = find(begin(vec), end(vec), "def"); it != end(vec)) { *it = "###"; } print("Final vector: ", vec); return 0;} Output: This feature of C++ 17 is very useful when you write template code. The normal if statement condition is executed at run time, so C++17 introduced this new if constexpr statement. The main difference is that if constexpr is evaluated at compile time. Basically, constexpr function is evaluated at compile-time. So why is this important, its main importance goes with template code. Before C++17: Suppose, to compare if an integer variable with a value, then declare and initialize that integer at compile time only before using that variable as shown below: C++ // Below is the syntax for using// If-else statement int x = 5; // Conditionif (x == 5) { // Do something}else { // Do something else} When C++17: Suppose you have some template that operates on some generic type T. C++ // Below is the generic code for// using If else statement template <typename T> // Function template for illustrating// if else statementauto func(T const &value){ if constexpr(T is integer) { // Do something } else { // Something else }} So one aspect of constexpr is that now the compiler knows if T is an integer or not, and the compiler considers only the substatement that satisfies the condition so only that block of code is compiled and the C++ compiler ignores the other substatements. Below is the program for the same: C++ // C++ 17 code to demonstrate error// generated using if statement #include <iostream>#include <string>#include <type_traits>using namespace std; // Template Classtemplate <typename T>auto length(T const& value){ // Check the condition with if // statement whether T is an // integer or not if (is_integral<T>::value) { return value; } else { return value.length(); }} // Driver Codeint main(){ int n{ 10 }; string s{ "abc" }; cout << "n = " << n << " and length = " << length(n) << endl; cout << "s = " << s << " and length = " << length(s) << endl;} Output: error: request for member 'length' in 'value', which is of non-class type 'const int' Explanation: In the above code, if the program is compiled then it will give a compilation error because integer has no function called length(), and as we have used only if statement the whole code will be compiled and will give an error. To avoid this kind of error i.e., consider only the code that is important C++17 is for the rescue. So on replacing if with if constexpr, if T is an integer, then only the condition under if constexpr will be compiled (as it satisfies the condition of T to be an integer) and not the else part which contains the length() function (that produced an error). The else block will be considered only when T is not an integer, for example, strings, as it has length() function it will not produce an error and will print length of the string. Below is the correct code: C++ // C++ 17 code to demonstrate if constexpr #include <iostream>#include <string>#include <type_traits>using namespace std; // Template Classtemplate <typename T>auto length(T const& value){ // Check the condition with if // statement whether T is an // integer or not if constexpr(is_integral<T>::value) { return value; } else { return value.length(); }} // Driver Codeint main(){ int n{ 10 }; string s{ "abc" }; cout << "n = " << n << " and length = " << length(n) << endl; cout << "s = " << s << " and length = " << length(s) << endl;} Output: It basically allows you to declare multiple variables that are initialized with values from pairs, generic tuples or from custom structures and these multiples variable declarations happens in single statements. Before C++17: Before C++17, std::tie was used to declare multiple variables that are initialized with values from custom structures. C++ // Using tupleint a, b, c;std::tie(a, b, c) = std::make_tuple(1, 2, 3); When C++17: Suppose you have a dictionary having names as keys and their favorite language as values and this is implemented using standard container map and you want to insert a new entry to it using insert method. This insert method returns an std::pair containing two pieces of information, the first item in the pair is an iterator and the second item is a boolean value. C++ // Below is the code to use// structure binding in C++17map<string, string> fav_lang{ { "John", "Java" }, { "Alex", "C++" }, { "Peter", "Python" }}; auto result = fav_lang.insert({ "Henry", "Golang" }); There are two cases to consider here: Whether new is not present in the dictionary or it is already present. If the new association (key-value pair) is not present in the dictionary, it gets inserted. So in this case, the returned pair contains an iterator pointing to the new element and the boolean value becomes True. If the new key is already present then the iterator points to the existing key and boolean value becomes False. Now to write the code to inspect the boolean flag and insertion iterator, first write .first and .second to access elements in pair. C++ 17 can do better for this as: Using C++ 17 structure bindings to declare and initialize two variables with more meaningful names than first and second. Using the names position and success is much clearer than using first and second. The meaning of position and success is very straightforward i.e., position tells about where the iterator is and success tells whether the element is inserted or not. Below is the program for the same: C++ // C++ 17 program to demonstrate// Structure Bindings #include <iostream>#include <map>#include <string>using namespace std; // Driver Codeint main(){ // Key-value pair declared inside // Map data structure map<string, string> fav_lang{ { "John", "Java" }, { "Alex", "C++" }, { "Peter", "Python" } }; // Structure binding concept used // position and success are used // in place of first and second auto[process, success] = fav_lang.insert({ "Henry", "Golang" }); // Check boolean value of success if (success) { cout << "Insertion done!!" << endl; } // Iterate over map for (const auto & [ name, lang ] : fav_lang) { cout << name << ":" << lang << endl; } return 0;} Output: C++11 gave the option of variadic templates to work with variable number of input arguments. Fold expressions are a new way to unpack variadic parameters with operators. The syntax is as follows: (pack op ...) (... op pack) (pack op ... op init) (init op ... op pack) where pack represents an unexpanded parameter pack, op represents an operator and init represents a value. (pack op ...): This is a right fold that is expanded like pack1 op (... op (packN-1 op packN)). (... op pack): This is a left fold that is expanded like ((pack1 op pack2) op ...) op packN. (pack op ... op init): This is a binary right fold that is expanded like pack1 op (... op (packN-1 op (packN op init))). (init op ... op pack): This is a binary left fold that is expanded like (((init op pack1) op pack2) op ...) op packN. Before C++17: To make a function that takes variable number of arguments and returns the sum of arguments. C++ // Below is the function that implements// folding expressions using variable// number of arguments int sum(int num, ...){ va_list valist; int s = 0, i; va_start(valist, num); for (i = 0; i < num; i++) s += va_arg(valist, int); va_end(valist); return s;} When C++17:To implement a recursive function like sum etc through variadic templates, this becomes efficient with C++17 which is better than C++11 implementations. Below is the template class of the same: C++ // Template for performing the// recursion using variadic template auto C11_sum(){ return 0;} // Template Classtemplate<typename T1, typename... T>auto C11_sum(T1 s, T... ts){ return s + C11_sum(ts...);} Below is the program to illustrate the same: C++ // C++ program to illustrate the// folding expression in C++17 #include <iostream>#include <string>using namespace std; // Template Classtemplate<typename... Args>auto sum(Args... args){ return (args + ... + 0);} template <typename... Args>auto sum2(Args... args){ return (args + ...);} // Driver Codeint main(){ // Function Calls cout << sum(11, 22, 33, 44, 55) << "\n"; cout << sum2(11, 22, 33, 44, 55) << "\n"; return 0;} Output: In C++ 17 initialize initialization of enums using braces is allowed. Below is the syntax for the same: enum byte : unsigned char {}; byte b {0}; // OK byte c {-1}; // ERROR byte d = byte{1}; // OK byte e = byte{256}; // ERROR Some of the library features of C++17: std::byte{b}: It is a unique type that applies the concept of byte as specified in the C++ language definition. A byte is a collection of bits and only bitwise operators can be used in this case. Below is the program to illustrate the same: C++ // Program to illustrate std::byte// in the C++ 17 #include <cstddef>#include <iostream>using namespace std; // Function to print byte avoid Print(const byte& a){ cout << to_integer<int>(a) << endl;} // Driver Codeint main(){ byte b{ 5 }; // Print byte Print(b); // A 2-bit left shift b <<= 2; // Print byte Print(b); // Initialize two new bytes using // binary literals byte b1{ 0b1100 }; byte b2{ 0b1010 }; Print(b1); Print(b2); // Bit-wise OR and AND operations byte byteOr = b1 | b2; byte byteAnd = b1 & b2; // Print byte Print(byteOr); Print(byteAnd); return 0;} Output: std::filesystem(): It provides a standard way to manipulate directories and files. In the below example a file a copied to a temporary path if there is available space. Below is the template for the same: C++ // For manipulating the file// directories const auto FilePath {"FileToCopy"}; // If any filepath existsif(filesystem::exists(FilePath)) { const auto FileSize { filesystem::file_size(FilePath) }; filesystem::path tmpPath {"/tmp"}; // If filepath is available or not if(filesystem::space(tmpPath) .available > FileSize) { // Create Directory filesystem::create_directory( tmpPath.append("example")); // Copy File to file path filesystem::copy_file(FilePath, tmpPath.append("newFile")); }} std::apply(): Its parameters are a callable object which is to be invoked and a tuple whose elements need to be used as arguments. Below is the template for the same: C++ // Function that adds two numbers auto add = [](int a, int b) { return a + b;}; apply(add, std::make_tuple(11, 22)); std::any(): The class any describes a type-safe container for single values of any type.The non-member any cast functions provide type-safe access to the contained object. rajeev0719singh surinderdawra388 C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Bitwise Operators in C/C++ Set in C++ Standard Template Library (STL) vector erase() and clear() in C++ unordered_map in C++ STL Inheritance in C++ Priority Queue in C++ Standard Template Library (STL) The C++ Standard Template Library (STL) Sorting a vector in C++ Substring in C++ C++ Classes and Objects
[ { "code": null, "e": 52, "s": 24, "text": "\n20 Nov, 2021" }, { "code": null, "e": 164, "s": 52, "text": "C++17 enables writing simple, clearer, and more expressive code. Some of the features introduced in C++17 are: " }, { "code": null, "e": 182, "s": 164, "text": "Nested Namespaces" }, { "code": null, "e": 220, "s": 182, "text": "Variable declaration in if and switch" }, { "code": null, "e": 243, "s": 220, "text": "if constexpr statement" }, { "code": null, "e": 263, "s": 243, "text": "Structured bindings" }, { "code": null, "e": 280, "s": 263, "text": "Fold Expressions" }, { "code": null, "e": 316, "s": 280, "text": "Direct list initialization of enums" }, { "code": null, "e": 494, "s": 316, "text": "Namespaces are a very convenient tool to organize and to structure the code base, putting together components like classes and functions that logically belong to the same group." }, { "code": null, "e": 945, "s": 494, "text": "Let’s consider a hypothetical code base of a video game engine. Here, defined a namespace for the whole game engine, so all the classes and the functions implemented in this Game Engine will be declared under this common namespace. To do more clear definitions you can define another namespace under the global namespace lets say Graphics which is a sub-namespace, now put all classes that perform graphics operations under that namespace and so on. " }, { "code": null, "e": 1005, "s": 945, "text": "Before C++17:Below is the syntax used for nested namespace:" }, { "code": null, "e": 1009, "s": 1005, "text": "C++" }, { "code": "// Below is the syntax for using// the nested namespace namespace Game { namespace Graphics { namespace Physics { class 2D { .......... }; } }}", "e": 1209, "s": 1009, "text": null }, { "code": null, "e": 1221, "s": 1209, "text": "When C++17:" }, { "code": null, "e": 1639, "s": 1221, "text": "Before C++17 you have to use this verbose syntax for declaring classes in nested namespaces, but C++17 has introduced a new feature that makes it possible to open nested namespaces without this hectic syntax that require repeated namespace keyword and keeping track of opening and closing braces. In C++17 there a simple and concise syntax using double colons to introduce nested namespaces. The syntax is as follows:" }, { "code": null, "e": 1643, "s": 1639, "text": "C++" }, { "code": "// Below is the syntax to use the// nested namespace in one line namespace Game::Graphics::Physics { class 2D { .......... };}", "e": 1783, "s": 1643, "text": null }, { "code": null, "e": 1886, "s": 1783, "text": "This makes the code less error-prone as there is no need to pay attention to several levels of braces." }, { "code": null, "e": 1900, "s": 1886, "text": "Before C++17:" }, { "code": null, "e": 2115, "s": 1900, "text": "Suppose a vector of strings and you want to replace a string “abc” with “$$$” if it is present in the vector. To do that you can invoke the standard find() function to search for an item in a vector as shown below:" }, { "code": null, "e": 2119, "s": 2115, "text": "C++" }, { "code": "// Below is the approach for replace// any string with another string// in vector of string vector<string> str // Find and replace abc with $$$ const auto it = find(begin(str), end(str), \"abc\"); if (it != end(str)) { *it = \"$$$\"; }", "e": 2374, "s": 2119, "text": null }, { "code": null, "e": 2388, "s": 2374, "text": "Explanation: " }, { "code": null, "e": 2463, "s": 2388, "text": "The find algorithm will return an iterator pointing to the matched string." }, { "code": null, "e": 2714, "s": 2463, "text": "Now, if again we want to replace another string with some other string in the same vector, then for this, follow the same approach as shown above, and as you will repeat the same code to just have to change the name of the iterator to something else." }, { "code": null, "e": 2949, "s": 2714, "text": "As declaring more than two iterators with the same name in the same scope will give a compilation error. The name changing option will work but if there are several strings that need to be replaced, but this approach is not efficient." }, { "code": null, "e": 3077, "s": 2949, "text": "When C++17: For dealing with such cases C++17 gives a better option by declaring variables inside if statements as shown below:" }, { "code": null, "e": 3081, "s": 3077, "text": "C++" }, { "code": "// Below is the syntax for replacing a// string in vector of string in C++17 if (const auto it = find(begin(str), end(str), \"abc\"); it != end(str)) { *it = \"$$$\";}", "e": 3299, "s": 3081, "text": null }, { "code": null, "e": 3522, "s": 3299, "text": "Now the scope of the iterator “it” is within the if statement itself, and the same iterator name can be used to replace other strings too.The same thing can be done using a switch statement to using the syntax given below:" }, { "code": null, "e": 3581, "s": 3522, "text": "switch (initial-statement; variable) {\n ....\n // Cases\n}" }, { "code": null, "e": 3682, "s": 3581, "text": "Below is the program that replaces some defined strings in the given vector that runs only in C++17:" }, { "code": null, "e": 3686, "s": 3682, "text": "C++" }, { "code": "// C++ 17 code to demonstrate if constexpr #include <algorithm>#include <iostream>#include <string>#include <vector>using namespace std; // Helper function to print content// of string vectorvoid print(const string& str, const vector<string>& vec){ cout << str; for (const auto& i : vec) { cout << i << \" \"; } cout << endl;} // Driver Codeint main(){ // Declare vector of string vector<string> vec{ \"abc\", \"xyz\", \"def\", \"ghi\" }; // Invoke print helper function print(\"Initial vector: \", vec); // abc -> $$$, and the scope of \"it\" // Function invoked for passing // iterators from begin to end if (const auto it = find(begin(vec), end(vec), \"abc\"); // Check if the iterator reaches // to the end or not it != end(vec)) { // Replace the string if an // iterator doesn't reach end *it = \"$$$\"; } // def -> ### // Replace another string using // the same iterator name if (const auto it = find(begin(vec), end(vec), \"def\"); it != end(vec)) { *it = \"###\"; } print(\"Final vector: \", vec); return 0;}", "e": 4910, "s": 3686, "text": null }, { "code": null, "e": 4918, "s": 4910, "text": "Output:" }, { "code": null, "e": 5300, "s": 4918, "text": "This feature of C++ 17 is very useful when you write template code. The normal if statement condition is executed at run time, so C++17 introduced this new if constexpr statement. The main difference is that if constexpr is evaluated at compile time. Basically, constexpr function is evaluated at compile-time. So why is this important, its main importance goes with template code." }, { "code": null, "e": 5476, "s": 5300, "text": "Before C++17: Suppose, to compare if an integer variable with a value, then declare and initialize that integer at compile time only before using that variable as shown below:" }, { "code": null, "e": 5480, "s": 5476, "text": "C++" }, { "code": "// Below is the syntax for using// If-else statement int x = 5; // Conditionif (x == 5) { // Do something}else { // Do something else}", "e": 5621, "s": 5480, "text": null }, { "code": null, "e": 5633, "s": 5621, "text": "When C++17:" }, { "code": null, "e": 5702, "s": 5633, "text": "Suppose you have some template that operates on some generic type T." }, { "code": null, "e": 5706, "s": 5702, "text": "C++" }, { "code": "// Below is the generic code for// using If else statement template <typename T> // Function template for illustrating// if else statementauto func(T const &value){ if constexpr(T is integer) { // Do something } else { // Something else }}", "e": 5994, "s": 5706, "text": null }, { "code": null, "e": 6250, "s": 5994, "text": "So one aspect of constexpr is that now the compiler knows if T is an integer or not, and the compiler considers only the substatement that satisfies the condition so only that block of code is compiled and the C++ compiler ignores the other substatements." }, { "code": null, "e": 6285, "s": 6250, "text": "Below is the program for the same:" }, { "code": null, "e": 6289, "s": 6285, "text": "C++" }, { "code": "// C++ 17 code to demonstrate error// generated using if statement #include <iostream>#include <string>#include <type_traits>using namespace std; // Template Classtemplate <typename T>auto length(T const& value){ // Check the condition with if // statement whether T is an // integer or not if (is_integral<T>::value) { return value; } else { return value.length(); }} // Driver Codeint main(){ int n{ 10 }; string s{ \"abc\" }; cout << \"n = \" << n << \" and length = \" << length(n) << endl; cout << \"s = \" << s << \" and length = \" << length(s) << endl;}", "e": 6924, "s": 6289, "text": null }, { "code": null, "e": 6932, "s": 6924, "text": "Output:" }, { "code": null, "e": 7018, "s": 6932, "text": "error: request for member 'length' in 'value', which is of non-class type 'const int'" }, { "code": null, "e": 7032, "s": 7018, "text": "Explanation: " }, { "code": null, "e": 7259, "s": 7032, "text": "In the above code, if the program is compiled then it will give a compilation error because integer has no function called length(), and as we have used only if statement the whole code will be compiled and will give an error." }, { "code": null, "e": 7359, "s": 7259, "text": "To avoid this kind of error i.e., consider only the code that is important C++17 is for the rescue." }, { "code": null, "e": 7617, "s": 7359, "text": "So on replacing if with if constexpr, if T is an integer, then only the condition under if constexpr will be compiled (as it satisfies the condition of T to be an integer) and not the else part which contains the length() function (that produced an error)." }, { "code": null, "e": 7798, "s": 7617, "text": "The else block will be considered only when T is not an integer, for example, strings, as it has length() function it will not produce an error and will print length of the string." }, { "code": null, "e": 7825, "s": 7798, "text": "Below is the correct code:" }, { "code": null, "e": 7829, "s": 7825, "text": "C++" }, { "code": "// C++ 17 code to demonstrate if constexpr #include <iostream>#include <string>#include <type_traits>using namespace std; // Template Classtemplate <typename T>auto length(T const& value){ // Check the condition with if // statement whether T is an // integer or not if constexpr(is_integral<T>::value) { return value; } else { return value.length(); }} // Driver Codeint main(){ int n{ 10 }; string s{ \"abc\" }; cout << \"n = \" << n << \" and length = \" << length(n) << endl; cout << \"s = \" << s << \" and length = \" << length(s) << endl;}", "e": 8478, "s": 7829, "text": null }, { "code": null, "e": 8486, "s": 8478, "text": "Output:" }, { "code": null, "e": 8698, "s": 8486, "text": "It basically allows you to declare multiple variables that are initialized with values from pairs, generic tuples or from custom structures and these multiples variable declarations happens in single statements." }, { "code": null, "e": 8712, "s": 8698, "text": "Before C++17:" }, { "code": null, "e": 8831, "s": 8712, "text": "Before C++17, std::tie was used to declare multiple variables that are initialized with values from custom structures." }, { "code": null, "e": 8835, "s": 8831, "text": "C++" }, { "code": "// Using tupleint a, b, c;std::tie(a, b, c) = std::make_tuple(1, 2, 3);", "e": 8907, "s": 8835, "text": null }, { "code": null, "e": 8919, "s": 8907, "text": "When C++17:" }, { "code": null, "e": 9283, "s": 8919, "text": "Suppose you have a dictionary having names as keys and their favorite language as values and this is implemented using standard container map and you want to insert a new entry to it using insert method. This insert method returns an std::pair containing two pieces of information, the first item in the pair is an iterator and the second item is a boolean value." }, { "code": null, "e": 9287, "s": 9283, "text": "C++" }, { "code": "// Below is the code to use// structure binding in C++17map<string, string> fav_lang{ { \"John\", \"Java\" }, { \"Alex\", \"C++\" }, { \"Peter\", \"Python\" }}; auto result = fav_lang.insert({ \"Henry\", \"Golang\" });", "e": 9523, "s": 9287, "text": null }, { "code": null, "e": 9562, "s": 9523, "text": "There are two cases to consider here: " }, { "code": null, "e": 9845, "s": 9562, "text": "Whether new is not present in the dictionary or it is already present. If the new association (key-value pair) is not present in the dictionary, it gets inserted. So in this case, the returned pair contains an iterator pointing to the new element and the boolean value becomes True." }, { "code": null, "e": 9957, "s": 9845, "text": "If the new key is already present then the iterator points to the existing key and boolean value becomes False." }, { "code": null, "e": 10124, "s": 9957, "text": "Now to write the code to inspect the boolean flag and insertion iterator, first write .first and .second to access elements in pair. C++ 17 can do better for this as:" }, { "code": null, "e": 10246, "s": 10124, "text": "Using C++ 17 structure bindings to declare and initialize two variables with more meaningful names than first and second." }, { "code": null, "e": 10328, "s": 10246, "text": "Using the names position and success is much clearer than using first and second." }, { "code": null, "e": 10495, "s": 10328, "text": "The meaning of position and success is very straightforward i.e., position tells about where the iterator is and success tells whether the element is inserted or not." }, { "code": null, "e": 10530, "s": 10495, "text": "Below is the program for the same:" }, { "code": null, "e": 10534, "s": 10530, "text": "C++" }, { "code": "// C++ 17 program to demonstrate// Structure Bindings #include <iostream>#include <map>#include <string>using namespace std; // Driver Codeint main(){ // Key-value pair declared inside // Map data structure map<string, string> fav_lang{ { \"John\", \"Java\" }, { \"Alex\", \"C++\" }, { \"Peter\", \"Python\" } }; // Structure binding concept used // position and success are used // in place of first and second auto[process, success] = fav_lang.insert({ \"Henry\", \"Golang\" }); // Check boolean value of success if (success) { cout << \"Insertion done!!\" << endl; } // Iterate over map for (const auto & [ name, lang ] : fav_lang) { cout << name << \":\" << lang << endl; } return 0;}", "e": 11357, "s": 10534, "text": null }, { "code": null, "e": 11365, "s": 11357, "text": "Output:" }, { "code": null, "e": 11562, "s": 11365, "text": "C++11 gave the option of variadic templates to work with variable number of input arguments. Fold expressions are a new way to unpack variadic parameters with operators. The syntax is as follows: " }, { "code": null, "e": 11742, "s": 11562, "text": "(pack op ...) (... op pack) (pack op ... op init) (init op ... op pack) where pack represents an unexpanded parameter pack, op represents an operator and init represents a value. " }, { "code": null, "e": 11838, "s": 11742, "text": "(pack op ...): This is a right fold that is expanded like pack1 op (... op (packN-1 op packN))." }, { "code": null, "e": 11931, "s": 11838, "text": "(... op pack): This is a left fold that is expanded like ((pack1 op pack2) op ...) op packN." }, { "code": null, "e": 12052, "s": 11931, "text": "(pack op ... op init): This is a binary right fold that is expanded like pack1 op (... op (packN-1 op (packN op init)))." }, { "code": null, "e": 12170, "s": 12052, "text": "(init op ... op pack): This is a binary left fold that is expanded like (((init op pack1) op pack2) op ...) op packN." }, { "code": null, "e": 12277, "s": 12170, "text": "Before C++17: To make a function that takes variable number of arguments and returns the sum of arguments." }, { "code": null, "e": 12281, "s": 12277, "text": "C++" }, { "code": "// Below is the function that implements// folding expressions using variable// number of arguments int sum(int num, ...){ va_list valist; int s = 0, i; va_start(valist, num); for (i = 0; i < num; i++) s += va_arg(valist, int); va_end(valist); return s;}", "e": 12565, "s": 12281, "text": null }, { "code": null, "e": 12770, "s": 12565, "text": "When C++17:To implement a recursive function like sum etc through variadic templates, this becomes efficient with C++17 which is better than C++11 implementations. Below is the template class of the same:" }, { "code": null, "e": 12774, "s": 12770, "text": "C++" }, { "code": "// Template for performing the// recursion using variadic template auto C11_sum(){ return 0;} // Template Classtemplate<typename T1, typename... T>auto C11_sum(T1 s, T... ts){ return s + C11_sum(ts...);}", "e": 12984, "s": 12774, "text": null }, { "code": null, "e": 13029, "s": 12984, "text": "Below is the program to illustrate the same:" }, { "code": null, "e": 13033, "s": 13029, "text": "C++" }, { "code": "// C++ program to illustrate the// folding expression in C++17 #include <iostream>#include <string>using namespace std; // Template Classtemplate<typename... Args>auto sum(Args... args){ return (args + ... + 0);} template <typename... Args>auto sum2(Args... args){ return (args + ...);} // Driver Codeint main(){ // Function Calls cout << sum(11, 22, 33, 44, 55) << \"\\n\"; cout << sum2(11, 22, 33, 44, 55) << \"\\n\"; return 0;}", "e": 13498, "s": 13033, "text": null }, { "code": null, "e": 13506, "s": 13498, "text": "Output:" }, { "code": null, "e": 13612, "s": 13506, "text": "In C++ 17 initialize initialization of enums using braces is allowed. Below is the syntax for the same: " }, { "code": null, "e": 13737, "s": 13612, "text": "enum byte : unsigned char {}; byte b {0}; // OK byte c {-1}; // ERROR byte d = byte{1}; // OK byte e = byte{256}; // ERROR " }, { "code": null, "e": 13777, "s": 13737, "text": "Some of the library features of C++17: " }, { "code": null, "e": 14018, "s": 13777, "text": "std::byte{b}: It is a unique type that applies the concept of byte as specified in the C++ language definition. A byte is a collection of bits and only bitwise operators can be used in this case. Below is the program to illustrate the same:" }, { "code": null, "e": 14022, "s": 14018, "text": "C++" }, { "code": "// Program to illustrate std::byte// in the C++ 17 #include <cstddef>#include <iostream>using namespace std; // Function to print byte avoid Print(const byte& a){ cout << to_integer<int>(a) << endl;} // Driver Codeint main(){ byte b{ 5 }; // Print byte Print(b); // A 2-bit left shift b <<= 2; // Print byte Print(b); // Initialize two new bytes using // binary literals byte b1{ 0b1100 }; byte b2{ 0b1010 }; Print(b1); Print(b2); // Bit-wise OR and AND operations byte byteOr = b1 | b2; byte byteAnd = b1 & b2; // Print byte Print(byteOr); Print(byteAnd); return 0;}", "e": 14660, "s": 14022, "text": null }, { "code": null, "e": 14668, "s": 14660, "text": "Output:" }, { "code": null, "e": 14873, "s": 14668, "text": "std::filesystem(): It provides a standard way to manipulate directories and files. In the below example a file a copied to a temporary path if there is available space. Below is the template for the same:" }, { "code": null, "e": 14877, "s": 14873, "text": "C++" }, { "code": "// For manipulating the file// directories const auto FilePath {\"FileToCopy\"}; // If any filepath existsif(filesystem::exists(FilePath)) { const auto FileSize { filesystem::file_size(FilePath) }; filesystem::path tmpPath {\"/tmp\"}; // If filepath is available or not if(filesystem::space(tmpPath) .available > FileSize) { // Create Directory filesystem::create_directory( tmpPath.append(\"example\")); // Copy File to file path filesystem::copy_file(FilePath, tmpPath.append(\"newFile\")); }}", "e": 15485, "s": 14877, "text": null }, { "code": null, "e": 15652, "s": 15485, "text": "std::apply(): Its parameters are a callable object which is to be invoked and a tuple whose elements need to be used as arguments. Below is the template for the same:" }, { "code": null, "e": 15656, "s": 15652, "text": "C++" }, { "code": "// Function that adds two numbers auto add = [](int a, int b) { return a + b;}; apply(add, std::make_tuple(11, 22));", "e": 15773, "s": 15656, "text": null }, { "code": null, "e": 15945, "s": 15773, "text": "std::any(): The class any describes a type-safe container for single values of any type.The non-member any cast functions provide type-safe access to the contained object." }, { "code": null, "e": 15961, "s": 15945, "text": "rajeev0719singh" }, { "code": null, "e": 15978, "s": 15961, "text": "surinderdawra388" }, { "code": null, "e": 15982, "s": 15978, "text": "C++" }, { "code": null, "e": 15986, "s": 15982, "text": "CPP" }, { "code": null, "e": 16084, "s": 15986, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 16111, "s": 16084, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 16154, "s": 16111, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 16188, "s": 16154, "text": "vector erase() and clear() in C++" }, { "code": null, "e": 16213, "s": 16188, "text": "unordered_map in C++ STL" }, { "code": null, "e": 16232, "s": 16213, "text": "Inheritance in C++" }, { "code": null, "e": 16286, "s": 16232, "text": "Priority Queue in C++ Standard Template Library (STL)" }, { "code": null, "e": 16326, "s": 16286, "text": "The C++ Standard Template Library (STL)" }, { "code": null, "e": 16350, "s": 16326, "text": "Sorting a vector in C++" }, { "code": null, "e": 16367, "s": 16350, "text": "Substring in C++" } ]
Anagram | Practice | GeeksforGeeks
Given two stringsaandbconsisting of lowercase characters. The task is to check whether two given strings are an anagram of each other or not. An anagram of a string is another string that contains the same characters, only the order of characters can be different. For example, act and tac are an anagram of each other. Example 1: Input:a = geeksforgeeks, b = forgeeksgeeks Output: YES Explanation: Both the string have samecharacters with same frequency. So, both are anagrams. Example 2: Input:a = allergy, b = allergic Output: NO Explanation:Characters in both the strings are not same, so they are not anagrams. Your Task: You don't need to read input or print anything. Your task is to complete the function isAnagram() which takes the string a and string b as input parameter and check if the two strings are an anagram of each other. The function returns true if the strings are anagram else it returns false. Note: In python, you have to return True or False. Expected Time Complexity:O(|a|+|b|). Expected Auxiliary Space:O(Number of distinct characters). Note: |s| represents the length of string s. Constraints: 1 ≤ |a|,|b| ≤ 105 0 rrodwal22in 10 hours int arr1[26] = {0}; int arr2[26] = {0}; int i = 0; int len1 = a.length(); int len2 = b.length(); while(i < len1){ char ch = a[i]; arr1[ch - 'a'] += 1; i++; } i = 0; while(i < len2){ char ch = b[i]; arr2[ch - 'a'] += 1; i++; } i = 0; while(i < 26){ if(arr1[i] != arr2[i]){ return false; } i++; } return true; +1 arpitagarwal2854 hours ago def isAnagram(self,a,b): x = sorted(a) y = sorted(b) if x ==y: return True else: return False 0 ashwanish9914 hours ago Simple And Easy JAVA Solution class Solution{ public static boolean isAnagram(String a,String b) { if(a.length() != b.length()){ return false; } char st1[] = a.toCharArray(); char st2[] = b.toCharArray(); Arrays.sort(st1); Arrays.sort(st2); if(Arrays.equals(st1, st2)){ return true; } return false; }} +1 manzoorhussain442816 hours ago Answer in Python using: def isAnagram(self,a,b): if len(a) != len(b): return False for s in set(a): if a.count(s) == b.count(s): continue else: return False return True 0 arshiavashisht0617 hours ago C++ SOLUTION (USING unordered_map) Time Complexity: linear.Auxiliary Space:O(Number of distinct characters). bool isAnagram(string a, string b){ int n = a.length(); int m = b.length(); if(m!=n) return false; unordered_map<char, int> mp ; for(int i=0; i<n; i++){ mp[a[i]]++; } for(int j=0; j<m; j++){ mp[b[j]]--; } for(auto it : mp){ if(it.second!=0) return false; } return true; } 0 carlosdegollado33322 hours ago public static boolean isAnagram(String a,String b) { if (a.length() != b.length()) { return false; } else { boolean result = true; Map<Character, Integer> hm = new HashMap<Character, Integer>(); for (int i = 0; i < a.length(); i++) { if (hm.containsKey(a.charAt(i))) { int count = hm.get(a.charAt(i)); count++; hm.put(a.charAt(i), count); } else { hm.put(a.charAt(i), 1); } } for (int k = 0; k < b.length(); k++) { if (hm.containsKey(b.charAt(k))) { int count = hm.get(b.charAt(k)); count--; hm.put(b.charAt(k), count); } else { return false; } } for (Map.Entry<Character, Integer> me : hm.entrySet()) { if (me.getValue() != 0) { return false; } } return result; } } 0 sshashikant1 day ago JAVA | HashMap T.C. - O(|a|+|b|) S.C. - O(Number of distinct characters) public static boolean isAnagram(String a,String b) { // Your code here if(a.length()!=b.length()) return false; HashMap<Character, Integer> hm = new HashMap<>(); for(char c : a.toCharArray()){ hm.put(c, hm.getOrDefault(c,0)+1); } for(char c : b.toCharArray()){ if(hm.containsKey(c)) hm.put(c, hm.get(c)-1); } for(Map.Entry e : hm.entrySet()){ if((int)e.getValue()!=0) return false; } return true; 0 negirs7xb2 days ago My Solution : bool isAnagram(string a, string b){ // Your code here string c; int lenA = a.length(); int lenB = b.length(); char letter; if (lenA == lenB){ for (int i=0;i<lenA;i++){ for(int j=0;j<lenB; j++){ if (a.at(i) == b.at(j)){ letter = a.at(i); c.append(1,letter); b.erase(b.begin() + j); lenB--; break; } } } } if (a==c){ return 1; }else{ return 0; } } 0 anshikabansal3332 days ago in this solution i have used 26 letters but the question asks for distinct elements as auxilliRY SPACE...IF SOMEONE CAN HELP? // my code bool isAnagram(string a, string b){ // Your code here int arr[26]; int barr[26]; for(int i=0;i<26;i++){ arr[i]=0; barr[i]=0; } for(int i=0;i<a.length();i++){ int t=(int)a[i]; // cout<<t; arr[t-97]++; } for(int i=0;i<b.length();i++){ int t=(int)b[i]; barr[t-97]++; } for(int i=0;i<26;i++){ if(arr[i]!=barr[i]) return false; } return true; } 0 ddttx772 days ago bool isAnagram(string a, string b) { if(a.size()!=b.size()) return false; vector<int> v(26,0); int i; for(i=0;i<a.size();i++) v[a[i]-'0'-49]++; for(i=0;i<b.size();i++) v[b[i]-'0'-49]--; for(i=0;i<v.size();i++) { if(v[i]!=0) return false; } return true; } We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab. Make sure you are not using ad-blockers. Disable browser extensions. We recommend using latest version of your browser for best experience. Avoid using static/global variables in coding problems as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases in coding problems does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
[ { "code": null, "e": 558, "s": 238, "text": "Given two stringsaandbconsisting of lowercase characters. The task is to check whether two given strings are an anagram of each other or not. An anagram of a string is another string that contains the same characters, only the order of characters can be different. For example, act and tac are an anagram of each other." }, { "code": null, "e": 569, "s": 558, "text": "Example 1:" }, { "code": null, "e": 725, "s": 569, "text": "Input:a = geeksforgeeks, b = forgeeksgeeks\nOutput: YES\nExplanation: Both the string have samecharacters with\n same frequency. So, both are anagrams." }, { "code": null, "e": 736, "s": 725, "text": "Example 2:" }, { "code": null, "e": 871, "s": 736, "text": "Input:a = allergy, b = allergic\nOutput: NO\nExplanation:Characters in both the strings are \n not same, so they are not anagrams." }, { "code": null, "e": 1172, "s": 871, "text": "Your Task:\nYou don't need to read input or print anything. Your task is to complete the function isAnagram() which takes the string a and string b as input parameter and check if the two strings are an anagram of each other. The function returns true if the strings are anagram else it returns false." }, { "code": null, "e": 1223, "s": 1172, "text": "Note: In python, you have to return True or False." }, { "code": null, "e": 1319, "s": 1223, "text": "Expected Time Complexity:O(|a|+|b|).\nExpected Auxiliary Space:O(Number of distinct characters)." }, { "code": null, "e": 1364, "s": 1319, "text": "Note: |s| represents the length of string s." }, { "code": null, "e": 1395, "s": 1364, "text": "Constraints:\n1 ≤ |a|,|b| ≤ 105" }, { "code": null, "e": 1397, "s": 1395, "text": "0" }, { "code": null, "e": 1418, "s": 1397, "text": "rrodwal22in 10 hours" }, { "code": null, "e": 1832, "s": 1418, "text": "int arr1[26] = {0}; int arr2[26] = {0}; int i = 0; int len1 = a.length(); int len2 = b.length(); while(i < len1){ char ch = a[i]; arr1[ch - 'a'] += 1; i++; } i = 0; while(i < len2){ char ch = b[i]; arr2[ch - 'a'] += 1; i++; } i = 0; while(i < 26){ if(arr1[i] != arr2[i]){ return false; } i++; } return true; " }, { "code": null, "e": 1835, "s": 1832, "text": "+1" }, { "code": null, "e": 1862, "s": 1835, "text": "arpitagarwal2854 hours ago" }, { "code": null, "e": 2000, "s": 1862, "text": "def isAnagram(self,a,b): x = sorted(a) y = sorted(b) if x ==y: return True else: return False" }, { "code": null, "e": 2002, "s": 2000, "text": "0" }, { "code": null, "e": 2026, "s": 2002, "text": "ashwanish9914 hours ago" }, { "code": null, "e": 2056, "s": 2026, "text": "Simple And Easy JAVA Solution" }, { "code": null, "e": 2421, "s": 2058, "text": "class Solution{ public static boolean isAnagram(String a,String b) { if(a.length() != b.length()){ return false; } char st1[] = a.toCharArray(); char st2[] = b.toCharArray(); Arrays.sort(st1); Arrays.sort(st2); if(Arrays.equals(st1, st2)){ return true; } return false; }}" }, { "code": null, "e": 2424, "s": 2421, "text": "+1" }, { "code": null, "e": 2455, "s": 2424, "text": "manzoorhussain442816 hours ago" }, { "code": null, "e": 2479, "s": 2455, "text": "Answer in Python using:" }, { "code": null, "e": 2716, "s": 2479, "text": "def isAnagram(self,a,b):\n if len(a) != len(b):\n return False\n for s in set(a):\n if a.count(s) == b.count(s):\n continue\n else:\n return False\n return True" }, { "code": null, "e": 2718, "s": 2716, "text": "0" }, { "code": null, "e": 2747, "s": 2718, "text": "arshiavashisht0617 hours ago" }, { "code": null, "e": 2782, "s": 2747, "text": "C++ SOLUTION (USING unordered_map)" }, { "code": null, "e": 2856, "s": 2782, "text": "Time Complexity: linear.Auxiliary Space:O(Number of distinct characters)." }, { "code": null, "e": 3261, "s": 2858, "text": "bool isAnagram(string a, string b){ int n = a.length(); int m = b.length(); if(m!=n) return false; unordered_map<char, int> mp ; for(int i=0; i<n; i++){ mp[a[i]]++; } for(int j=0; j<m; j++){ mp[b[j]]--; } for(auto it : mp){ if(it.second!=0) return false; } return true; }" }, { "code": null, "e": 3263, "s": 3261, "text": "0" }, { "code": null, "e": 3294, "s": 3263, "text": "carlosdegollado33322 hours ago" }, { "code": null, "e": 4409, "s": 3294, "text": " public static boolean isAnagram(String a,String b) { if (a.length() != b.length()) { return false; } else { boolean result = true; Map<Character, Integer> hm = new HashMap<Character, Integer>(); for (int i = 0; i < a.length(); i++) { if (hm.containsKey(a.charAt(i))) { int count = hm.get(a.charAt(i)); count++; hm.put(a.charAt(i), count); } else { hm.put(a.charAt(i), 1); } } for (int k = 0; k < b.length(); k++) { if (hm.containsKey(b.charAt(k))) { int count = hm.get(b.charAt(k)); count--; hm.put(b.charAt(k), count); } else { return false; } } for (Map.Entry<Character, Integer> me : hm.entrySet()) { if (me.getValue() != 0) { return false; } } return result; } }" }, { "code": null, "e": 4411, "s": 4409, "text": "0" }, { "code": null, "e": 4432, "s": 4411, "text": "sshashikant1 day ago" }, { "code": null, "e": 4447, "s": 4432, "text": "JAVA | HashMap" }, { "code": null, "e": 4465, "s": 4447, "text": "T.C. - O(|a|+|b|)" }, { "code": null, "e": 4505, "s": 4465, "text": "S.C. - O(Number of distinct characters)" }, { "code": null, "e": 5069, "s": 4505, "text": "public static boolean isAnagram(String a,String b)\n {\n // Your code here\n if(a.length()!=b.length())\n return false;\n \n HashMap<Character, Integer> hm = new HashMap<>();\n \n for(char c : a.toCharArray()){\n hm.put(c, hm.getOrDefault(c,0)+1);\n }\n for(char c : b.toCharArray()){\n if(hm.containsKey(c))\n hm.put(c, hm.get(c)-1);\n }\n for(Map.Entry e : hm.entrySet()){\n if((int)e.getValue()!=0)\n return false;\n }\n return true;" }, { "code": null, "e": 5071, "s": 5069, "text": "0" }, { "code": null, "e": 5091, "s": 5071, "text": "negirs7xb2 days ago" }, { "code": null, "e": 5106, "s": 5091, "text": "My Solution : " }, { "code": null, "e": 5190, "s": 5106, "text": " bool isAnagram(string a, string b){ // Your code here string c;" }, { "code": null, "e": 5242, "s": 5190, "text": " int lenA = a.length(); int lenB = b.length();" }, { "code": null, "e": 5258, "s": 5242, "text": " char letter;" }, { "code": null, "e": 5594, "s": 5258, "text": " if (lenA == lenB){ for (int i=0;i<lenA;i++){ for(int j=0;j<lenB; j++){ if (a.at(i) == b.at(j)){ letter = a.at(i); c.append(1,letter); b.erase(b.begin() + j); lenB--; break; } } } }" }, { "code": null, "e": 5664, "s": 5594, "text": " if (a==c){ return 1; }else{ return 0; } }" }, { "code": null, "e": 5666, "s": 5664, "text": "0" }, { "code": null, "e": 5693, "s": 5666, "text": "anshikabansal3332 days ago" }, { "code": null, "e": 5819, "s": 5693, "text": "in this solution i have used 26 letters but the question asks for distinct elements as auxilliRY SPACE...IF SOMEONE CAN HELP?" }, { "code": null, "e": 5832, "s": 5821, "text": "// my code" }, { "code": null, "e": 6351, "s": 5832, "text": " bool isAnagram(string a, string b){ // Your code here int arr[26]; int barr[26]; for(int i=0;i<26;i++){ arr[i]=0; barr[i]=0; } for(int i=0;i<a.length();i++){ int t=(int)a[i]; // cout<<t; arr[t-97]++; } for(int i=0;i<b.length();i++){ int t=(int)b[i]; barr[t-97]++; } for(int i=0;i<26;i++){ if(arr[i]!=barr[i]) return false; } return true;" }, { "code": null, "e": 6353, "s": 6351, "text": "}" }, { "code": null, "e": 6361, "s": 6359, "text": "0" }, { "code": null, "e": 6379, "s": 6361, "text": "ddttx772 days ago" }, { "code": null, "e": 6788, "s": 6379, "text": "\tbool isAnagram(string a, string b)\n {\n if(a.size()!=b.size())\n return false;\n \n vector<int> v(26,0);\n int i;\n for(i=0;i<a.size();i++)\n v[a[i]-'0'-49]++;\n for(i=0;i<b.size();i++)\n v[b[i]-'0'-49]--;\n for(i=0;i<v.size();i++)\n {\n if(v[i]!=0)\n return false;\n }\n return true;\n }" }, { "code": null, "e": 6934, "s": 6788, "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": 6970, "s": 6934, "text": " Login to access your submissions. " }, { "code": null, "e": 6980, "s": 6970, "text": "\nProblem\n" }, { "code": null, "e": 6990, "s": 6980, "text": "\nContest\n" }, { "code": null, "e": 7053, "s": 6990, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 7238, "s": 7053, "text": "Avoid using static/global variables in your code as your code is tested \n against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 7522, "s": 7238, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code.\n On submission, your code is tested against multiple test cases consisting of all\n possible corner cases and stress constraints." }, { "code": null, "e": 7668, "s": 7522, "text": "You can access the hints to get an idea about what is expected of you as well as\n the final solution code." }, { "code": null, "e": 7745, "s": 7668, "text": "You can view the solutions submitted by other users from the submission tab." }, { "code": null, "e": 7786, "s": 7745, "text": "Make sure you are not using ad-blockers." }, { "code": null, "e": 7814, "s": 7786, "text": "Disable browser extensions." }, { "code": null, "e": 7885, "s": 7814, "text": "We recommend using latest version of your browser for best experience." }, { "code": null, "e": 8072, "s": 7885, "text": "Avoid using static/global variables in coding problems as your code is tested \n against multiple test cases and these tend to retain their previous values." } ]
How to remove a SubList from a List in Java
18 Jan, 2019 Given a list in Java, the task is to remove all the elements in the sublist whose index is between fromIndex, inclusive, and toIndex, exclusive. The range of the index is defined by the user. Example: Input list = [1, 2, 3, 4, 5, 6, 7, 8], fromIndex = 2, endIndex = 4Output [1, 2, 5, 6, 7, 8] Input list = [‘G’, ‘E’, ‘E’, ‘G’, ‘G’, ‘K’, ‘S’], fromIndex = 3, endIndex = 5Output [‘G’, ‘E’, ‘E’, ‘K’, ‘S’] Method 1: Using subList() and clear() methodSyntax:List.subList(int fromIndex, int toIndex).clear() Example:// Java code to remove a subList using// subList(a, b).clear() method import java.util.*; public class AbstractListDemo { public static void main(String args[]) { // Creating an empty AbstractList AbstractList<String> list = new LinkedList<String>(); // Using add() method // to add elements in the list list.add("GFG"); list.add("for"); list.add("Geeks"); list.add("computer"); list.add("portal"); // Output the list System.out.println("Original List: " + list); // subList and clear method // to remove elements // specified in the range list.subList(1, 3).clear(); // Print the final list System.out.println("Final List: " + list); }}Output:Original List: [GFG, for, Geeks, computer, portal] Final List: [GFG, computer, portal] Note: Classes which can inherit AbstractList:ArrayListVectorLinkedListStack Syntax: List.subList(int fromIndex, int toIndex).clear() Example: // Java code to remove a subList using// subList(a, b).clear() method import java.util.*; public class AbstractListDemo { public static void main(String args[]) { // Creating an empty AbstractList AbstractList<String> list = new LinkedList<String>(); // Using add() method // to add elements in the list list.add("GFG"); list.add("for"); list.add("Geeks"); list.add("computer"); list.add("portal"); // Output the list System.out.println("Original List: " + list); // subList and clear method // to remove elements // specified in the range list.subList(1, 3).clear(); // Print the final list System.out.println("Final List: " + list); }} Original List: [GFG, for, Geeks, computer, portal] Final List: [GFG, computer, portal] Note: Classes which can inherit AbstractList: ArrayList Vector LinkedList Stack Method 2: Using removeRange() methodSyntax:List.removeRange(int fromIndex, int toIndex) Example:// Java code to remove a subList// using removeRange() method import java.util.*; // since removeRange() is a protected method// ArrayList has to be extend the classpublic class GFG extends ArrayList<Integer> { public static void main(String[] args) { // create an empty array list GFG arr = new GFG(); // use add() method // to add values in the list arr.add(1); arr.add(2); arr.add(3); arr.add(4); arr.add(5); arr.add(6); arr.add(7); arr.add(8); // prints the list before removing System.out.println("Original List: " + arr); // removing elements in the list // from index 2 to 4 arr.removeRange(2, 4); System.out.println("Final List: " + arr); }}Output:Original List: [1, 2, 3, 4, 5, 6, 7, 8] Final List: [1, 2, 5, 6, 7, 8] Syntax: List.removeRange(int fromIndex, int toIndex) Example: // Java code to remove a subList// using removeRange() method import java.util.*; // since removeRange() is a protected method// ArrayList has to be extend the classpublic class GFG extends ArrayList<Integer> { public static void main(String[] args) { // create an empty array list GFG arr = new GFG(); // use add() method // to add values in the list arr.add(1); arr.add(2); arr.add(3); arr.add(4); arr.add(5); arr.add(6); arr.add(7); arr.add(8); // prints the list before removing System.out.println("Original List: " + arr); // removing elements in the list // from index 2 to 4 arr.removeRange(2, 4); System.out.println("Final List: " + arr); }} Original List: [1, 2, 3, 4, 5, 6, 7, 8] Final List: [1, 2, 5, 6, 7, 8] java-list Java-List-Programs Picked Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Arrays in Java Split() String method in Java with examples Arrays.sort() in Java with examples Reverse a string in Java Object Oriented Programming (OOPs) Concept in Java For-each loop in Java How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples Stream In Java
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Jan, 2019" }, { "code": null, "e": 220, "s": 28, "text": "Given a list in Java, the task is to remove all the elements in the sublist whose index is between fromIndex, inclusive, and toIndex, exclusive. The range of the index is defined by the user." }, { "code": null, "e": 229, "s": 220, "text": "Example:" }, { "code": null, "e": 321, "s": 229, "text": "Input list = [1, 2, 3, 4, 5, 6, 7, 8], fromIndex = 2, endIndex = 4Output [1, 2, 5, 6, 7, 8]" }, { "code": null, "e": 431, "s": 321, "text": "Input list = [‘G’, ‘E’, ‘E’, ‘G’, ‘G’, ‘K’, ‘S’], fromIndex = 3, endIndex = 5Output [‘G’, ‘E’, ‘E’, ‘K’, ‘S’]" }, { "code": null, "e": 1549, "s": 431, "text": "Method 1: Using subList() and clear() methodSyntax:List.subList(int fromIndex, int toIndex).clear()\nExample:// Java code to remove a subList using// subList(a, b).clear() method import java.util.*; public class AbstractListDemo { public static void main(String args[]) { // Creating an empty AbstractList AbstractList<String> list = new LinkedList<String>(); // Using add() method // to add elements in the list list.add(\"GFG\"); list.add(\"for\"); list.add(\"Geeks\"); list.add(\"computer\"); list.add(\"portal\"); // Output the list System.out.println(\"Original List: \" + list); // subList and clear method // to remove elements // specified in the range list.subList(1, 3).clear(); // Print the final list System.out.println(\"Final List: \" + list); }}Output:Original List: [GFG, for, Geeks, computer, portal]\nFinal List: [GFG, computer, portal]\nNote: Classes which can inherit AbstractList:ArrayListVectorLinkedListStack" }, { "code": null, "e": 1557, "s": 1549, "text": "Syntax:" }, { "code": null, "e": 1607, "s": 1557, "text": "List.subList(int fromIndex, int toIndex).clear()\n" }, { "code": null, "e": 1616, "s": 1607, "text": "Example:" }, { "code": "// Java code to remove a subList using// subList(a, b).clear() method import java.util.*; public class AbstractListDemo { public static void main(String args[]) { // Creating an empty AbstractList AbstractList<String> list = new LinkedList<String>(); // Using add() method // to add elements in the list list.add(\"GFG\"); list.add(\"for\"); list.add(\"Geeks\"); list.add(\"computer\"); list.add(\"portal\"); // Output the list System.out.println(\"Original List: \" + list); // subList and clear method // to remove elements // specified in the range list.subList(1, 3).clear(); // Print the final list System.out.println(\"Final List: \" + list); }}", "e": 2457, "s": 1616, "text": null }, { "code": null, "e": 2545, "s": 2457, "text": "Original List: [GFG, for, Geeks, computer, portal]\nFinal List: [GFG, computer, portal]\n" }, { "code": null, "e": 2591, "s": 2545, "text": "Note: Classes which can inherit AbstractList:" }, { "code": null, "e": 2601, "s": 2591, "text": "ArrayList" }, { "code": null, "e": 2608, "s": 2601, "text": "Vector" }, { "code": null, "e": 2619, "s": 2608, "text": "LinkedList" }, { "code": null, "e": 2625, "s": 2619, "text": "Stack" }, { "code": null, "e": 3650, "s": 2625, "text": "Method 2: Using removeRange() methodSyntax:List.removeRange(int fromIndex, int toIndex)\nExample:// Java code to remove a subList// using removeRange() method import java.util.*; // since removeRange() is a protected method// ArrayList has to be extend the classpublic class GFG extends ArrayList<Integer> { public static void main(String[] args) { // create an empty array list GFG arr = new GFG(); // use add() method // to add values in the list arr.add(1); arr.add(2); arr.add(3); arr.add(4); arr.add(5); arr.add(6); arr.add(7); arr.add(8); // prints the list before removing System.out.println(\"Original List: \" + arr); // removing elements in the list // from index 2 to 4 arr.removeRange(2, 4); System.out.println(\"Final List: \" + arr); }}Output:Original List: [1, 2, 3, 4, 5, 6, 7, 8]\nFinal List: [1, 2, 5, 6, 7, 8]\n" }, { "code": null, "e": 3658, "s": 3650, "text": "Syntax:" }, { "code": null, "e": 3704, "s": 3658, "text": "List.removeRange(int fromIndex, int toIndex)\n" }, { "code": null, "e": 3713, "s": 3704, "text": "Example:" }, { "code": "// Java code to remove a subList// using removeRange() method import java.util.*; // since removeRange() is a protected method// ArrayList has to be extend the classpublic class GFG extends ArrayList<Integer> { public static void main(String[] args) { // create an empty array list GFG arr = new GFG(); // use add() method // to add values in the list arr.add(1); arr.add(2); arr.add(3); arr.add(4); arr.add(5); arr.add(6); arr.add(7); arr.add(8); // prints the list before removing System.out.println(\"Original List: \" + arr); // removing elements in the list // from index 2 to 4 arr.removeRange(2, 4); System.out.println(\"Final List: \" + arr); }}", "e": 4564, "s": 3713, "text": null }, { "code": null, "e": 4636, "s": 4564, "text": "Original List: [1, 2, 3, 4, 5, 6, 7, 8]\nFinal List: [1, 2, 5, 6, 7, 8]\n" }, { "code": null, "e": 4646, "s": 4636, "text": "java-list" }, { "code": null, "e": 4665, "s": 4646, "text": "Java-List-Programs" }, { "code": null, "e": 4672, "s": 4665, "text": "Picked" }, { "code": null, "e": 4677, "s": 4672, "text": "Java" }, { "code": null, "e": 4682, "s": 4677, "text": "Java" }, { "code": null, "e": 4780, "s": 4682, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4795, "s": 4780, "text": "Arrays in Java" }, { "code": null, "e": 4839, "s": 4795, "text": "Split() String method in Java with examples" }, { "code": null, "e": 4875, "s": 4839, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 4900, "s": 4875, "text": "Reverse a string in Java" }, { "code": null, "e": 4951, "s": 4900, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 4973, "s": 4951, "text": "For-each loop in Java" }, { "code": null, "e": 5004, "s": 4973, "text": "How to iterate any Map in Java" }, { "code": null, "e": 5023, "s": 5004, "text": "Interfaces in Java" }, { "code": null, "e": 5053, "s": 5023, "text": "HashMap in Java with Examples" } ]
SAP ABAP - Do Loop
Unconditional loops repeatedly execute several statements without specifying any condition. The DO statement implements unconditional loops by executing a set of statement blocks several times unconditionally. The general format for the DO statement is as follows − DO [n TIMES]. <statement block>. ENDDO. ‘Times’ imposes a restriction on the number of loop passes, which is represented by ‘n’. The value of ‘n’ should not be negative or zero. If it is zero or negative, the statements in the loop are not executed. Report YH_SEP_15. Do 15 TIMES. Write: / 'Hello'. ENDDO. The above code produces the following output − Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello In this example, the system understands that the loop is to be processed 15 times.
[ { "code": null, "e": 3242, "s": 3032, "text": "Unconditional loops repeatedly execute several statements without specifying any condition. The DO statement implements unconditional loops by executing a set of statement blocks several times unconditionally." }, { "code": null, "e": 3298, "s": 3242, "text": "The general format for the DO statement is as follows −" }, { "code": null, "e": 3345, "s": 3298, "text": "DO [n TIMES]. \n \n<statement block>.\n \nENDDO.\n" }, { "code": null, "e": 3555, "s": 3345, "text": "‘Times’ imposes a restriction on the number of loop passes, which is represented by ‘n’. The value of ‘n’ should not be negative or zero. If it is zero or negative, the statements in the loop are not executed." }, { "code": null, "e": 3620, "s": 3555, "text": "Report YH_SEP_15.\n \nDo 15 TIMES. \n \nWrite: / 'Hello'.\n \nENDDO." }, { "code": null, "e": 3667, "s": 3620, "text": "The above code produces the following output −" }, { "code": null, "e": 3772, "s": 3667, "text": "Hello \nHello \nHello \nHello \nHello \nHello \nHello \nHello \nHello \nHello \nHello \nHello \nHello \nHello \nHello\n" } ]
How to Create New ImageView Dynamically on Button Click in Android?
23 Apr, 2021 In this article, we are going to implement a very important feature related to ImageView. Here we are going to add ImageView dynamically. We will be just changing the background color. Whenever we click on a button a new ImageView will be created. So here we are going to learn how to implement that feature. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. Step 1: Create a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Step 2: Working with the activity_main.xml file Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/layout" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_marginTop="20dp" android:gravity="center_horizontal" android:orientation="vertical" tools:context=".MainActivity"> <!--Adding the Button in the layout--> <Button android:id="@+id/addiview" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/purple_500" android:text="Add Image View" android:textColor="@color/black" /> </LinearLayout> Step 3: Working with the MainActivity.java file Go to the MainActivity.java file and refer to the following code. Here we are creating an ImageView and a layout and will add the ImageView in the layout. This is how we are creating an ImageView ImageView imageView=new ImageView(AddImageViw.this); // adding the image in ImageView imageView.setImageResource(R.mipmap.ic_launcher); This is how we are adding the newly created image view in our layout. LinearLayout.LayoutParams params=new LinearLayout.LayoutParams(width,height); params.setMargins(0,10,0,10); // setting the margin in the layout imageView.setLayoutParams(params); layout.addView(imageView); // adding the image in the layout Below is the complete code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. Java import android.graphics.Color;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.ImageView;import android.widget.LinearLayout; import androidx.appcompat.app.AppCompatActivity; import java.util.Random; public class MainActivity extends AppCompatActivity { Button addview; LinearLayout layout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initialising layout addview = findViewById(R.id.addiview); layout = findViewById(R.id.layout); // we will click on the add view button addview.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // initialising new layout ImageView imageView = new ImageView(MainActivity.this); // setting the image in the layout imageView.setImageResource(R.mipmap.ic_launcher); // calling addview with width and height addvieW(imageView, 200, 200); // adding the background color colorrandom(imageView); } }); } public void colorrandom(ImageView imageView) { // Initialising the Random(); Random random = new Random(); // adding the random background color int color = Color.argb(255, random.nextInt(256), random.nextInt(256), random.nextInt(256)); // setting the background color imageView.setBackgroundColor(color); } private void addvieW(ImageView imageView, int width, int height) { LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(width, height); // setting the margin in linearlayout params.setMargins(0, 10, 0, 10); imageView.setLayoutParams(params); // adding the image in layout layout.addView(imageView); }} Output: Android Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Android RecyclerView in Kotlin Android SDK and it's Components How to Add Views Dynamically and Store Data in Arraylist in Android? Broadcast Receiver in Android With Example Navigation Drawer in Android Arrays in Java Split() String method in Java with examples Arrays.sort() in Java with examples Object Oriented Programming (OOPs) Concept in Java Reverse a string in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Apr, 2021" }, { "code": null, "e": 504, "s": 28, "text": "In this article, we are going to implement a very important feature related to ImageView. Here we are going to add ImageView dynamically. We will be just changing the background color. Whenever we click on a button a new ImageView will be created. So here we are going to learn how to implement that feature. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. " }, { "code": null, "e": 533, "s": 504, "text": "Step 1: Create a New Project" }, { "code": null, "e": 695, "s": 533, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language." }, { "code": null, "e": 743, "s": 695, "text": "Step 2: Working with the activity_main.xml file" }, { "code": null, "e": 886, "s": 743, "text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. " }, { "code": null, "e": 890, "s": 886, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:id=\"@+id/layout\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_marginTop=\"20dp\" android:gravity=\"center_horizontal\" android:orientation=\"vertical\" tools:context=\".MainActivity\"> <!--Adding the Button in the layout--> <Button android:id=\"@+id/addiview\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:background=\"@color/purple_500\" android:text=\"Add Image View\" android:textColor=\"@color/black\" /> </LinearLayout>", "e": 1631, "s": 890, "text": null }, { "code": null, "e": 1679, "s": 1631, "text": "Step 3: Working with the MainActivity.java file" }, { "code": null, "e": 1876, "s": 1679, "text": "Go to the MainActivity.java file and refer to the following code. Here we are creating an ImageView and a layout and will add the ImageView in the layout. This is how we are creating an ImageView " }, { "code": null, "e": 2012, "s": 1876, "text": "ImageView imageView=new ImageView(AddImageViw.this);\n// adding the image in ImageView\nimageView.setImageResource(R.mipmap.ic_launcher);" }, { "code": null, "e": 2082, "s": 2012, "text": "This is how we are adding the newly created image view in our layout." }, { "code": null, "e": 2350, "s": 2082, "text": "LinearLayout.LayoutParams params=new LinearLayout.LayoutParams(width,height);\n params.setMargins(0,10,0,10); // setting the margin in the layout \n imageView.setLayoutParams(params);\n layout.addView(imageView); // adding the image in the layout" }, { "code": null, "e": 2483, "s": 2350, "text": "Below is the complete code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 2488, "s": 2483, "text": "Java" }, { "code": "import android.graphics.Color;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.ImageView;import android.widget.LinearLayout; import androidx.appcompat.app.AppCompatActivity; import java.util.Random; public class MainActivity extends AppCompatActivity { Button addview; LinearLayout layout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initialising layout addview = findViewById(R.id.addiview); layout = findViewById(R.id.layout); // we will click on the add view button addview.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // initialising new layout ImageView imageView = new ImageView(MainActivity.this); // setting the image in the layout imageView.setImageResource(R.mipmap.ic_launcher); // calling addview with width and height addvieW(imageView, 200, 200); // adding the background color colorrandom(imageView); } }); } public void colorrandom(ImageView imageView) { // Initialising the Random(); Random random = new Random(); // adding the random background color int color = Color.argb(255, random.nextInt(256), random.nextInt(256), random.nextInt(256)); // setting the background color imageView.setBackgroundColor(color); } private void addvieW(ImageView imageView, int width, int height) { LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(width, height); // setting the margin in linearlayout params.setMargins(0, 10, 0, 10); imageView.setLayoutParams(params); // adding the image in layout layout.addView(imageView); }}", "e": 4576, "s": 2488, "text": null }, { "code": null, "e": 4584, "s": 4576, "text": "Output:" }, { "code": null, "e": 4592, "s": 4584, "text": "Android" }, { "code": null, "e": 4597, "s": 4592, "text": "Java" }, { "code": null, "e": 4602, "s": 4597, "text": "Java" }, { "code": null, "e": 4610, "s": 4602, "text": "Android" }, { "code": null, "e": 4708, "s": 4610, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4739, "s": 4708, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 4771, "s": 4739, "text": "Android SDK and it's Components" }, { "code": null, "e": 4840, "s": 4771, "text": "How to Add Views Dynamically and Store Data in Arraylist in Android?" }, { "code": null, "e": 4883, "s": 4840, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 4912, "s": 4883, "text": "Navigation Drawer in Android" }, { "code": null, "e": 4927, "s": 4912, "text": "Arrays in Java" }, { "code": null, "e": 4971, "s": 4927, "text": "Split() String method in Java with examples" }, { "code": null, "e": 5007, "s": 4971, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 5058, "s": 5007, "text": "Object Oriented Programming (OOPs) Concept in Java" } ]
Java | Abstract Class and Interface | Question 2
22 Apr, 2022 Which of the following is true about interfaces in java. 1) An interface can contain following type of members. ....public, static, final fields (i.e., constants) ....default and static methods with bodies 2) An instance of interface can be created. 3) A class can implement multiple interfaces. 4) Many classes can implement the same interface. (A) 1, 3 and 4 (B) 1, 2 and 4 (C) 2, 3 and 4 (D) 1, 2, 3 and 4 Answer: (A) Explanation: The instance of an interface can’t be created because it acts as an abstract class. Quiz of this Question anand8214370 Abstract Class and Interface Java-Abstract Class and Interface Java Quiz Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Java | Constructors | Question 3 Java | Exception Handling | Question 2 Java | Functions | Question 1 Java | Exception Handling | Question 3 Java | Exception Handling | Question 4 Java | Exception Handling | Question 8 Java | Exception Handling | Question 7 Java | Exception Handling | Question 6 Java | Class and Object | Question 1 Java | Exception Handling | Question 8
[ { "code": null, "e": 52, "s": 24, "text": "\n22 Apr, 2022" }, { "code": null, "e": 109, "s": 52, "text": "Which of the following is true about interfaces in java." }, { "code": null, "e": 402, "s": 109, "text": "1) An interface can contain following type of members.\n....public, static, final fields (i.e., constants) \n....default and static methods with bodies\n\n2) An instance of interface can be created.\n\n3) A class can implement multiple interfaces.\n\n4) Many classes can implement the same interface." }, { "code": null, "e": 406, "s": 402, "text": "(A)" }, { "code": null, "e": 417, "s": 406, "text": "1, 3 and 4" }, { "code": null, "e": 421, "s": 417, "text": "(B)" }, { "code": null, "e": 432, "s": 421, "text": "1, 2 and 4" }, { "code": null, "e": 436, "s": 432, "text": "(C)" }, { "code": null, "e": 447, "s": 436, "text": "2, 3 and 4" }, { "code": null, "e": 451, "s": 447, "text": "(D)" }, { "code": null, "e": 465, "s": 451, "text": "1, 2, 3 and 4" }, { "code": null, "e": 477, "s": 465, "text": "Answer: (A)" }, { "code": null, "e": 574, "s": 477, "text": "Explanation: The instance of an interface can’t be created because it acts as an abstract class." }, { "code": null, "e": 596, "s": 574, "text": "Quiz of this Question" }, { "code": null, "e": 609, "s": 596, "text": "anand8214370" }, { "code": null, "e": 638, "s": 609, "text": "Abstract Class and Interface" }, { "code": null, "e": 672, "s": 638, "text": "Java-Abstract Class and Interface" }, { "code": null, "e": 682, "s": 672, "text": "Java Quiz" }, { "code": null, "e": 780, "s": 682, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 813, "s": 780, "text": "Java | Constructors | Question 3" }, { "code": null, "e": 852, "s": 813, "text": "Java | Exception Handling | Question 2" }, { "code": null, "e": 882, "s": 852, "text": "Java | Functions | Question 1" }, { "code": null, "e": 921, "s": 882, "text": "Java | Exception Handling | Question 3" }, { "code": null, "e": 960, "s": 921, "text": "Java | Exception Handling | Question 4" }, { "code": null, "e": 999, "s": 960, "text": "Java | Exception Handling | Question 8" }, { "code": null, "e": 1038, "s": 999, "text": "Java | Exception Handling | Question 7" }, { "code": null, "e": 1077, "s": 1038, "text": "Java | Exception Handling | Question 6" }, { "code": null, "e": 1114, "s": 1077, "text": "Java | Class and Object | Question 1" } ]
Maximum distance between two occurrences of same element in array
06 Jul, 2022 Given an array with repeated elements, the task is to find the maximum distance between two occurrences of an element. Examples: Input : arr[] = {3, 2, 1, 2, 1, 4, 5, 8, 6, 7, 4, 2} Output: 10 // maximum distance for 2 is 11-1 = 10 // maximum distance for 1 is 4-2 = 2 // maximum distance for 4 is 10-5 = 5 A simple solution for this problem is to, one by one, pick each element from the array and find its first and last occurrence in the array and take the difference between the first and last occurrence for maximum distance. The time complexity for this approach is O(n2). An efficient solution to this problem is to use hashing. The idea is to traverse the input array and store the index of the first occurrence in a hash map. For every other occurrence, find the difference between the index and the first index stored in the hash map. If the difference is more than the result so far, then update the result. Below are implementations of the idea. The implementation uses unordered_map in. C++ Java Python3 C# Javascript // C++ program to find maximum distance between two// same occurrences of a number.#include<bits/stdc++.h>using namespace std; // Function to find maximum distance between equal elementsint maxDistance(int arr[], int n){ // Used to store element to first index mapping unordered_map<int, int> mp; // Traverse elements and find maximum distance between // same occurrences with the help of map. int max_dist = 0; for (int i=0; i<n; i++) { // If this is first occurrence of element, insert its // index in map if (mp.find(arr[i]) == mp.end()) mp[arr[i]] = i; // Else update max distance else max_dist = max(max_dist, i - mp[arr[i]]); } return max_dist;} // Driver program to run the caseint main(){ int arr[] = {3, 2, 1, 2, 1, 4, 5, 8, 6, 7, 4, 2}; int n = sizeof(arr)/sizeof(arr[0]); cout << maxDistance(arr, n); return 0;} // Java program to find maximum distance between two// same occurrences of a number.import java.io.*;import java.util.*; class GFG{ // Function to find maximum distance between equal elements static int maxDistance(int[] arr, int n) { // Used to store element to first index mapping HashMap<Integer, Integer> map = new HashMap<>(); // Traverse elements and find maximum distance between // same occurrences with the help of map. int max_dist = 0; for (int i = 0; i < n; i++) { // If this is first occurrence of element, insert its // index in map if (!map.containsKey(arr[i])) map.put(arr[i], i); // Else update max distance else max_dist = Math.max(max_dist, i - map.get(arr[i])); } return max_dist;} // Driver codepublic static void main(String args[]){ int[] arr = {3, 2, 1, 2, 1, 4, 5, 8, 6, 7, 4, 2}; int n = arr.length; System.out.println(maxDistance(arr, n));}} // This code is contributed by rachana soma # Python program to find maximum distance between two# same occurrences of a number. # Function to find maximum distance between equal elementsdef maxDistance(arr, n): # Used to store element to first index mapping mp = {} # Traverse elements and find maximum distance between # same occurrences with the help of map. maxDict = 0 for i in range(n): # If this is first occurrence of element, insert its # index in map if arr[i] not in mp.keys(): mp[arr[i]] = i # Else update max distance else: maxDict = max(maxDict, i-mp[arr[i]]) return maxDict # Driver Programif __name__=='__main__': arr = [3, 2, 1, 2, 1, 4, 5, 8, 6, 7, 4, 2] n = len(arr) print (maxDistance(arr, n)) # Contributed By: Harshit Sidhwa // C# program to find maximum distance between two// same occurrences of a number. using System;using System.Collections.Generic; class GFG{ // Function to find maximum distance between equal elements static int maxDistance(int[] arr, int n) { // Used to store element to first index mapping Dictionary<int, int> map = new Dictionary<int, int>(); // Traverse elements and find maximum distance between // same occurrences with the help of map. int max_dist = 0; for (int i = 0; i < n; i++) { // If this is first occurrence of element, insert its // index in map if (!map.ContainsKey(arr[i])) map.Add(arr[i], i); // Else update max distance else max_dist = Math.Max(max_dist, i - map[arr[i]]); } return max_dist;} // Driver codepublic static void Main(String []args){ int[] arr = {3, 2, 1, 2, 1, 4, 5, 8, 6, 7, 4, 2}; int n = arr.Length; Console.WriteLine(maxDistance(arr, n));}} // This code is contributed by PrinciRaj1992 <script> // Javascript program to find maximum distance between two// same occurrences of a number. // Function to find maximum distance between equal elements function maxDistance(arr, n) { // Used to store element to first index mapping let map = new Map(); // Traverse elements and find maximum distance between // same occurrences with the help of map. let max_dist = 0; for (let i = 0; i < n; i++) { // If this is first occurrence of element, insert its // index in map if (!map.has(arr[i])) map.set(arr[i], i); // Else update max distance else max_dist = Math.max(max_dist, i - map.get(arr[i])); } return max_dist;} // Driver program let arr = [3, 2, 1, 2, 1, 4, 5, 8, 6, 7, 4, 2]; let n = arr.length; document.write(maxDistance(arr, n)); </script> 10 Time complexity : O(n) under the assumption that unordered_map’s search and insert operations take O(1) time.Auxiliary Space : O(n). This article is contributed by Shashank Mishra ( Gullu ). 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. rachana soma nidhi_biet princiraj1992 avijitmondal1998 amartyaghoshgfg anandkumarshivam2266 hardikkoriintern Arrays Hash Arrays Hash Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n06 Jul, 2022" }, { "code": null, "e": 171, "s": 52, "text": "Given an array with repeated elements, the task is to find the maximum distance between two occurrences of an element." }, { "code": null, "e": 183, "s": 171, "text": "Examples: " }, { "code": null, "e": 365, "s": 183, "text": "Input : arr[] = {3, 2, 1, 2, 1, 4, 5, 8, 6, 7, 4, 2}\nOutput: 10\n// maximum distance for 2 is 11-1 = 10 \n// maximum distance for 1 is 4-2 = 2 \n// maximum distance for 4 is 10-5 = 5 " }, { "code": null, "e": 636, "s": 365, "text": "A simple solution for this problem is to, one by one, pick each element from the array and find its first and last occurrence in the array and take the difference between the first and last occurrence for maximum distance. The time complexity for this approach is O(n2)." }, { "code": null, "e": 976, "s": 636, "text": "An efficient solution to this problem is to use hashing. The idea is to traverse the input array and store the index of the first occurrence in a hash map. For every other occurrence, find the difference between the index and the first index stored in the hash map. If the difference is more than the result so far, then update the result." }, { "code": null, "e": 1058, "s": 976, "text": "Below are implementations of the idea. The implementation uses unordered_map in. " }, { "code": null, "e": 1062, "s": 1058, "text": "C++" }, { "code": null, "e": 1067, "s": 1062, "text": "Java" }, { "code": null, "e": 1075, "s": 1067, "text": "Python3" }, { "code": null, "e": 1078, "s": 1075, "text": "C#" }, { "code": null, "e": 1089, "s": 1078, "text": "Javascript" }, { "code": "// C++ program to find maximum distance between two// same occurrences of a number.#include<bits/stdc++.h>using namespace std; // Function to find maximum distance between equal elementsint maxDistance(int arr[], int n){ // Used to store element to first index mapping unordered_map<int, int> mp; // Traverse elements and find maximum distance between // same occurrences with the help of map. int max_dist = 0; for (int i=0; i<n; i++) { // If this is first occurrence of element, insert its // index in map if (mp.find(arr[i]) == mp.end()) mp[arr[i]] = i; // Else update max distance else max_dist = max(max_dist, i - mp[arr[i]]); } return max_dist;} // Driver program to run the caseint main(){ int arr[] = {3, 2, 1, 2, 1, 4, 5, 8, 6, 7, 4, 2}; int n = sizeof(arr)/sizeof(arr[0]); cout << maxDistance(arr, n); return 0;}", "e": 2011, "s": 1089, "text": null }, { "code": "// Java program to find maximum distance between two// same occurrences of a number.import java.io.*;import java.util.*; class GFG{ // Function to find maximum distance between equal elements static int maxDistance(int[] arr, int n) { // Used to store element to first index mapping HashMap<Integer, Integer> map = new HashMap<>(); // Traverse elements and find maximum distance between // same occurrences with the help of map. int max_dist = 0; for (int i = 0; i < n; i++) { // If this is first occurrence of element, insert its // index in map if (!map.containsKey(arr[i])) map.put(arr[i], i); // Else update max distance else max_dist = Math.max(max_dist, i - map.get(arr[i])); } return max_dist;} // Driver codepublic static void main(String args[]){ int[] arr = {3, 2, 1, 2, 1, 4, 5, 8, 6, 7, 4, 2}; int n = arr.length; System.out.println(maxDistance(arr, n));}} // This code is contributed by rachana soma", "e": 3103, "s": 2011, "text": null }, { "code": "# Python program to find maximum distance between two# same occurrences of a number. # Function to find maximum distance between equal elementsdef maxDistance(arr, n): # Used to store element to first index mapping mp = {} # Traverse elements and find maximum distance between # same occurrences with the help of map. maxDict = 0 for i in range(n): # If this is first occurrence of element, insert its # index in map if arr[i] not in mp.keys(): mp[arr[i]] = i # Else update max distance else: maxDict = max(maxDict, i-mp[arr[i]]) return maxDict # Driver Programif __name__=='__main__': arr = [3, 2, 1, 2, 1, 4, 5, 8, 6, 7, 4, 2] n = len(arr) print (maxDistance(arr, n)) # Contributed By: Harshit Sidhwa", "e": 3910, "s": 3103, "text": null }, { "code": "// C# program to find maximum distance between two// same occurrences of a number. using System;using System.Collections.Generic; class GFG{ // Function to find maximum distance between equal elements static int maxDistance(int[] arr, int n) { // Used to store element to first index mapping Dictionary<int, int> map = new Dictionary<int, int>(); // Traverse elements and find maximum distance between // same occurrences with the help of map. int max_dist = 0; for (int i = 0; i < n; i++) { // If this is first occurrence of element, insert its // index in map if (!map.ContainsKey(arr[i])) map.Add(arr[i], i); // Else update max distance else max_dist = Math.Max(max_dist, i - map[arr[i]]); } return max_dist;} // Driver codepublic static void Main(String []args){ int[] arr = {3, 2, 1, 2, 1, 4, 5, 8, 6, 7, 4, 2}; int n = arr.Length; Console.WriteLine(maxDistance(arr, n));}} // This code is contributed by PrinciRaj1992", "e": 5013, "s": 3910, "text": null }, { "code": "<script> // Javascript program to find maximum distance between two// same occurrences of a number. // Function to find maximum distance between equal elements function maxDistance(arr, n) { // Used to store element to first index mapping let map = new Map(); // Traverse elements and find maximum distance between // same occurrences with the help of map. let max_dist = 0; for (let i = 0; i < n; i++) { // If this is first occurrence of element, insert its // index in map if (!map.has(arr[i])) map.set(arr[i], i); // Else update max distance else max_dist = Math.max(max_dist, i - map.get(arr[i])); } return max_dist;} // Driver program let arr = [3, 2, 1, 2, 1, 4, 5, 8, 6, 7, 4, 2]; let n = arr.length; document.write(maxDistance(arr, n)); </script>", "e": 5956, "s": 5013, "text": null }, { "code": null, "e": 5959, "s": 5956, "text": "10" }, { "code": null, "e": 6092, "s": 5959, "text": "Time complexity : O(n) under the assumption that unordered_map’s search and insert operations take O(1) time.Auxiliary Space : O(n)." }, { "code": null, "e": 6402, "s": 6092, "text": "This article is contributed by Shashank Mishra ( Gullu ). 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. " }, { "code": null, "e": 6415, "s": 6402, "text": "rachana soma" }, { "code": null, "e": 6426, "s": 6415, "text": "nidhi_biet" }, { "code": null, "e": 6440, "s": 6426, "text": "princiraj1992" }, { "code": null, "e": 6457, "s": 6440, "text": "avijitmondal1998" }, { "code": null, "e": 6473, "s": 6457, "text": "amartyaghoshgfg" }, { "code": null, "e": 6494, "s": 6473, "text": "anandkumarshivam2266" }, { "code": null, "e": 6511, "s": 6494, "text": "hardikkoriintern" }, { "code": null, "e": 6518, "s": 6511, "text": "Arrays" }, { "code": null, "e": 6523, "s": 6518, "text": "Hash" }, { "code": null, "e": 6530, "s": 6523, "text": "Arrays" }, { "code": null, "e": 6535, "s": 6530, "text": "Hash" } ]
Rat in a Maze with multiple steps or jump allowed
01 Jul, 2022 This is the variation of Rat in Maze A Maze is given as N*N binary matrix of blocks where source block is the upper left most block i.e., maze[0][0] and destination block is lower rightmost block i.e., maze[N-1][N-1]. A rat starts from source and has to reach destination. The rat can move only in two directions: forward and down. In the maze matrix, 0 means the block is dead end and non-zero number means the block can be used in the path from source to destination. The non-zero value of mat[i][j] indicates number of maximum jumps rat can make from cell mat[i][j].In this variation, Rat is allowed to jump multiple steps at a time instead of 1. Examples: Input : { {2, 1, 0, 0}, {3, 0, 0, 1}, {0, 1, 0, 1}, {0, 0, 0, 1} } Output : { {1, 0, 0, 0}, {1, 0, 0, 1}, {0, 0, 0, 1}, {0, 0, 0, 1} } Explanation Rat started with M[0][0] and can jump upto 2 steps right/down. Let's try in horizontal direction - M[0][1] won't lead to solution and M[0][2] is 0 which is dead end. So, backtrack and try in down direction. Rat jump down to M[1][0] which eventually leads to solution. Input : { {2, 1, 0, 0}, {2, 0, 0, 1}, {0, 1, 0, 1}, {0, 0, 0, 1} } Output : Solution doesn't exist Naive Algorithm The Naive Algorithm is to generate all paths from source to destination and one by one check if the generated path satisfies the constraints. while there are untried paths { generate the next path if this path has all blocks as non-zero { print this path; } } Backtracking Algorithm If destination is reached print the solution matrix Else a) Mark current cell in solution matrix as 1. b) Move forward/jump (for each valid steps) in horizontal direction and recursively check if this move leads to a solution. c) If the move chosen in the above step doesn't lead to a solution then move down and check if this move leads to a solution. d) If none of the above solutions work then unmark this cell as 0 (BACKTRACK) and return false. Implementation of Backtracking solution C++ Java Python3 C# Javascript /* C/C++ program to solve Rat in a Maze problemusing backtracking */#include <stdio.h> // Maze size#define N 4 bool solveMazeUtil(int maze[N][N], int x, int y, int sol[N][N]); /* A utility function to print solution matrixsol[N][N] */void printSolution(int sol[N][N]){ for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) printf(" %d ", sol[i][j]); printf("\n"); }} /* A utility function to check if x, y is validindex for N*N maze */bool isSafe(int maze[N][N], int x, int y){ // if (x, y outside maze) return false if (x >= 0 && x < N && y >= 0 && y < N && maze[x][y] != 0) return true; return false;} /* This function solves the Maze problem usingBacktracking. It mainly uses solveMazeUtil() tosolve the problem. It returns false if no pathis possible, otherwise return true and printsthe path in the form of 1s. Please note thatthere may be more than one solutions,this function prints one of the feasible solutions.*/bool solveMaze(int maze[N][N]){ int sol[N][N] = { { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }; if (solveMazeUtil(maze, 0, 0, sol) == false) { printf("Solution doesn't exist"); return false; } printSolution(sol); return true;} /* A recursive utility function to solve Maze problem */bool solveMazeUtil(int maze[N][N], int x, int y, int sol[N][N]){ // if (x, y is goal) return true if (x == N - 1 && y == N - 1) { sol[x][y] = 1; return true; } // Check if maze[x][y] is valid if (isSafe(maze, x, y) == true) { // mark x, y as part of solution path sol[x][y] = 1; /* Move forward in x direction */ for (int i = 1; i <= maze[x][y] && i < N; i++) { /* Move forward in x direction */ if (solveMazeUtil(maze, x + i, y, sol) == true) return true; /* If moving in x direction doesn't give solution then Move down in y direction */ if (solveMazeUtil(maze, x, y + i, sol) == true) return true; } /* If none of the above movements work then BACKTRACK: unmark x, y as part of solution path */ sol[x][y] = 0; return false; } return false;} // driver program to test above functionint main(){ int maze[N][N] = { { 2, 1, 0, 0 }, { 3, 0, 0, 1 }, { 0, 1, 0, 1 }, { 0, 0, 0, 1 } }; solveMaze(maze); return 0;} // Java program to solve Rat in a Maze problem// using backtrackingclass GFG{ // Maze size static int N = 4; /* A utility function to print solution matrix sol[N][N] */ static void printSolution(int sol[][]) { for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { System.out.printf(" %d ", sol[i][j]); } System.out.printf("\n"); } } /* A utility function to check if x, y is valid index for N*N maze */ static boolean isSafe(int maze[][], int x, int y) { // if (x, y outside maze) return false if (x >= 0 && x < N && y >= 0 && y < N && maze[x][y] != 0) { return true; } return false; } /* This function solves the Maze problem using Backtracking. It mainly uses solveMazeUtil() to solve the problem. It returns false if no path is possible, otherwise return true and prints the path in the form of 1s. Please note that there may be more than one solutions, this function prints one of the feasible solutions.*/ static boolean solveMaze(int maze[][]) { int sol[][] = {{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}}; if (solveMazeUtil(maze, 0, 0, sol) == false) { System.out.printf("Solution doesn't exist"); return false; } printSolution(sol); return true; } /* A recursive utility function to solve Maze problem */ static boolean solveMazeUtil(int maze[][], int x, int y, int sol[][]) { // if (x, y is goal) return true if (x == N - 1 && y == N - 1) { sol[x][y] = 1; return true; } // Check if maze[x][y] is valid if (isSafe(maze, x, y) == true) { // mark x, y as part of solution path sol[x][y] = 1; /* Move forward in x direction */ for (int i = 1; i <= maze[x][y] && i < N; i++) { /* Move forward in x direction */ if (solveMazeUtil(maze, x + i, y, sol) == true) { return true; } /* If moving in x direction doesn't give solution then Move down in y direction */ if (solveMazeUtil(maze, x, y + i, sol) == true) { return true; } } /* If none of the above movements work then BACKTRACK: unmark x, y as part of solution path */ sol[x][y] = 0; return false; } return false; } // Driver Code public static void main(String[] args) { int maze[][] = {{2, 1, 0, 0}, {3, 0, 0, 1}, {0, 1, 0, 1}, {0, 0, 0, 1}}; solveMaze(maze); }} // This code is contributed by Princi Singh """ Python3 program to solve Rat in aMaze problem using backtracking """ # Maze sizeN = 4 """ A utility function to print solution matrixsol """def printSolution(sol): for i in range(N): for j in range(N): print(sol[i][j], end = " ") print() """ A utility function to check ifx, y is valid index for N*N maze """def isSafe(maze, x, y): # if (x, y outside maze) return false if (x >= 0 and x < N and y >= 0 and y < N and maze[x][y] != 0): return True return False """ This function solves the Maze problem usingBacktracking. It mainly uses solveMazeUtil() tosolve the problem. It returns false if no pathis possible, otherwise return True and printsthe path in the form of 1s. Please note thatthere may be more than one solutions,this function prints one of the feasible solutions."""def solveMaze(maze): sol = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] if (solveMazeUtil(maze, 0, 0, sol) == False): print("Solution doesn't exist") return False printSolution(sol) return True """ A recursive utility functionto solve Maze problem """def solveMazeUtil(maze, x, y, sol): # if (x, y is goal) return True if (x == N - 1 and y == N - 1) : sol[x][y] = 1 return True # Check if maze[x][y] is valid if (isSafe(maze, x, y) == True): # mark x, y as part of solution path sol[x][y] = 1 """ Move forward in x direction """ for i in range(1, N): if (i <= maze[x][y]): """ Move forward in x direction """ if (solveMazeUtil(maze, x + i, y, sol) == True): return True """ If moving in x direction doesn't give solution then Move down in y direction """ if (solveMazeUtil(maze, x, y + i, sol) == True): return True """ If none of the above movements work then BACKTRACK: unmark x, y as part of solution path """ sol[x][y] = 0 return False return False # Driver Codemaze = [[2, 1, 0, 0], [3, 0, 0, 1], [0, 1, 0, 1], [0, 0, 0, 1]]solveMaze(maze) # This code is contributed by SHUBHAMSINGH10 // C# program to solve Rat in a Maze problem// using backtrackingusing System; class GFG{ // Maze size static int N = 4; /* A utility function to print solution matrix sol[N, N] */ static void printSolution(int [,]sol) { for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { Console.Write(" {0} ", sol[i, j]); } Console.Write("\n"); } } /* A utility function to check if x, y is valid index for N*N maze */ static Boolean isSafe(int [,]maze, int x, int y) { // if (x, y outside maze) return false if (x >= 0 && x < N && y >= 0 && y < N && maze[x, y] != 0) { return true; } return false; } /* This function solves the Maze problem using Backtracking. It mainly uses solveMazeUtil() to solve the problem. It returns false if no path is possible, otherwise return true and prints the path in the form of 1s. Please note that there may be more than one solutions, this function prints one of the feasible solutions.*/ static Boolean solveMaze(int [,]maze) { int [,]sol = {{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}}; if (solveMazeUtil(maze, 0, 0, sol) == false) { Console.Write("Solution doesn't exist"); return false; } printSolution(sol); return true; } /* A recursive utility function to solve Maze problem */ static Boolean solveMazeUtil(int [,]maze, int x, int y, int [,]sol) { // if (x, y is goal) return true if (x == N - 1 && y == N - 1) { sol[x, y] = 1; return true; } // Check if maze[x,y] is valid if (isSafe(maze, x, y) == true) { // mark x, y as part of solution path sol[x, y] = 1; /* Move forward in x direction */ for (int i = 1; i <= maze[x, y] && i < N; i++) { /* Move forward in x direction */ if (solveMazeUtil(maze, x + i, y, sol) == true) { return true; } /* If moving in x direction doesn't give solution then Move down in y direction */ if (solveMazeUtil(maze, x, y + i, sol) == true) { return true; } } /* If none of the above movements work then BACKTRACK: unmark x, y as part of solution path */ sol[x, y] = 0; return false; } return false; } // Driver Code public static void Main(String[] args) { int [,]maze = {{2, 1, 0, 0}, {3, 0, 0, 1}, {0, 1, 0, 1}, {0, 0, 0, 1}}; solveMaze(maze); }} // This code is contributed by 29AjayKumar <script> // JavaScript program to solve Rat in a Maze problem// using backtracking // Maze size let N = 4; /* A utility function to print solution matrix sol[N][N] */ function printSolution(sol) { for (let i = 0; i < N; i++) { for (let j = 0; j < N; j++) { document.write(sol[i][j] + " "); } document.write("<br/>"); } } /* A utility function to check if x, y is valid index for N*N maze */ function isSafe(maze, x, y) { // if (x, y outside maze) return false if (x >= 0 && x < N && y >= 0 && y < N && maze[x][y] != 0) { return true; } return false; } /* This function solves the Maze problem using Backtracking. It mainly uses solveMazeUtil() to solve the problem. It returns false if no path is possible, otherwise return true and print the path in the form of 1s. Please note that there may be more than one solutions, this function prints one of the feasible solutions.*/ function solveMaze(maze) { let sol = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]; if (solveMazeUtil(maze, 0, 0, sol) == false) { document.write("Solution doesn't exist"); return false; } printSolution(sol); return true; } /* A recursive utility function to solve Maze problem */ function solveMazeUtil(maze, x, y, sol) { // if (x, y is goal) return true if (x == N - 1 && y == N - 1) { sol[x][y] = 1; return true; } // Check if maze[x][y] is valid if (isSafe(maze, x, y) == true) { // mark x, y as part of solution path sol[x][y] = 1; /* Move forward in x direction */ for (let i = 1; i <= maze[x][y] && i < N; i++) { /* Move forward in x direction */ if (solveMazeUtil(maze, x + i, y, sol) == true) { return true; } /* If moving in x direction doesn't give solution then Move down in y direction */ if (solveMazeUtil(maze, x, y + i, sol) == true) { return true; } } /* If none of the above movements work then BACKTRACK: unmark x, y as part of solution path */ sol[x][y] = 0; return false; } return false; } // Driver code let maze = [[2, 1, 0, 0], [3, 0, 0, 1], [0, 1, 0, 1], [0, 0, 0, 1]]; solveMaze(maze); // This code is contributed by splevel62.</script> 1 0 0 0 1 0 0 1 0 0 0 1 0 0 0 1 princi singh 29AjayKumar SHUBHAMSINGH10 splevel62 khushboogoyal499 surinderdawra388 Backtracking Matrix Matrix Backtracking Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Generate all the binary strings of N bits Print all paths from a given source to a destination Print all permutations of a string in Java Find if there is a path of more than k length from a source Print a given matrix in spiral form Matrix Chain Multiplication | DP-8 Program to find largest element in an array The Celebrity Problem Find the number of islands | Set 1 (Using DFS)
[ { "code": null, "e": 54, "s": 26, "text": "\n01 Jul, 2022" }, { "code": null, "e": 716, "s": 54, "text": "This is the variation of Rat in Maze A Maze is given as N*N binary matrix of blocks where source block is the upper left most block i.e., maze[0][0] and destination block is lower rightmost block i.e., maze[N-1][N-1]. A rat starts from source and has to reach destination. The rat can move only in two directions: forward and down. In the maze matrix, 0 means the block is dead end and non-zero number means the block can be used in the path from source to destination. The non-zero value of mat[i][j] indicates number of maximum jumps rat can make from cell mat[i][j].In this variation, Rat is allowed to jump multiple steps at a time instead of 1. Examples: " }, { "code": null, "e": 1346, "s": 716, "text": "Input : { {2, 1, 0, 0},\n {3, 0, 0, 1},\n {0, 1, 0, 1},\n {0, 0, 0, 1}\n }\nOutput : { {1, 0, 0, 0},\n {1, 0, 0, 1},\n {0, 0, 0, 1},\n {0, 0, 0, 1}\n }\n\nExplanation \nRat started with M[0][0] and can jump upto 2 steps right/down. \nLet's try in horizontal direction - \nM[0][1] won't lead to solution and M[0][2] is 0 which is dead end. \nSo, backtrack and try in down direction. \nRat jump down to M[1][0] which eventually leads to solution. \n\nInput : { \n {2, 1, 0, 0},\n {2, 0, 0, 1},\n {0, 1, 0, 1},\n {0, 0, 0, 1}\n }\nOutput : Solution doesn't exist" }, { "code": null, "e": 1505, "s": 1346, "text": "Naive Algorithm The Naive Algorithm is to generate all paths from source to destination and one by one check if the generated path satisfies the constraints. " }, { "code": null, "e": 1641, "s": 1505, "text": "while there are untried paths\n{\n generate the next path\n if this path has all blocks as non-zero\n {\n print this path;\n }\n}" }, { "code": null, "e": 1665, "s": 1641, "text": "Backtracking Algorithm " }, { "code": null, "e": 2155, "s": 1665, "text": "If destination is reached\n print the solution matrix\nElse\n a) Mark current cell in solution matrix as 1. \n b) Move forward/jump (for each valid steps) in horizontal direction \n and recursively check if this move leads to a solution. \n c) If the move chosen in the above step doesn't lead to a solution\n then move down and check if this move leads to a solution. \n d) If none of the above solutions work then unmark this cell as 0 \n (BACKTRACK) and return false." }, { "code": null, "e": 2197, "s": 2155, "text": "Implementation of Backtracking solution " }, { "code": null, "e": 2201, "s": 2197, "text": "C++" }, { "code": null, "e": 2206, "s": 2201, "text": "Java" }, { "code": null, "e": 2214, "s": 2206, "text": "Python3" }, { "code": null, "e": 2217, "s": 2214, "text": "C#" }, { "code": null, "e": 2228, "s": 2217, "text": "Javascript" }, { "code": "/* C/C++ program to solve Rat in a Maze problemusing backtracking */#include <stdio.h> // Maze size#define N 4 bool solveMazeUtil(int maze[N][N], int x, int y, int sol[N][N]); /* A utility function to print solution matrixsol[N][N] */void printSolution(int sol[N][N]){ for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) printf(\" %d \", sol[i][j]); printf(\"\\n\"); }} /* A utility function to check if x, y is validindex for N*N maze */bool isSafe(int maze[N][N], int x, int y){ // if (x, y outside maze) return false if (x >= 0 && x < N && y >= 0 && y < N && maze[x][y] != 0) return true; return false;} /* This function solves the Maze problem usingBacktracking. It mainly uses solveMazeUtil() tosolve the problem. It returns false if no pathis possible, otherwise return true and printsthe path in the form of 1s. Please note thatthere may be more than one solutions,this function prints one of the feasible solutions.*/bool solveMaze(int maze[N][N]){ int sol[N][N] = { { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }; if (solveMazeUtil(maze, 0, 0, sol) == false) { printf(\"Solution doesn't exist\"); return false; } printSolution(sol); return true;} /* A recursive utility function to solve Maze problem */bool solveMazeUtil(int maze[N][N], int x, int y, int sol[N][N]){ // if (x, y is goal) return true if (x == N - 1 && y == N - 1) { sol[x][y] = 1; return true; } // Check if maze[x][y] is valid if (isSafe(maze, x, y) == true) { // mark x, y as part of solution path sol[x][y] = 1; /* Move forward in x direction */ for (int i = 1; i <= maze[x][y] && i < N; i++) { /* Move forward in x direction */ if (solveMazeUtil(maze, x + i, y, sol) == true) return true; /* If moving in x direction doesn't give solution then Move down in y direction */ if (solveMazeUtil(maze, x, y + i, sol) == true) return true; } /* If none of the above movements work then BACKTRACK: unmark x, y as part of solution path */ sol[x][y] = 0; return false; } return false;} // driver program to test above functionint main(){ int maze[N][N] = { { 2, 1, 0, 0 }, { 3, 0, 0, 1 }, { 0, 1, 0, 1 }, { 0, 0, 0, 1 } }; solveMaze(maze); return 0;}", "e": 4831, "s": 2228, "text": null }, { "code": "// Java program to solve Rat in a Maze problem// using backtrackingclass GFG{ // Maze size static int N = 4; /* A utility function to print solution matrix sol[N][N] */ static void printSolution(int sol[][]) { for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { System.out.printf(\" %d \", sol[i][j]); } System.out.printf(\"\\n\"); } } /* A utility function to check if x, y is valid index for N*N maze */ static boolean isSafe(int maze[][], int x, int y) { // if (x, y outside maze) return false if (x >= 0 && x < N && y >= 0 && y < N && maze[x][y] != 0) { return true; } return false; } /* This function solves the Maze problem using Backtracking. It mainly uses solveMazeUtil() to solve the problem. It returns false if no path is possible, otherwise return true and prints the path in the form of 1s. Please note that there may be more than one solutions, this function prints one of the feasible solutions.*/ static boolean solveMaze(int maze[][]) { int sol[][] = {{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}}; if (solveMazeUtil(maze, 0, 0, sol) == false) { System.out.printf(\"Solution doesn't exist\"); return false; } printSolution(sol); return true; } /* A recursive utility function to solve Maze problem */ static boolean solveMazeUtil(int maze[][], int x, int y, int sol[][]) { // if (x, y is goal) return true if (x == N - 1 && y == N - 1) { sol[x][y] = 1; return true; } // Check if maze[x][y] is valid if (isSafe(maze, x, y) == true) { // mark x, y as part of solution path sol[x][y] = 1; /* Move forward in x direction */ for (int i = 1; i <= maze[x][y] && i < N; i++) { /* Move forward in x direction */ if (solveMazeUtil(maze, x + i, y, sol) == true) { return true; } /* If moving in x direction doesn't give solution then Move down in y direction */ if (solveMazeUtil(maze, x, y + i, sol) == true) { return true; } } /* If none of the above movements work then BACKTRACK: unmark x, y as part of solution path */ sol[x][y] = 0; return false; } return false; } // Driver Code public static void main(String[] args) { int maze[][] = {{2, 1, 0, 0}, {3, 0, 0, 1}, {0, 1, 0, 1}, {0, 0, 0, 1}}; solveMaze(maze); }} // This code is contributed by Princi Singh", "e": 7892, "s": 4831, "text": null }, { "code": "\"\"\" Python3 program to solve Rat in aMaze problem using backtracking \"\"\" # Maze sizeN = 4 \"\"\" A utility function to print solution matrixsol \"\"\"def printSolution(sol): for i in range(N): for j in range(N): print(sol[i][j], end = \" \") print() \"\"\" A utility function to check ifx, y is valid index for N*N maze \"\"\"def isSafe(maze, x, y): # if (x, y outside maze) return false if (x >= 0 and x < N and y >= 0 and y < N and maze[x][y] != 0): return True return False \"\"\" This function solves the Maze problem usingBacktracking. It mainly uses solveMazeUtil() tosolve the problem. It returns false if no pathis possible, otherwise return True and printsthe path in the form of 1s. Please note thatthere may be more than one solutions,this function prints one of the feasible solutions.\"\"\"def solveMaze(maze): sol = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] if (solveMazeUtil(maze, 0, 0, sol) == False): print(\"Solution doesn't exist\") return False printSolution(sol) return True \"\"\" A recursive utility functionto solve Maze problem \"\"\"def solveMazeUtil(maze, x, y, sol): # if (x, y is goal) return True if (x == N - 1 and y == N - 1) : sol[x][y] = 1 return True # Check if maze[x][y] is valid if (isSafe(maze, x, y) == True): # mark x, y as part of solution path sol[x][y] = 1 \"\"\" Move forward in x direction \"\"\" for i in range(1, N): if (i <= maze[x][y]): \"\"\" Move forward in x direction \"\"\" if (solveMazeUtil(maze, x + i, y, sol) == True): return True \"\"\" If moving in x direction doesn't give solution then Move down in y direction \"\"\" if (solveMazeUtil(maze, x, y + i, sol) == True): return True \"\"\" If none of the above movements work then BACKTRACK: unmark x, y as part of solution path \"\"\" sol[x][y] = 0 return False return False # Driver Codemaze = [[2, 1, 0, 0], [3, 0, 0, 1], [0, 1, 0, 1], [0, 0, 0, 1]]solveMaze(maze) # This code is contributed by SHUBHAMSINGH10", "e": 10296, "s": 7892, "text": null }, { "code": "// C# program to solve Rat in a Maze problem// using backtrackingusing System; class GFG{ // Maze size static int N = 4; /* A utility function to print solution matrix sol[N, N] */ static void printSolution(int [,]sol) { for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { Console.Write(\" {0} \", sol[i, j]); } Console.Write(\"\\n\"); } } /* A utility function to check if x, y is valid index for N*N maze */ static Boolean isSafe(int [,]maze, int x, int y) { // if (x, y outside maze) return false if (x >= 0 && x < N && y >= 0 && y < N && maze[x, y] != 0) { return true; } return false; } /* This function solves the Maze problem using Backtracking. It mainly uses solveMazeUtil() to solve the problem. It returns false if no path is possible, otherwise return true and prints the path in the form of 1s. Please note that there may be more than one solutions, this function prints one of the feasible solutions.*/ static Boolean solveMaze(int [,]maze) { int [,]sol = {{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}}; if (solveMazeUtil(maze, 0, 0, sol) == false) { Console.Write(\"Solution doesn't exist\"); return false; } printSolution(sol); return true; } /* A recursive utility function to solve Maze problem */ static Boolean solveMazeUtil(int [,]maze, int x, int y, int [,]sol) { // if (x, y is goal) return true if (x == N - 1 && y == N - 1) { sol[x, y] = 1; return true; } // Check if maze[x,y] is valid if (isSafe(maze, x, y) == true) { // mark x, y as part of solution path sol[x, y] = 1; /* Move forward in x direction */ for (int i = 1; i <= maze[x, y] && i < N; i++) { /* Move forward in x direction */ if (solveMazeUtil(maze, x + i, y, sol) == true) { return true; } /* If moving in x direction doesn't give solution then Move down in y direction */ if (solveMazeUtil(maze, x, y + i, sol) == true) { return true; } } /* If none of the above movements work then BACKTRACK: unmark x, y as part of solution path */ sol[x, y] = 0; return false; } return false; } // Driver Code public static void Main(String[] args) { int [,]maze = {{2, 1, 0, 0}, {3, 0, 0, 1}, {0, 1, 0, 1}, {0, 0, 0, 1}}; solveMaze(maze); }} // This code is contributed by 29AjayKumar", "e": 13457, "s": 10296, "text": null }, { "code": "<script> // JavaScript program to solve Rat in a Maze problem// using backtracking // Maze size let N = 4; /* A utility function to print solution matrix sol[N][N] */ function printSolution(sol) { for (let i = 0; i < N; i++) { for (let j = 0; j < N; j++) { document.write(sol[i][j] + \" \"); } document.write(\"<br/>\"); } } /* A utility function to check if x, y is valid index for N*N maze */ function isSafe(maze, x, y) { // if (x, y outside maze) return false if (x >= 0 && x < N && y >= 0 && y < N && maze[x][y] != 0) { return true; } return false; } /* This function solves the Maze problem using Backtracking. It mainly uses solveMazeUtil() to solve the problem. It returns false if no path is possible, otherwise return true and print the path in the form of 1s. Please note that there may be more than one solutions, this function prints one of the feasible solutions.*/ function solveMaze(maze) { let sol = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]; if (solveMazeUtil(maze, 0, 0, sol) == false) { document.write(\"Solution doesn't exist\"); return false; } printSolution(sol); return true; } /* A recursive utility function to solve Maze problem */ function solveMazeUtil(maze, x, y, sol) { // if (x, y is goal) return true if (x == N - 1 && y == N - 1) { sol[x][y] = 1; return true; } // Check if maze[x][y] is valid if (isSafe(maze, x, y) == true) { // mark x, y as part of solution path sol[x][y] = 1; /* Move forward in x direction */ for (let i = 1; i <= maze[x][y] && i < N; i++) { /* Move forward in x direction */ if (solveMazeUtil(maze, x + i, y, sol) == true) { return true; } /* If moving in x direction doesn't give solution then Move down in y direction */ if (solveMazeUtil(maze, x, y + i, sol) == true) { return true; } } /* If none of the above movements work then BACKTRACK: unmark x, y as part of solution path */ sol[x][y] = 0; return false; } return false; } // Driver code let maze = [[2, 1, 0, 0], [3, 0, 0, 1], [0, 1, 0, 1], [0, 0, 0, 1]]; solveMaze(maze); // This code is contributed by splevel62.</script>", "e": 16409, "s": 13457, "text": null }, { "code": null, "e": 16456, "s": 16409, "text": "1 0 0 0 \n1 0 0 1 \n0 0 0 1 \n0 0 0 1" }, { "code": null, "e": 16471, "s": 16458, "text": "princi singh" }, { "code": null, "e": 16483, "s": 16471, "text": "29AjayKumar" }, { "code": null, "e": 16498, "s": 16483, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 16508, "s": 16498, "text": "splevel62" }, { "code": null, "e": 16525, "s": 16508, "text": "khushboogoyal499" }, { "code": null, "e": 16542, "s": 16525, "text": "surinderdawra388" }, { "code": null, "e": 16555, "s": 16542, "text": "Backtracking" }, { "code": null, "e": 16562, "s": 16555, "text": "Matrix" }, { "code": null, "e": 16569, "s": 16562, "text": "Matrix" }, { "code": null, "e": 16582, "s": 16569, "text": "Backtracking" }, { "code": null, "e": 16680, "s": 16582, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 16765, "s": 16680, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 16807, "s": 16765, "text": "Generate all the binary strings of N bits" }, { "code": null, "e": 16860, "s": 16807, "text": "Print all paths from a given source to a destination" }, { "code": null, "e": 16903, "s": 16860, "text": "Print all permutations of a string in Java" }, { "code": null, "e": 16963, "s": 16903, "text": "Find if there is a path of more than k length from a source" }, { "code": null, "e": 16999, "s": 16963, "text": "Print a given matrix in spiral form" }, { "code": null, "e": 17034, "s": 16999, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 17078, "s": 17034, "text": "Program to find largest element in an array" }, { "code": null, "e": 17100, "s": 17078, "text": "The Celebrity Problem" } ]
Dictionary Methods in Python Program
A python dictionary is a collection data type which is wrapped in braces, {}, with a series of key value pairs inside the braces. Each key is connected to a value. We use a key to access the value associated with that key. A key can be a number, a string, a list, or even another dictionary. There are many in-built methods available in the python Standard Library which is useful in dictionary operations. Below we will see the examples of most frequently used dictionary methods. The method keys() returns a list of all the available keys in the dictionary. Live Demo dict={'Name':'Harry','Rollno':30,'Dept':'cse','Marks':97} print(dict.keys()) Running the above code gives us the following result dict_keys(['Name', 'Rollno', 'Dept', 'Marks']) This method returns a list of dictionary's (key, value) as tuple. Live Demo dict={'Name':'Harry','Rollno':30,'Dept':'cse','Marks':97} print(dict.items()) Running the above code gives us the following result dict_items([('Name', 'Harry'), ('Rollno', 30), ('Dept', 'cse'), ('Marks', 97)]) This method returns list of dictionary dictionary's values from the key value pairs. Live Demo dict={'Name':'Harry','Rollno':30,'Dept':'cse','Marks':97} print(dict.values()) Running the above code gives us the following result: dict_values(['Harry', 30, 'cse', 97]) The method pop(key) Removes and returns the value of specified key. Live Demo dict={'Name':'Harry','Rollno':30,'Dept':'cse','Marks':97} dict.pop('Marks') print(dict) Running the above code gives us the following result: {'Name': 'Harry', 'Rollno': 30, 'Dept': 'cse'} This method Returns a shallow copy of dictionary. Live Demo dict={'Name':'Harry','Rollno':30,'Dept':'cse','Marks':97} dict_new=dict.copy() print(dict_new) Running the above code gives us the following result: {'Name': 'Harry', 'Rollno': 30, 'Dept': 'cse', 'Marks': 97} The method clear() Removes all elements of dictionary. Live Demo dict={'Name':'Harry','Rollno':30,'Dept':'cse','Marks':97} dict.clear() print(dict) Running the above code gives us the following result: {} This method returns value of given key or None as default if key is not in the dictionary. Live Demo dict={'Name':'Harry','Rollno':30,'Dept':'cse','Marks':97} print('\nName: ', dict.get('Name')) print('\nAge: ', dict.get('Age')) Running the above code gives us the following result: Name: Harry Age: None The update() inserts new item to the dictionary. Live Demo dict={'Name':'Harry','Rollno':30,'Dept':'cse','Marks':97} dict.update({'Age':22}) print(dict) Running the above code gives us the following result {'Name': 'Harry', 'Rollno': 30, 'Dept': 'cse', 'Marks': 97, 'Age': 22}
[ { "code": null, "e": 1354, "s": 1062, "text": "A python dictionary is a collection data type which is wrapped in braces, {}, with a series of key value pairs inside the braces. Each key is connected to a value. We use a key to access the value associated with that key. A key can be a number, a string, a list, or even another dictionary." }, { "code": null, "e": 1544, "s": 1354, "text": "There are many in-built methods available in the python Standard Library which is useful in dictionary operations. Below we will see the examples of most frequently used dictionary methods." }, { "code": null, "e": 1622, "s": 1544, "text": "The method keys() returns a list of all the available keys in the dictionary." }, { "code": null, "e": 1633, "s": 1622, "text": " Live Demo" }, { "code": null, "e": 1710, "s": 1633, "text": "dict={'Name':'Harry','Rollno':30,'Dept':'cse','Marks':97}\nprint(dict.keys())" }, { "code": null, "e": 1763, "s": 1710, "text": "Running the above code gives us the following result" }, { "code": null, "e": 1810, "s": 1763, "text": "dict_keys(['Name', 'Rollno', 'Dept', 'Marks'])" }, { "code": null, "e": 1876, "s": 1810, "text": "This method returns a list of dictionary's (key, value) as tuple." }, { "code": null, "e": 1887, "s": 1876, "text": " Live Demo" }, { "code": null, "e": 1965, "s": 1887, "text": "dict={'Name':'Harry','Rollno':30,'Dept':'cse','Marks':97}\nprint(dict.items())" }, { "code": null, "e": 2018, "s": 1965, "text": "Running the above code gives us the following result" }, { "code": null, "e": 2098, "s": 2018, "text": "dict_items([('Name', 'Harry'), ('Rollno', 30), ('Dept', 'cse'), ('Marks', 97)])" }, { "code": null, "e": 2183, "s": 2098, "text": "This method returns list of dictionary dictionary's values from the key value pairs." }, { "code": null, "e": 2194, "s": 2183, "text": " Live Demo" }, { "code": null, "e": 2273, "s": 2194, "text": "dict={'Name':'Harry','Rollno':30,'Dept':'cse','Marks':97}\nprint(dict.values())" }, { "code": null, "e": 2327, "s": 2273, "text": "Running the above code gives us the following result:" }, { "code": null, "e": 2365, "s": 2327, "text": "dict_values(['Harry', 30, 'cse', 97])" }, { "code": null, "e": 2433, "s": 2365, "text": "The method pop(key) Removes and returns the value of specified key." }, { "code": null, "e": 2444, "s": 2433, "text": " Live Demo" }, { "code": null, "e": 2532, "s": 2444, "text": "dict={'Name':'Harry','Rollno':30,'Dept':'cse','Marks':97}\ndict.pop('Marks')\nprint(dict)" }, { "code": null, "e": 2586, "s": 2532, "text": "Running the above code gives us the following result:" }, { "code": null, "e": 2633, "s": 2586, "text": "{'Name': 'Harry', 'Rollno': 30, 'Dept': 'cse'}" }, { "code": null, "e": 2683, "s": 2633, "text": "This method Returns a shallow copy of dictionary." }, { "code": null, "e": 2694, "s": 2683, "text": " Live Demo" }, { "code": null, "e": 2789, "s": 2694, "text": "dict={'Name':'Harry','Rollno':30,'Dept':'cse','Marks':97}\ndict_new=dict.copy()\nprint(dict_new)" }, { "code": null, "e": 2843, "s": 2789, "text": "Running the above code gives us the following result:" }, { "code": null, "e": 2903, "s": 2843, "text": "{'Name': 'Harry', 'Rollno': 30, 'Dept': 'cse', 'Marks': 97}" }, { "code": null, "e": 2958, "s": 2903, "text": "The method clear() Removes all elements of dictionary." }, { "code": null, "e": 2969, "s": 2958, "text": " Live Demo" }, { "code": null, "e": 3052, "s": 2969, "text": "dict={'Name':'Harry','Rollno':30,'Dept':'cse','Marks':97}\ndict.clear()\nprint(dict)" }, { "code": null, "e": 3106, "s": 3052, "text": "Running the above code gives us the following result:" }, { "code": null, "e": 3109, "s": 3106, "text": "{}" }, { "code": null, "e": 3200, "s": 3109, "text": "This method returns value of given key or None as default if key is not in the dictionary." }, { "code": null, "e": 3211, "s": 3200, "text": " Live Demo" }, { "code": null, "e": 3339, "s": 3211, "text": "dict={'Name':'Harry','Rollno':30,'Dept':'cse','Marks':97}\nprint('\\nName: ', dict.get('Name'))\nprint('\\nAge: ', dict.get('Age'))" }, { "code": null, "e": 3393, "s": 3339, "text": "Running the above code gives us the following result:" }, { "code": null, "e": 3415, "s": 3393, "text": "Name: Harry\nAge: None" }, { "code": null, "e": 3464, "s": 3415, "text": "The update() inserts new item to the dictionary." }, { "code": null, "e": 3475, "s": 3464, "text": " Live Demo" }, { "code": null, "e": 3569, "s": 3475, "text": "dict={'Name':'Harry','Rollno':30,'Dept':'cse','Marks':97}\ndict.update({'Age':22})\nprint(dict)" }, { "code": null, "e": 3622, "s": 3569, "text": "Running the above code gives us the following result" }, { "code": null, "e": 3693, "s": 3622, "text": "{'Name': 'Harry', 'Rollno': 30, 'Dept': 'cse', 'Marks': 97, 'Age': 22}" } ]
Complex Numbers in C#
To work WITH and display complex numbers in C#, you need to check for real and imaginary values. A complex number like 7+5i is formed up of two parts, a real part 7, and an imaginary part 5. Here, the imaginary part is the multiple of i. To display complete numbers, use the − public struct Complex To add both the complex numbers, you need to add the real and imaginary part − public static Complex operator +(Complex one, Complex two) { return new Complex(one.real + two.real, one.imaginary + two.imaginary); } You can try to run the following code to work with complex numbers in C#. Live Demo using System; public struct Complex { public int real; public int imaginary; public Complex(int real, int imaginary) { this.real = real; this.imaginary = imaginary; } public static Complex operator +(Complex one, Complex two) { return new Complex(one.real + two.real, one.imaginary + two.imaginary); } public override string ToString() { return (String.Format("{0} + {1}i", real, imaginary)); } } class Demo { static void Main() { Complex val1 = new Complex(7, 1); Complex val2 = new Complex(2, 6); // Add both of them Complex res = val1 + val2; Console.WriteLine("First: {0}", val1); Console.WriteLine("Second: {0}", val2); // display the result Console.WriteLine("Result (Sum): {0}", res); Console.ReadLine(); } } First: 7 + 1i Second: 2 + 6i Result (Sum): 9 + 7i
[ { "code": null, "e": 1159, "s": 1062, "text": "To work WITH and display complex numbers in C#, you need to check for real and imaginary values." }, { "code": null, "e": 1300, "s": 1159, "text": "A complex number like 7+5i is formed up of two parts, a real part 7, and an imaginary part 5. Here, the imaginary part is the multiple of i." }, { "code": null, "e": 1339, "s": 1300, "text": "To display complete numbers, use the −" }, { "code": null, "e": 1361, "s": 1339, "text": "public struct Complex" }, { "code": null, "e": 1440, "s": 1361, "text": "To add both the complex numbers, you need to add the real and imaginary part −" }, { "code": null, "e": 1578, "s": 1440, "text": "public static Complex operator +(Complex one, Complex two) {\n return new Complex(one.real + two.real, one.imaginary + two.imaginary);\n}" }, { "code": null, "e": 1652, "s": 1578, "text": "You can try to run the following code to work with complex numbers in C#." }, { "code": null, "e": 1663, "s": 1652, "text": " Live Demo" }, { "code": null, "e": 2487, "s": 1663, "text": "using System;\npublic struct Complex {\n public int real;\n public int imaginary;\n public Complex(int real, int imaginary) {\n this.real = real;\n this.imaginary = imaginary;\n }\n public static Complex operator +(Complex one, Complex two) {\n return new Complex(one.real + two.real, one.imaginary + two.imaginary);\n }\n public override string ToString() {\n return (String.Format(\"{0} + {1}i\", real, imaginary));\n }\n}\nclass Demo {\n static void Main() {\n Complex val1 = new Complex(7, 1);\n Complex val2 = new Complex(2, 6);\n // Add both of them\n Complex res = val1 + val2;\n Console.WriteLine(\"First: {0}\", val1);\n Console.WriteLine(\"Second: {0}\", val2);\n // display the result\n Console.WriteLine(\"Result (Sum): {0}\", res);\n Console.ReadLine();\n }\n}" }, { "code": null, "e": 2537, "s": 2487, "text": "First: 7 + 1i\nSecond: 2 + 6i\nResult (Sum): 9 + 7i" } ]
Android - Twitter Integration
Android allows your application to connect to twitter and share data or any kind of updates on twitter. This chapter is about integrating twitter into your application. There are two ways through which you can integrate twitter and share something from your application. These ways are listed below − Twitter SDK (Twitter4J) Intent Share This is the first way of connecting with Twitter. You have to register your application and then receive some Application Id, and then you have to download the twitter SDK and add it to your project. The steps are listed below − Create a new twitter application at dev.twitter.com/apps/new and fill all the information. It is shown below − Now under settings tab, change the access to read,write and access messages and save the settings. It is shown below − If everything works fine, you will receive an consumer ID with the secret. Just copy the application id and save it somewhere. It is shown in the image below − Download twitter sdk here. Copy the twitter4J jar into your project libs folder. Once everything is complete , you can run the twitter 4J samples which can be found here. In order to use twitter, you need to instantiate an object of twitter class.It can be done by calling the static method getsingleton(). Its syntax is given below. // The factory instance is re-usable and thread safe. Twitter twitter = TwitterFactory.getSingleton(); In order to update the status , you can call updateStatus() method. Its syntax is given below − Status status = twitter.updateStatus(latestStatus); System.out.println("Successfully updated the status to [" + status.getText() + "]."); Intent share is used to share data between applications. In this strategy, we will not handle the SDK stuff, but let the twitter application handles it. We will simply call the twitter application and pass the data to share. This way, we can share something on twitter. Android provides intent library to share data between activities and applications. In order to use it as share intent, we have to specify the type of the share intent to ACTION_SEND. Its syntax is given below − Intent shareIntent = new Intent(); shareIntent.setAction(Intent.ACTION_SEND); Next thing you need to is to define the type of data to pass, and then pass the data. Its syntax is given below − shareIntent.setType("text/plain"); shareIntent.putExtra(Intent.EXTRA_TEXT, "Hello, from tutorialspoint"); startActivity(Intent.createChooser(shareIntent, "Share your thoughts")); Apart from the these methods, there are other methods available that allows intent handling. They are listed below − addCategory(String category) This method add a new category to the intent. createChooser(Intent target, CharSequence title) Convenience function for creating a ACTION_CHOOSER Intent getAction() This method retrieve the general action to be performed, such as ACTION_VIEW getCategories() This method return the set of all categories in the intent and the current scaling event putExtra(String name, int value) This method add extended data to the intent. toString() This method returns a string containing a concise, human-readable description of this object Here is an example demonstrating the use of IntentShare to share data on twitter. It creates a basic application that allows you to share some text on twitter. To experiment with this example , you can run this on an actual device or in an emulator. Following is the content of the modified MainActivity.java. package com.example.sairamkrishna.myapplication; import android.content.Intent; import android.net.Uri; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageView; import java.io.FileNotFoundException; import java.io.InputStream; public class MainActivity extends ActionBarActivity { private ImageView img; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); img=(ImageView)findViewById(R.id.imageView); Button b1=(Button)findViewById(R.id.button); b1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent sharingIntent = new Intent(Intent.ACTION_SEND); Uri screenshotUri = Uri.parse("android.resource://comexample.sairamkrishna.myapplication/*"); try { InputStream stream = getContentResolver().openInputStream(screenshotUri); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } sharingIntent.setType("image/jpeg"); sharingIntent.putExtra(Intent.EXTRA_STREAM, screenshotUri); startActivity(Intent.createChooser(sharingIntent, "Share image using")); } }); } } Following is the modified content of the xml res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" 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"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/textView" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:textSize="30dp" android:text="Twitter share " /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Tutorials Point" android:id="@+id/textView2" android:layout_below="@+id/textView" android:layout_centerHorizontal="true" android:textSize="35dp" android:textColor="#ff16ff01" /> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/imageView" android:layout_below="@+id/textView2" android:layout_centerHorizontal="true" android:src="@drawable/abc"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Share" android:id="@+id/button" android:layout_marginTop="61dp" android:layout_below="@+id/imageView" android:layout_centerHorizontal="true" /> </RelativeLayout> Following is the content of AndroidManifest.xml file. <?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 your default screen − Now just tap on the button and you will see a list of share providers. Now just select twitter from that list and then write any message. It is shown in the image below − Now just select the tweet button and then it would be post on your twitter page. It 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": 3776, "s": 3607, "text": "Android allows your application to connect to twitter and share data or any kind of updates on twitter. This chapter is about integrating twitter into your application." }, { "code": null, "e": 3908, "s": 3776, "text": "There are two ways through which you can integrate twitter and share something from your application. These ways are listed below −" }, { "code": null, "e": 3932, "s": 3908, "text": "Twitter SDK (Twitter4J)" }, { "code": null, "e": 3945, "s": 3932, "text": "Intent Share" }, { "code": null, "e": 4174, "s": 3945, "text": "This is the first way of connecting with Twitter. You have to register your application and then receive some Application Id, and then you have to download the twitter SDK and add it to your project. The steps are listed below −" }, { "code": null, "e": 4286, "s": 4174, "text": "Create a new twitter application at dev.twitter.com/apps/new and fill all the information. It is shown below −" }, { "code": null, "e": 4405, "s": 4286, "text": "Now under settings tab, change the access to read,write and access messages and save the settings. It is shown below −" }, { "code": null, "e": 4565, "s": 4405, "text": "If everything works fine, you will receive an consumer ID with the secret. Just copy the application id and save it somewhere. It is shown in the image below −" }, { "code": null, "e": 4646, "s": 4565, "text": "Download twitter sdk here. Copy the twitter4J jar into your project libs folder." }, { "code": null, "e": 4736, "s": 4646, "text": "Once everything is complete , you can run the twitter 4J samples which can be found here." }, { "code": null, "e": 4899, "s": 4736, "text": "In order to use twitter, you need to instantiate an object of twitter class.It can be done by calling the static method getsingleton(). Its syntax is given below." }, { "code": null, "e": 5002, "s": 4899, "text": "// The factory instance is re-usable and thread safe.\nTwitter twitter = TwitterFactory.getSingleton();" }, { "code": null, "e": 5098, "s": 5002, "text": "In order to update the status , you can call updateStatus() method. Its syntax is given below −" }, { "code": null, "e": 5236, "s": 5098, "text": "Status status = twitter.updateStatus(latestStatus);\nSystem.out.println(\"Successfully updated the status to [\" + status.getText() + \"].\");" }, { "code": null, "e": 5506, "s": 5236, "text": "Intent share is used to share data between applications. In this strategy, we will not handle the SDK stuff, but let the twitter application handles it. We will simply call the twitter application and pass the data to share. This way, we can share something on twitter." }, { "code": null, "e": 5717, "s": 5506, "text": "Android provides intent library to share data between activities and applications. In order to use it as share intent, we have to specify the type of the share intent to ACTION_SEND. Its syntax is given below −" }, { "code": null, "e": 5795, "s": 5717, "text": "Intent shareIntent = new Intent();\nshareIntent.setAction(Intent.ACTION_SEND);" }, { "code": null, "e": 5909, "s": 5795, "text": "Next thing you need to is to define the type of data to pass, and then pass the data. Its syntax is given below −" }, { "code": null, "e": 6088, "s": 5909, "text": "shareIntent.setType(\"text/plain\");\nshareIntent.putExtra(Intent.EXTRA_TEXT, \"Hello, from tutorialspoint\");\nstartActivity(Intent.createChooser(shareIntent, \"Share your thoughts\"));" }, { "code": null, "e": 6205, "s": 6088, "text": "Apart from the these methods, there are other methods available that allows intent handling. They are listed below −" }, { "code": null, "e": 6234, "s": 6205, "text": "addCategory(String category)" }, { "code": null, "e": 6280, "s": 6234, "text": "This method add a new category to the intent." }, { "code": null, "e": 6329, "s": 6280, "text": "createChooser(Intent target, CharSequence title)" }, { "code": null, "e": 6387, "s": 6329, "text": "Convenience function for creating a ACTION_CHOOSER Intent" }, { "code": null, "e": 6399, "s": 6387, "text": "getAction()" }, { "code": null, "e": 6476, "s": 6399, "text": "This method retrieve the general action to be performed, such as ACTION_VIEW" }, { "code": null, "e": 6492, "s": 6476, "text": "getCategories()" }, { "code": null, "e": 6581, "s": 6492, "text": "This method return the set of all categories in the intent and the current scaling event" }, { "code": null, "e": 6614, "s": 6581, "text": "putExtra(String name, int value)" }, { "code": null, "e": 6659, "s": 6614, "text": "This method add extended data to the intent." }, { "code": null, "e": 6670, "s": 6659, "text": "toString()" }, { "code": null, "e": 6763, "s": 6670, "text": "This method returns a string containing a concise, human-readable description of this object" }, { "code": null, "e": 6923, "s": 6763, "text": "Here is an example demonstrating the use of IntentShare to share data on twitter. It creates a basic application that allows you to share some text on twitter." }, { "code": null, "e": 7013, "s": 6923, "text": "To experiment with this example , you can run this on an actual device or in an emulator." }, { "code": null, "e": 7074, "s": 7013, "text": "Following is the content of the modified MainActivity.java." }, { "code": null, "e": 8526, "s": 7074, "text": "package com.example.sairamkrishna.myapplication;\n\nimport android.content.Intent;\nimport android.net.Uri;\nimport android.support.v7.app.ActionBarActivity;\nimport android.os.Bundle;\nimport android.view.View;\n\nimport android.widget.Button;\nimport android.widget.ImageView;\nimport java.io.FileNotFoundException;\nimport java.io.InputStream;\n\npublic class MainActivity extends ActionBarActivity {\n private ImageView img;\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n\n img=(ImageView)findViewById(R.id.imageView);\n Button b1=(Button)findViewById(R.id.button);\n\n b1.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n Intent sharingIntent = new Intent(Intent.ACTION_SEND);\n Uri screenshotUri = Uri.parse(\"android.resource://comexample.sairamkrishna.myapplication/*\");\n\n try {\n InputStream stream = getContentResolver().openInputStream(screenshotUri);\n } catch (FileNotFoundException e) {\n // TODO Auto-generated catch block\n e.printStackTrace();\n }\n sharingIntent.setType(\"image/jpeg\");\n sharingIntent.putExtra(Intent.EXTRA_STREAM, screenshotUri);\n startActivity(Intent.createChooser(sharingIntent, \"Share image using\"));\n }\n });\n }\n}" }, { "code": null, "e": 8601, "s": 8526, "text": "Following is the modified content of the xml res/layout/activity_main.xml." }, { "code": null, "e": 10286, "s": 8601, "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\" \n 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\" tools:context=\".MainActivity\">\n\n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:id=\"@+id/textView\"\n android:layout_alignParentTop=\"true\"\n android:layout_centerHorizontal=\"true\"\n android:textSize=\"30dp\"\n android:text=\"Twitter share \" />\n\n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Tutorials Point\"\n android:id=\"@+id/textView2\"\n android:layout_below=\"@+id/textView\"\n android:layout_centerHorizontal=\"true\"\n android:textSize=\"35dp\"\n android:textColor=\"#ff16ff01\" />\n\n <ImageView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:id=\"@+id/imageView\"\n android:layout_below=\"@+id/textView2\"\n android:layout_centerHorizontal=\"true\"\n android:src=\"@drawable/abc\"/>\n\n <Button\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Share\"\n android:id=\"@+id/button\"\n android:layout_marginTop=\"61dp\"\n android:layout_below=\"@+id/imageView\"\n android:layout_centerHorizontal=\"true\" />\n\n</RelativeLayout>" }, { "code": null, "e": 10340, "s": 10286, "text": "Following is the content of AndroidManifest.xml file." }, { "code": null, "e": 11042, "s": 10340, "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\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": 11421, "s": 11042, "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": 11535, "s": 11421, "text": "Select your mobile device as an option and then check your mobile device which will display your default screen −" }, { "code": null, "e": 11606, "s": 11535, "text": "Now just tap on the button and you will see a list of share providers." }, { "code": null, "e": 11706, "s": 11606, "text": "Now just select twitter from that list and then write any message. It is shown in the image below −" }, { "code": null, "e": 11807, "s": 11706, "text": "Now just select the tweet button and then it would be post on your twitter page. It is shown below −" }, { "code": null, "e": 11842, "s": 11807, "text": "\n 46 Lectures \n 7.5 hours \n" }, { "code": null, "e": 11854, "s": 11842, "text": " Aditya Dua" }, { "code": null, "e": 11889, "s": 11854, "text": "\n 32 Lectures \n 3.5 hours \n" }, { "code": null, "e": 11903, "s": 11889, "text": " Sharad Kumar" }, { "code": null, "e": 11935, "s": 11903, "text": "\n 9 Lectures \n 1 hours \n" }, { "code": null, "e": 11952, "s": 11935, "text": " Abhilash Nelson" }, { "code": null, "e": 11987, "s": 11952, "text": "\n 14 Lectures \n 1.5 hours \n" }, { "code": null, "e": 12004, "s": 11987, "text": " Abhilash Nelson" }, { "code": null, "e": 12039, "s": 12004, "text": "\n 15 Lectures \n 1.5 hours \n" }, { "code": null, "e": 12056, "s": 12039, "text": " Abhilash Nelson" }, { "code": null, "e": 12089, "s": 12056, "text": "\n 10 Lectures \n 1 hours \n" }, { "code": null, "e": 12106, "s": 12089, "text": " Abhilash Nelson" }, { "code": null, "e": 12113, "s": 12106, "text": " Print" }, { "code": null, "e": 12124, "s": 12113, "text": " Add Notes" } ]
Random Forest in Python. A Practical End-to-End Machine Learning... | by Will Koehrsen | Towards Data Science
A Practical End-to-End Machine Learning Example There has never been a better time to get into machine learning. With the learning resources available online, free open-source tools with implementations of any algorithm imaginable, and the cheap availability of computing power through cloud services such as AWS, machine learning is truly a field that has been democratized by the internet. Anyone with access to a laptop and a willingness to learn can try out state-of-the-art algorithms in minutes. With a little more time, you can develop practical models to help in your daily life or at work (or even switch into the machine learning field and reap the economic benefits). This post will walk you through an end-to-end implementation of the powerful random forest machine learning model. It is meant to serve as a complement to my conceptual explanation of the random forest, but can be read entirely on its own as long as you have the basic idea of a decision tree and a random forest. A follow-up post details how we can improve upon the model built here. There will of course be Python code here, however, it is not meant to intimate anyone, but rather to show how accessible machine learning is with the resources available today! The complete project with data is available on GitHub, and the data file and Jupyter Notebook can also be downloaded from Google Drive. All you need is a laptop with Python installed and the ability to start a Jupyter Notebook and you can follow along. (For installing Python and running a Jupyter notebook check out this guide). There will be a few necessary machine learning topics touched on here, but I will try to make them clear and provide resources for learning more for those interested. The problem we will tackle is predicting the max temperature for tomorrow in our city using one year of past weather data. I am using Seattle, WA but feel free to find data for your own city using the NOAA Climate Data Online tool. We are going to act as if we don’t have access to any weather forecasts (and besides, it’s more fun to make our own predictions rather than rely on others). What we do have access to is one year of historical max temperatures, the temperatures for the previous two days, and an estimate from a friend who is always claiming to know everything about the weather. This is a supervised, regression machine learning problem. It’s supervised because we have both the features (data for the city) and the targets (temperature) that we want to predict. During training, we give the random forest both the features and targets and it must learn how to map the data to a prediction. Moreover, this is a regression task because the target value is continuous (as opposed to discrete classes in classification). That’s pretty much all the background we need, so let’s start! Before we jump right into programming, we should lay out a brief guide to keep us on track. The following steps form the basis for any machine learning workflow once we have a problem and model in mind: State the question and determine required dataAcquire the data in an accessible formatIdentify and correct missing data points/anomalies as requiredPrepare the data for the machine learning modelEstablish a baseline model that you aim to exceedTrain the model on the training dataMake predictions on the test dataCompare predictions to the known test set targets and calculate performance metricsIf performance is not satisfactory, adjust the model, acquire more data, or try a different modeling techniqueInterpret model and report results visually and numerically State the question and determine required data Acquire the data in an accessible format Identify and correct missing data points/anomalies as required Prepare the data for the machine learning model Establish a baseline model that you aim to exceed Train the model on the training data Make predictions on the test data Compare predictions to the known test set targets and calculate performance metrics If performance is not satisfactory, adjust the model, acquire more data, or try a different modeling technique Interpret model and report results visually and numerically Step 1 is already checked off! We have our question: “can we predict the max temperature tomorrow for our city?” and we know we have access to historical max temperatures for the past year in Seattle, WA. First, we need some data. To use a realistic example, I retrieved weather data for Seattle, WA from 2016 using the NOAA Climate Data Online tool. Generally, about 80% of the time spent in data analysis is cleaning and retrieving data, but this workload can be reduced by finding high-quality data sources. The NOAA tool is surprisingly easy to use and temperature data can be downloaded as clean csv files which can be parsed in languages such as Python or R. The complete data file is available for download for those wanting to follow along. The following Python code loads in the csv data and displays the structure of the data: # Pandas is used for data manipulationimport pandas as pd# Read in data and display first 5 rowsfeatures = pd.read_csv('temps.csv')features.head(5) The information is in the tidy data format with each row forming one observation, with the variable values in the columns. Following are explanations of the columns: year: 2016 for all data points month: number for month of the year day: number for day of the year week: day of the week as a character string temp_2: max temperature 2 days prior temp_1: max temperature 1 day prior average: historical average max temperature actual: max temperature measurement friend: your friend’s prediction, a random number between 20 below the average and 20 above the average If we look at the dimensions of the data, we notice only there are only 348 rows, which doesn’t quite agree with the 366 days we know there were in 2016. Looking through the data from the NOAA, I noticed several missing days, which is a great reminder that data collected in the real-world will never be perfect. Missing data can impact an analysis as can incorrect data or outliers. In this case, the missing data will not have a large effect, and the data quality is good because of the source. We also can see there are nine columns which represent eight features and the one target (‘actual’). print('The shape of our features is:', features.shape)The shape of our features is: (348, 9) To identify anomalies, we can quickly compute summary statistics. # Descriptive statistics for each columnfeatures.describe() There are not any data points that immediately appear as anomalous and no zeros in any of the measurement columns. Another method to verify the quality of the data is make basic plots. Often it is easier to spot anomalies in a graph than in numbers. I have left out the actual code here, because plotting is Python is non-intuitive but feel free to refer to the notebook for the complete implementation (like any good data scientist, I pretty much copy and pasted the plotting code from Stack Overflow). Examining the quantitative statistics and the graphs, we can feel confident in the high quality of our data. There are no clear outliers, and although there are a few missing points, they will not detract from the analysis. Unfortunately, we aren’t quite at the point where you can just feed raw data into a model and have it return an answer (although people are working on this)! We will need to do some minor modification to put our data into machine-understandable terms. We will use the Python library Pandas for our data manipulation relying, on the structure known as a dataframe, which is basically an excel spreadsheet with rows and columns. The exact steps for preparation of the data will depend on the model used and the data gathered, but some amount of data manipulation will be required for any machine learning application. One-Hot Encoding The first step for us is known as one-hot encoding of the data. This process takes categorical variables, such as days of the week and converts it to a numerical representation without an arbitrary ordering. Days of the week are intuitive to us because we use them all the time. You will (hopefully) never find anyone who doesn’t know that ‘Mon’ refers to the first day of the workweek, but machines do not have any intuitive knowledge. What computers know is numbers and for machine learning we must accommodate them. We could simply map days of the week to numbers 1–7, but this might lead to the algorithm placing more importance on Sunday because it has a higher numerical value. Instead, we change the single column of weekdays into seven columns of binary data. This is best illustrated pictorially. One hot encoding takes this: and turns it into So, if a data point is a Wednesday, it will have a 1 in the Wednesday column and a 0 in all other columns. This process can be done in pandas in a single line! # One-hot encode the data using pandas get_dummiesfeatures = pd.get_dummies(features)# Display the first 5 rows of the last 12 columnsfeatures.iloc[:,5:].head(5) Snapshot of data after one-hot encoding: The shape of our data is now 349 x 15 and all of the column are numbers, just how the algorithm likes it! Features and Targets and Convert Data to Arrays Now, we need to separate the data into the features and targets. The target, also known as the label, is the value we want to predict, in this case the actual max temperature and the features are all the columns the model uses to make a prediction. We will also convert the Pandas dataframes to Numpy arrays because that is the way the algorithm works. (I save the column headers, which are the names of the features, to a list to use for later visualization). # Use numpy to convert to arraysimport numpy as np# Labels are the values we want to predictlabels = np.array(features['actual'])# Remove the labels from the features# axis 1 refers to the columnsfeatures= features.drop('actual', axis = 1)# Saving feature names for later usefeature_list = list(features.columns)# Convert to numpy arrayfeatures = np.array(features) Training and Testing Sets There is one final step of data preparation: splitting data into training and testing sets. During training, we let the model ‘see’ the answers, in this case the actual temperature, so it can learn how to predict the temperature from the features. We expect there to be some relationship between all the features and the target value, and the model’s job is to learn this relationship during training. Then, when it comes time to evaluate the model, we ask it to make predictions on a testing set where it only has access to the features (not the answers)! Because we do have the actual answers for the test set, we can compare these predictions to the true value to judge how accurate the model is. Generally, when training a model, we randomly split the data into training and testing sets to get a representation of all data points (if we trained on the first nine months of the year and then used the final three months for prediction, our algorithm would not perform well because it has not seen any data from those last three months.) I am setting the random state to 42 which means the results will be the same each time I run the split for reproducible results. The following code splits the data sets with another single line: # Using Skicit-learn to split data into training and testing setsfrom sklearn.model_selection import train_test_split# Split the data into training and testing setstrain_features, test_features, train_labels, test_labels = train_test_split(features, labels, test_size = 0.25, random_state = 42) We can look at the shape of all the data to make sure we did everything correctly. We expect the training features number of columns to match the testing feature number of columns and the number of rows to match for the respective training and testing features and the labels : print('Training Features Shape:', train_features.shape)print('Training Labels Shape:', train_labels.shape)print('Testing Features Shape:', test_features.shape)print('Testing Labels Shape:', test_labels.shape)Training Features Shape: (261, 14)Training Labels Shape: (261,)Testing Features Shape: (87, 14)Testing Labels Shape: (87,) It looks as if everything is in order! Just to recap, to get the data into a form acceptable for machine learning we: One-hot encoded categorical variablesSplit data into features and labelsConverted to arraysSplit data into training and testing sets One-hot encoded categorical variables Split data into features and labels Converted to arrays Split data into training and testing sets Depending on the initial data set, there may be extra work involved such as removing outliers, imputing missing values, or converting temporal variables into cyclical representations. These steps may seem arbitrary at first, but once you get the basic workflow, it will be generally the same for any machine learning problem. It’s all about taking human-readable data and putting it into a form that can be understood by a machine learning model. Before we can make and evaluate predictions, we need to establish a baseline, a sensible measure that we hope to beat with our model. If our model cannot improve upon the baseline, then it will be a failure and we should try a different model or admit that machine learning is not right for our problem. The baseline prediction for our case can be the historical max temperature averages. In other words, our baseline is the error we would get if we simply predicted the average max temperature for all days. # The baseline predictions are the historical averagesbaseline_preds = test_features[:, feature_list.index('average')]# Baseline errors, and display average baseline errorbaseline_errors = abs(baseline_preds - test_labels)print('Average baseline error: ', round(np.mean(baseline_errors), 2))Average baseline error: 5.06 degrees. We now have our goal! If we can’t beat an average error of 5 degrees, then we need to rethink our approach. After all the work of data preparation, creating and training the model is pretty simple using Scikit-learn. We import the random forest regression model from skicit-learn, instantiate the model, and fit (scikit-learn’s name for training) the model on the training data. (Again setting the random state for reproducible results). This entire process is only 3 lines in scikit-learn! # Import the model we are usingfrom sklearn.ensemble import RandomForestRegressor# Instantiate model with 1000 decision treesrf = RandomForestRegressor(n_estimators = 1000, random_state = 42)# Train the model on training datarf.fit(train_features, train_labels); Our model has now been trained to learn the relationships between the features and the targets. The next step is figuring out how good the model is! To do this we make predictions on the test features (the model is never allowed to see the test answers). We then compare the predictions to the known answers. When performing regression, we need to make sure to use the absolute error because we expect some of our answers to be low and some to be high. We are interested in how far away our average prediction is from the actual value so we take the absolute value (as we also did when establishing the baseline). Making predictions with out model is another 1-line command in Skicit-learn. # Use the forest's predict method on the test datapredictions = rf.predict(test_features)# Calculate the absolute errorserrors = abs(predictions - test_labels)# Print out the mean absolute error (mae)print('Mean Absolute Error:', round(np.mean(errors), 2), 'degrees.')Mean Absolute Error: 3.83 degrees. Our average estimate is off by 3.83 degrees. That is more than a 1 degree average improvement over the baseline. Although this might not seem significant, it is nearly 25% better than the baseline, which, depending on the field and the problem, could represent millions of dollars to a company. To put our predictions in perspective, we can calculate an accuracy using the mean average percentage error subtracted from 100 %. # Calculate mean absolute percentage error (MAPE)mape = 100 * (errors / test_labels)# Calculate and display accuracyaccuracy = 100 - np.mean(mape)print('Accuracy:', round(accuracy, 2), '%.')Accuracy: 93.99 %. That looks pretty good! Our model has learned how to predict the maximum temperature for the next day in Seattle with 94% accuracy. In the usual machine learning workflow, this would be when start hyperparameter tuning. This is a complicated phrase that means “adjust the settings to improve performance” (The settings are known as hyperparameters to distinguish them from model parameters learned during training). The most common way to do this is simply make a bunch of models with different settings, evaluate them all on the same validation set, and see which one does best. Of course, this would be a tedious process to do by hand, and there are automated methods to do this process in Skicit-learn. Hyperparameter tuning is often more engineering than theory-based, and I would encourage anyone interested to check out the documentation and start playing around! An accuracy of 94% is satisfactory for this problem, but keep in mind that the first model built will almost never be the model that makes it to production. At this point, we know our model is good, but it’s pretty much a black box. We feed in some Numpy arrays for training, ask it to make a prediction, evaluate the predictions, and see that they are reasonable. The question is: how does this model arrive at the values? There are two approaches to get under the hood of the random forest: first, we can look at a single tree in the forest, and second, we can look at the feature importances of our explanatory variables. One of the coolest parts of the Random Forest implementation in Skicit-learn is we can actually examine any of the trees in the forest. We will select one tree, and save the whole tree as an image. The following code takes one tree from the forest and saves it as an image. # Import tools needed for visualizationfrom sklearn.tree import export_graphvizimport pydot# Pull out one tree from the foresttree = rf.estimators_[5]# Import tools needed for visualizationfrom sklearn.tree import export_graphvizimport pydot# Pull out one tree from the foresttree = rf.estimators_[5]# Export the image to a dot fileexport_graphviz(tree, out_file = 'tree.dot', feature_names = feature_list, rounded = True, precision = 1)# Use dot file to create a graph(graph, ) = pydot.graph_from_dot_file('tree.dot')# Write graph to a png filegraph.write_png('tree.png') Let’s take a look: Wow! That looks like quite an expansive tree with 15 layers (in reality this is quite a small tree compared to some I’ve seen). You can download this image yourself and examine it in greater detail, but to make things easier, I will limit the depth of trees in the forest to produce an understandable image. # Limit depth of tree to 3 levelsrf_small = RandomForestRegressor(n_estimators=10, max_depth = 3)rf_small.fit(train_features, train_labels)# Extract the small treetree_small = rf_small.estimators_[5]# Save the tree as a png imageexport_graphviz(tree_small, out_file = 'small_tree.dot', feature_names = feature_list, rounded = True, precision = 1)(graph, ) = pydot.graph_from_dot_file('small_tree.dot')graph.write_png('small_tree.png'); Here is the reduced size tree annotated with labels Based solely on this tree, we can make a prediction for any new data point. Let’s take an example of making a prediction for Wednesday, December 27, 2017. The (actual) variables are: temp_2 = 39, temp_1 = 35, average = 44, and friend = 30. We start at the root node and the first answer is True because temp_1 ≤ 59.5. We move to the left and encounter the second question, which is also True as average ≤ 46.8. Move down to the left and on to the third and final question which is True as well because temp_1 ≤ 44.5. Therefore, we conclude that our estimate for the maximum temperature is 41.0 degrees as indicated by the value in the leaf node. An interesting observation is that in the root node, there are only 162 samples despite there being 261 training data points. This is because each tree in the forest is trained on a random subset of the data points with replacement (called bagging, short for bootstrap aggregating). (We can turn off the sampling with replacement and use all the data points by setting bootstrap = False when making the forest). Random sampling of data points, combined with random sampling of a subset of the features at each node of the tree, is why the model is called a ‘random’ forest. Furthermore, notice that in our tree, there are only 2 variables we actually used to make a prediction! According to this particular decision tree, the rest of the features are not important for making a prediction. Month of the year, day of the month, and our friend’s prediction are utterly useless for predicting the maximum temperature tomorrow! The only important information according to our simple tree is the temperature 1 day prior and the historical average. Visualizing the tree has increased our domain knowledge of the problem, and we now know what data to look for if we are asked to make a prediction! In order to quantify the usefulness of all the variables in the entire random forest, we can look at the relative importances of the variables. The importances returned in Skicit-learn represent how much including a particular variable improves the prediction. The actual calculation of the importance is beyond the scope of this post, but we can use the numbers to make relative comparisons between variables. The code here takes advantage of a number of tricks in the Python language, namely list comprehensive, zip, sorting, and argument unpacking. It’s not that important to understand these at the moment, but if you want to become skilled at Python, these are tools you should have in your arsenal! # Get numerical feature importancesimportances = list(rf.feature_importances_)# List of tuples with variable and importancefeature_importances = [(feature, round(importance, 2)) for feature, importance in zip(feature_list, importances)]# Sort the feature importances by most important firstfeature_importances = sorted(feature_importances, key = lambda x: x[1], reverse = True)# Print out the feature and importances [print('Variable: {:20} Importance: {}'.format(*pair)) for pair in feature_importances];Variable: temp_1 Importance: 0.7Variable: average Importance: 0.19Variable: day Importance: 0.03Variable: temp_2 Importance: 0.02Variable: friend Importance: 0.02Variable: month Importance: 0.01Variable: year Importance: 0.0Variable: week_Fri Importance: 0.0Variable: week_Mon Importance: 0.0Variable: week_Sat Importance: 0.0Variable: week_Sun Importance: 0.0Variable: week_Thurs Importance: 0.0Variable: week_Tues Importance: 0.0Variable: week_Wed Importance: 0.0 At the top of the list is temp_1, the max temperature of the day before. This tells us the best predictor of the max temperature for a day is the max temperature of the day before, a rather intuitive finding. The second most important factor is the historical average max temperature, also not that surprising. Your friend turns out to not be very helpful, along with the day of the week, the year, the month, and the temperature 2 days prior. These importances all make sense as we would not expect the day of the week to be a predictor of maximum temperature as it has nothing to do with weather. Moreover, the year is the same for all data points and hence provides us with no information for predicting the max temperature. In future implementations of the model, we can remove those variables that have no importance and the performance will not suffer. Additionally, if we are using a different model, say a support vector machine, we could use the random forest feature importances as a kind of feature selection method. Let’s quickly make a random forest with only the two most important variables, the max temperature 1 day prior and the historical average and see how the performance compares. # New random forest with only the two most important variablesrf_most_important = RandomForestRegressor(n_estimators= 1000, random_state=42)# Extract the two most important featuresimportant_indices = [feature_list.index('temp_1'), feature_list.index('average')]train_important = train_features[:, important_indices]test_important = test_features[:, important_indices]# Train the random forestrf_most_important.fit(train_important, train_labels)# Make predictions and determine the errorpredictions = rf_most_important.predict(test_important)errors = abs(predictions - test_labels)# Display the performance metricsprint('Mean Absolute Error:', round(np.mean(errors), 2), 'degrees.')mape = np.mean(100 * (errors / test_labels))accuracy = 100 - mapeprint('Accuracy:', round(accuracy, 2), '%.')Mean Absolute Error: 3.9 degrees.Accuracy: 93.8 %. This tells us that we actually do not need all the data we collected to make accurate predictions! If we were to continue using this model, we could only collect the two variables and achieve nearly the same performance. In a production setting, we would need to weigh the decrease in accuracy versus the extra time required to obtain more information. Knowing how to find the right balance between performance and cost is an essential skill for a machine learning engineer and will ultimately depend on the problem! At this point we have covered pretty much everything there is to know for a basic implementation of the random forest for a supervised regression problem. We can feel confident that our model can predict the maximum temperature tomorrow with 94% accuracy from one year of historical data. From here, feel free to play around with this example, or use the model on a data set of your choice. I will wrap up this post by making a few visualizations. My two favorite parts of data science are graphing and modeling, so naturally I have to make some charts! In addition to being enjoyable to look at, charts can help us diagnose our model because they compress a lot of numbers into an image that we can quickly examine. The first chart I’ll make is a simple bar plot of the feature importances to illustrate the disparities in the relative significance of the variables. Plotting in Python is kind of non-intuitive, and I end up looking up almost everything on Stack Overflow when I make graphs. Don’t worry if the code here doesn’t quite make sense, sometimes fully understanding the code isn’t necessary to get the end result you want! # Import matplotlib for plotting and use magic command for Jupyter Notebooksimport matplotlib.pyplot as plt%matplotlib inline# Set the styleplt.style.use('fivethirtyeight')# list of x locations for plottingx_values = list(range(len(importances)))# Make a bar chartplt.bar(x_values, importances, orientation = 'vertical')# Tick labels for x axisplt.xticks(x_values, feature_list, rotation='vertical')# Axis labels and titleplt.ylabel('Importance'); plt.xlabel('Variable'); plt.title('Variable Importances'); Next, we can plot the entire dataset with predictions highlighted. This requires a little data manipulation, but its not too difficult. We can use this plot to determine if there are any outliers in either the data or our predictions. # Use datetime for creating date objects for plottingimport datetime# Dates of training valuesmonths = features[:, feature_list.index('month')]days = features[:, feature_list.index('day')]years = features[:, feature_list.index('year')]# List and then convert to datetime objectdates = [str(int(year)) + '-' + str(int(month)) + '-' + str(int(day)) for year, month, day in zip(years, months, days)]dates = [datetime.datetime.strptime(date, '%Y-%m-%d') for date in dates]# Dataframe with true values and datestrue_data = pd.DataFrame(data = {'date': dates, 'actual': labels})# Dates of predictionsmonths = test_features[:, feature_list.index('month')]days = test_features[:, feature_list.index('day')]years = test_features[:, feature_list.index('year')]# Column of datestest_dates = [str(int(year)) + '-' + str(int(month)) + '-' + str(int(day)) for year, month, day in zip(years, months, days)]# Convert to datetime objectstest_dates = [datetime.datetime.strptime(date, '%Y-%m-%d') for date in test_dates]# Dataframe with predictions and datespredictions_data = pd.DataFrame(data = {'date': test_dates, 'prediction': predictions})# Plot the actual valuesplt.plot(true_data['date'], true_data['actual'], 'b-', label = 'actual')# Plot the predicted valuesplt.plot(predictions_data['date'], predictions_data['prediction'], 'ro', label = 'prediction')plt.xticks(rotation = '60'); plt.legend()# Graph labelsplt.xlabel('Date'); plt.ylabel('Maximum Temperature (F)'); plt.title('Actual and Predicted Values'); A little bit of work for a nice looking graph! It doesn’t look as if we have any noticeable outliers that need to be corrected. To further diagnose the model, we can plot residuals (the errors) to see if our model has a tendency to over-predict or under-predict, and we can also see if the residuals are normally distributed. However, I will just make one final chart showing the actual values, the temperature one day previous, the historical average, and our friend’s prediction. This will allow us to see the difference between useful variables and those that aren’t so helpful. # Make the data accessible for plottingtrue_data['temp_1'] = features[:, feature_list.index('temp_1')]true_data['average'] = features[:, feature_list.index('average')]true_data['friend'] = features[:, feature_list.index('friend')]# Plot all the data as linesplt.plot(true_data['date'], true_data['actual'], 'b-', label = 'actual', alpha = 1.0)plt.plot(true_data['date'], true_data['temp_1'], 'y-', label = 'temp_1', alpha = 1.0)plt.plot(true_data['date'], true_data['average'], 'k-', label = 'average', alpha = 0.8)plt.plot(true_data['date'], true_data['friend'], 'r-', label = 'friend', alpha = 0.3)# Formatting plotplt.legend(); plt.xticks(rotation = '60');# Lables and titleplt.xlabel('Date'); plt.ylabel('Maximum Temperature (F)'); plt.title('Actual Max Temp and Variables'); It is a little hard to make out all the lines, but we can see why the max temperature one day prior and the historical max temperature are useful for predicting max temperature while our friend is not (don’t give up on the friend yet, but maybe also don’t place so much weight on their estimate!). Graphs such as this are often helpful to make ahead of time so we can choose the variables to include, but they also can be used for diagnosis. Much as in the case of Anscombe’s quartet, graphs are often more revealing than quantitative numbers and should be a part of any machine learning workflow. With those graphs, we have completed an entire end-to-end machine learning example! At this point, if we want to improve our model, we could try different hyperparameters (settings) try a different algorithm, or the best approach of all, gather more data! The performance of any model is directly proportional to the amount of valid data it can learn from, and we were using a very limited amount of information for training. I would encourage anyone to try and improve this model and share the results. From here you can dig more into the random forest theory and application using numerous online (free) resources. For those looking for a single book to cover both theory and Python implementations of machine learning models, I highly recommend Hands-On Machine Learning with Scikit-Learn and Tensorflow. Moreover, I hope everyone who made it through has seen how accessible machine learning has become and is ready to join the welcoming and helpful machine learning community. As always, I welcome feedback and constructive criticism! My email is [email protected].
[ { "code": null, "e": 220, "s": 172, "text": "A Practical End-to-End Machine Learning Example" }, { "code": null, "e": 1236, "s": 220, "text": "There has never been a better time to get into machine learning. With the learning resources available online, free open-source tools with implementations of any algorithm imaginable, and the cheap availability of computing power through cloud services such as AWS, machine learning is truly a field that has been democratized by the internet. Anyone with access to a laptop and a willingness to learn can try out state-of-the-art algorithms in minutes. With a little more time, you can develop practical models to help in your daily life or at work (or even switch into the machine learning field and reap the economic benefits). This post will walk you through an end-to-end implementation of the powerful random forest machine learning model. It is meant to serve as a complement to my conceptual explanation of the random forest, but can be read entirely on its own as long as you have the basic idea of a decision tree and a random forest. A follow-up post details how we can improve upon the model built here." }, { "code": null, "e": 1910, "s": 1236, "text": "There will of course be Python code here, however, it is not meant to intimate anyone, but rather to show how accessible machine learning is with the resources available today! The complete project with data is available on GitHub, and the data file and Jupyter Notebook can also be downloaded from Google Drive. All you need is a laptop with Python installed and the ability to start a Jupyter Notebook and you can follow along. (For installing Python and running a Jupyter notebook check out this guide). There will be a few necessary machine learning topics touched on here, but I will try to make them clear and provide resources for learning more for those interested." }, { "code": null, "e": 3006, "s": 1910, "text": "The problem we will tackle is predicting the max temperature for tomorrow in our city using one year of past weather data. I am using Seattle, WA but feel free to find data for your own city using the NOAA Climate Data Online tool. We are going to act as if we don’t have access to any weather forecasts (and besides, it’s more fun to make our own predictions rather than rely on others). What we do have access to is one year of historical max temperatures, the temperatures for the previous two days, and an estimate from a friend who is always claiming to know everything about the weather. This is a supervised, regression machine learning problem. It’s supervised because we have both the features (data for the city) and the targets (temperature) that we want to predict. During training, we give the random forest both the features and targets and it must learn how to map the data to a prediction. Moreover, this is a regression task because the target value is continuous (as opposed to discrete classes in classification). That’s pretty much all the background we need, so let’s start!" }, { "code": null, "e": 3209, "s": 3006, "text": "Before we jump right into programming, we should lay out a brief guide to keep us on track. The following steps form the basis for any machine learning workflow once we have a problem and model in mind:" }, { "code": null, "e": 3775, "s": 3209, "text": "State the question and determine required dataAcquire the data in an accessible formatIdentify and correct missing data points/anomalies as requiredPrepare the data for the machine learning modelEstablish a baseline model that you aim to exceedTrain the model on the training dataMake predictions on the test dataCompare predictions to the known test set targets and calculate performance metricsIf performance is not satisfactory, adjust the model, acquire more data, or try a different modeling techniqueInterpret model and report results visually and numerically" }, { "code": null, "e": 3822, "s": 3775, "text": "State the question and determine required data" }, { "code": null, "e": 3863, "s": 3822, "text": "Acquire the data in an accessible format" }, { "code": null, "e": 3926, "s": 3863, "text": "Identify and correct missing data points/anomalies as required" }, { "code": null, "e": 3974, "s": 3926, "text": "Prepare the data for the machine learning model" }, { "code": null, "e": 4024, "s": 3974, "text": "Establish a baseline model that you aim to exceed" }, { "code": null, "e": 4061, "s": 4024, "text": "Train the model on the training data" }, { "code": null, "e": 4095, "s": 4061, "text": "Make predictions on the test data" }, { "code": null, "e": 4179, "s": 4095, "text": "Compare predictions to the known test set targets and calculate performance metrics" }, { "code": null, "e": 4290, "s": 4179, "text": "If performance is not satisfactory, adjust the model, acquire more data, or try a different modeling technique" }, { "code": null, "e": 4350, "s": 4290, "text": "Interpret model and report results visually and numerically" }, { "code": null, "e": 4555, "s": 4350, "text": "Step 1 is already checked off! We have our question: “can we predict the max temperature tomorrow for our city?” and we know we have access to historical max temperatures for the past year in Seattle, WA." }, { "code": null, "e": 5099, "s": 4555, "text": "First, we need some data. To use a realistic example, I retrieved weather data for Seattle, WA from 2016 using the NOAA Climate Data Online tool. Generally, about 80% of the time spent in data analysis is cleaning and retrieving data, but this workload can be reduced by finding high-quality data sources. The NOAA tool is surprisingly easy to use and temperature data can be downloaded as clean csv files which can be parsed in languages such as Python or R. The complete data file is available for download for those wanting to follow along." }, { "code": null, "e": 5187, "s": 5099, "text": "The following Python code loads in the csv data and displays the structure of the data:" }, { "code": null, "e": 5335, "s": 5187, "text": "# Pandas is used for data manipulationimport pandas as pd# Read in data and display first 5 rowsfeatures = pd.read_csv('temps.csv')features.head(5)" }, { "code": null, "e": 5458, "s": 5335, "text": "The information is in the tidy data format with each row forming one observation, with the variable values in the columns." }, { "code": null, "e": 5501, "s": 5458, "text": "Following are explanations of the columns:" }, { "code": null, "e": 5532, "s": 5501, "text": "year: 2016 for all data points" }, { "code": null, "e": 5568, "s": 5532, "text": "month: number for month of the year" }, { "code": null, "e": 5600, "s": 5568, "text": "day: number for day of the year" }, { "code": null, "e": 5644, "s": 5600, "text": "week: day of the week as a character string" }, { "code": null, "e": 5681, "s": 5644, "text": "temp_2: max temperature 2 days prior" }, { "code": null, "e": 5717, "s": 5681, "text": "temp_1: max temperature 1 day prior" }, { "code": null, "e": 5761, "s": 5717, "text": "average: historical average max temperature" }, { "code": null, "e": 5797, "s": 5761, "text": "actual: max temperature measurement" }, { "code": null, "e": 5901, "s": 5797, "text": "friend: your friend’s prediction, a random number between 20 below the average and 20 above the average" }, { "code": null, "e": 6499, "s": 5901, "text": "If we look at the dimensions of the data, we notice only there are only 348 rows, which doesn’t quite agree with the 366 days we know there were in 2016. Looking through the data from the NOAA, I noticed several missing days, which is a great reminder that data collected in the real-world will never be perfect. Missing data can impact an analysis as can incorrect data or outliers. In this case, the missing data will not have a large effect, and the data quality is good because of the source. We also can see there are nine columns which represent eight features and the one target (‘actual’)." }, { "code": null, "e": 6592, "s": 6499, "text": "print('The shape of our features is:', features.shape)The shape of our features is: (348, 9)" }, { "code": null, "e": 6658, "s": 6592, "text": "To identify anomalies, we can quickly compute summary statistics." }, { "code": null, "e": 6718, "s": 6658, "text": "# Descriptive statistics for each columnfeatures.describe()" }, { "code": null, "e": 7222, "s": 6718, "text": "There are not any data points that immediately appear as anomalous and no zeros in any of the measurement columns. Another method to verify the quality of the data is make basic plots. Often it is easier to spot anomalies in a graph than in numbers. I have left out the actual code here, because plotting is Python is non-intuitive but feel free to refer to the notebook for the complete implementation (like any good data scientist, I pretty much copy and pasted the plotting code from Stack Overflow)." }, { "code": null, "e": 7446, "s": 7222, "text": "Examining the quantitative statistics and the graphs, we can feel confident in the high quality of our data. There are no clear outliers, and although there are a few missing points, they will not detract from the analysis." }, { "code": null, "e": 7873, "s": 7446, "text": "Unfortunately, we aren’t quite at the point where you can just feed raw data into a model and have it return an answer (although people are working on this)! We will need to do some minor modification to put our data into machine-understandable terms. We will use the Python library Pandas for our data manipulation relying, on the structure known as a dataframe, which is basically an excel spreadsheet with rows and columns." }, { "code": null, "e": 8062, "s": 7873, "text": "The exact steps for preparation of the data will depend on the model used and the data gathered, but some amount of data manipulation will be required for any machine learning application." }, { "code": null, "e": 8079, "s": 8062, "text": "One-Hot Encoding" }, { "code": null, "e": 8914, "s": 8079, "text": "The first step for us is known as one-hot encoding of the data. This process takes categorical variables, such as days of the week and converts it to a numerical representation without an arbitrary ordering. Days of the week are intuitive to us because we use them all the time. You will (hopefully) never find anyone who doesn’t know that ‘Mon’ refers to the first day of the workweek, but machines do not have any intuitive knowledge. What computers know is numbers and for machine learning we must accommodate them. We could simply map days of the week to numbers 1–7, but this might lead to the algorithm placing more importance on Sunday because it has a higher numerical value. Instead, we change the single column of weekdays into seven columns of binary data. This is best illustrated pictorially. One hot encoding takes this:" }, { "code": null, "e": 8932, "s": 8914, "text": "and turns it into" }, { "code": null, "e": 9092, "s": 8932, "text": "So, if a data point is a Wednesday, it will have a 1 in the Wednesday column and a 0 in all other columns. This process can be done in pandas in a single line!" }, { "code": null, "e": 9254, "s": 9092, "text": "# One-hot encode the data using pandas get_dummiesfeatures = pd.get_dummies(features)# Display the first 5 rows of the last 12 columnsfeatures.iloc[:,5:].head(5)" }, { "code": null, "e": 9295, "s": 9254, "text": "Snapshot of data after one-hot encoding:" }, { "code": null, "e": 9401, "s": 9295, "text": "The shape of our data is now 349 x 15 and all of the column are numbers, just how the algorithm likes it!" }, { "code": null, "e": 9449, "s": 9401, "text": "Features and Targets and Convert Data to Arrays" }, { "code": null, "e": 9910, "s": 9449, "text": "Now, we need to separate the data into the features and targets. The target, also known as the label, is the value we want to predict, in this case the actual max temperature and the features are all the columns the model uses to make a prediction. We will also convert the Pandas dataframes to Numpy arrays because that is the way the algorithm works. (I save the column headers, which are the names of the features, to a list to use for later visualization)." }, { "code": null, "e": 10276, "s": 9910, "text": "# Use numpy to convert to arraysimport numpy as np# Labels are the values we want to predictlabels = np.array(features['actual'])# Remove the labels from the features# axis 1 refers to the columnsfeatures= features.drop('actual', axis = 1)# Saving feature names for later usefeature_list = list(features.columns)# Convert to numpy arrayfeatures = np.array(features)" }, { "code": null, "e": 10302, "s": 10276, "text": "Training and Testing Sets" }, { "code": null, "e": 11472, "s": 10302, "text": "There is one final step of data preparation: splitting data into training and testing sets. During training, we let the model ‘see’ the answers, in this case the actual temperature, so it can learn how to predict the temperature from the features. We expect there to be some relationship between all the features and the target value, and the model’s job is to learn this relationship during training. Then, when it comes time to evaluate the model, we ask it to make predictions on a testing set where it only has access to the features (not the answers)! Because we do have the actual answers for the test set, we can compare these predictions to the true value to judge how accurate the model is. Generally, when training a model, we randomly split the data into training and testing sets to get a representation of all data points (if we trained on the first nine months of the year and then used the final three months for prediction, our algorithm would not perform well because it has not seen any data from those last three months.) I am setting the random state to 42 which means the results will be the same each time I run the split for reproducible results." }, { "code": null, "e": 11538, "s": 11472, "text": "The following code splits the data sets with another single line:" }, { "code": null, "e": 11833, "s": 11538, "text": "# Using Skicit-learn to split data into training and testing setsfrom sklearn.model_selection import train_test_split# Split the data into training and testing setstrain_features, test_features, train_labels, test_labels = train_test_split(features, labels, test_size = 0.25, random_state = 42)" }, { "code": null, "e": 12111, "s": 11833, "text": "We can look at the shape of all the data to make sure we did everything correctly. We expect the training features number of columns to match the testing feature number of columns and the number of rows to match for the respective training and testing features and the labels :" }, { "code": null, "e": 12442, "s": 12111, "text": "print('Training Features Shape:', train_features.shape)print('Training Labels Shape:', train_labels.shape)print('Testing Features Shape:', test_features.shape)print('Testing Labels Shape:', test_labels.shape)Training Features Shape: (261, 14)Training Labels Shape: (261,)Testing Features Shape: (87, 14)Testing Labels Shape: (87,)" }, { "code": null, "e": 12560, "s": 12442, "text": "It looks as if everything is in order! Just to recap, to get the data into a form acceptable for machine learning we:" }, { "code": null, "e": 12693, "s": 12560, "text": "One-hot encoded categorical variablesSplit data into features and labelsConverted to arraysSplit data into training and testing sets" }, { "code": null, "e": 12731, "s": 12693, "text": "One-hot encoded categorical variables" }, { "code": null, "e": 12767, "s": 12731, "text": "Split data into features and labels" }, { "code": null, "e": 12787, "s": 12767, "text": "Converted to arrays" }, { "code": null, "e": 12829, "s": 12787, "text": "Split data into training and testing sets" }, { "code": null, "e": 13276, "s": 12829, "text": "Depending on the initial data set, there may be extra work involved such as removing outliers, imputing missing values, or converting temporal variables into cyclical representations. These steps may seem arbitrary at first, but once you get the basic workflow, it will be generally the same for any machine learning problem. It’s all about taking human-readable data and putting it into a form that can be understood by a machine learning model." }, { "code": null, "e": 13785, "s": 13276, "text": "Before we can make and evaluate predictions, we need to establish a baseline, a sensible measure that we hope to beat with our model. If our model cannot improve upon the baseline, then it will be a failure and we should try a different model or admit that machine learning is not right for our problem. The baseline prediction for our case can be the historical max temperature averages. In other words, our baseline is the error we would get if we simply predicted the average max temperature for all days." }, { "code": null, "e": 14115, "s": 13785, "text": "# The baseline predictions are the historical averagesbaseline_preds = test_features[:, feature_list.index('average')]# Baseline errors, and display average baseline errorbaseline_errors = abs(baseline_preds - test_labels)print('Average baseline error: ', round(np.mean(baseline_errors), 2))Average baseline error: 5.06 degrees." }, { "code": null, "e": 14223, "s": 14115, "text": "We now have our goal! If we can’t beat an average error of 5 degrees, then we need to rethink our approach." }, { "code": null, "e": 14606, "s": 14223, "text": "After all the work of data preparation, creating and training the model is pretty simple using Scikit-learn. We import the random forest regression model from skicit-learn, instantiate the model, and fit (scikit-learn’s name for training) the model on the training data. (Again setting the random state for reproducible results). This entire process is only 3 lines in scikit-learn!" }, { "code": null, "e": 14869, "s": 14606, "text": "# Import the model we are usingfrom sklearn.ensemble import RandomForestRegressor# Instantiate model with 1000 decision treesrf = RandomForestRegressor(n_estimators = 1000, random_state = 42)# Train the model on training datarf.fit(train_features, train_labels);" }, { "code": null, "e": 15483, "s": 14869, "text": "Our model has now been trained to learn the relationships between the features and the targets. The next step is figuring out how good the model is! To do this we make predictions on the test features (the model is never allowed to see the test answers). We then compare the predictions to the known answers. When performing regression, we need to make sure to use the absolute error because we expect some of our answers to be low and some to be high. We are interested in how far away our average prediction is from the actual value so we take the absolute value (as we also did when establishing the baseline)." }, { "code": null, "e": 15560, "s": 15483, "text": "Making predictions with out model is another 1-line command in Skicit-learn." }, { "code": null, "e": 15863, "s": 15560, "text": "# Use the forest's predict method on the test datapredictions = rf.predict(test_features)# Calculate the absolute errorserrors = abs(predictions - test_labels)# Print out the mean absolute error (mae)print('Mean Absolute Error:', round(np.mean(errors), 2), 'degrees.')Mean Absolute Error: 3.83 degrees." }, { "code": null, "e": 16158, "s": 15863, "text": "Our average estimate is off by 3.83 degrees. That is more than a 1 degree average improvement over the baseline. Although this might not seem significant, it is nearly 25% better than the baseline, which, depending on the field and the problem, could represent millions of dollars to a company." }, { "code": null, "e": 16289, "s": 16158, "text": "To put our predictions in perspective, we can calculate an accuracy using the mean average percentage error subtracted from 100 %." }, { "code": null, "e": 16498, "s": 16289, "text": "# Calculate mean absolute percentage error (MAPE)mape = 100 * (errors / test_labels)# Calculate and display accuracyaccuracy = 100 - np.mean(mape)print('Accuracy:', round(accuracy, 2), '%.')Accuracy: 93.99 %." }, { "code": null, "e": 16630, "s": 16498, "text": "That looks pretty good! Our model has learned how to predict the maximum temperature for the next day in Seattle with 94% accuracy." }, { "code": null, "e": 17525, "s": 16630, "text": "In the usual machine learning workflow, this would be when start hyperparameter tuning. This is a complicated phrase that means “adjust the settings to improve performance” (The settings are known as hyperparameters to distinguish them from model parameters learned during training). The most common way to do this is simply make a bunch of models with different settings, evaluate them all on the same validation set, and see which one does best. Of course, this would be a tedious process to do by hand, and there are automated methods to do this process in Skicit-learn. Hyperparameter tuning is often more engineering than theory-based, and I would encourage anyone interested to check out the documentation and start playing around! An accuracy of 94% is satisfactory for this problem, but keep in mind that the first model built will almost never be the model that makes it to production." }, { "code": null, "e": 17993, "s": 17525, "text": "At this point, we know our model is good, but it’s pretty much a black box. We feed in some Numpy arrays for training, ask it to make a prediction, evaluate the predictions, and see that they are reasonable. The question is: how does this model arrive at the values? There are two approaches to get under the hood of the random forest: first, we can look at a single tree in the forest, and second, we can look at the feature importances of our explanatory variables." }, { "code": null, "e": 18191, "s": 17993, "text": "One of the coolest parts of the Random Forest implementation in Skicit-learn is we can actually examine any of the trees in the forest. We will select one tree, and save the whole tree as an image." }, { "code": null, "e": 18267, "s": 18191, "text": "The following code takes one tree from the forest and saves it as an image." }, { "code": null, "e": 18840, "s": 18267, "text": "# Import tools needed for visualizationfrom sklearn.tree import export_graphvizimport pydot# Pull out one tree from the foresttree = rf.estimators_[5]# Import tools needed for visualizationfrom sklearn.tree import export_graphvizimport pydot# Pull out one tree from the foresttree = rf.estimators_[5]# Export the image to a dot fileexport_graphviz(tree, out_file = 'tree.dot', feature_names = feature_list, rounded = True, precision = 1)# Use dot file to create a graph(graph, ) = pydot.graph_from_dot_file('tree.dot')# Write graph to a png filegraph.write_png('tree.png')" }, { "code": null, "e": 18859, "s": 18840, "text": "Let’s take a look:" }, { "code": null, "e": 19167, "s": 18859, "text": "Wow! That looks like quite an expansive tree with 15 layers (in reality this is quite a small tree compared to some I’ve seen). You can download this image yourself and examine it in greater detail, but to make things easier, I will limit the depth of trees in the forest to produce an understandable image." }, { "code": null, "e": 19603, "s": 19167, "text": "# Limit depth of tree to 3 levelsrf_small = RandomForestRegressor(n_estimators=10, max_depth = 3)rf_small.fit(train_features, train_labels)# Extract the small treetree_small = rf_small.estimators_[5]# Save the tree as a png imageexport_graphviz(tree_small, out_file = 'small_tree.dot', feature_names = feature_list, rounded = True, precision = 1)(graph, ) = pydot.graph_from_dot_file('small_tree.dot')graph.write_png('small_tree.png');" }, { "code": null, "e": 19655, "s": 19603, "text": "Here is the reduced size tree annotated with labels" }, { "code": null, "e": 20875, "s": 19655, "text": "Based solely on this tree, we can make a prediction for any new data point. Let’s take an example of making a prediction for Wednesday, December 27, 2017. The (actual) variables are: temp_2 = 39, temp_1 = 35, average = 44, and friend = 30. We start at the root node and the first answer is True because temp_1 ≤ 59.5. We move to the left and encounter the second question, which is also True as average ≤ 46.8. Move down to the left and on to the third and final question which is True as well because temp_1 ≤ 44.5. Therefore, we conclude that our estimate for the maximum temperature is 41.0 degrees as indicated by the value in the leaf node. An interesting observation is that in the root node, there are only 162 samples despite there being 261 training data points. This is because each tree in the forest is trained on a random subset of the data points with replacement (called bagging, short for bootstrap aggregating). (We can turn off the sampling with replacement and use all the data points by setting bootstrap = False when making the forest). Random sampling of data points, combined with random sampling of a subset of the features at each node of the tree, is why the model is called a ‘random’ forest." }, { "code": null, "e": 21492, "s": 20875, "text": "Furthermore, notice that in our tree, there are only 2 variables we actually used to make a prediction! According to this particular decision tree, the rest of the features are not important for making a prediction. Month of the year, day of the month, and our friend’s prediction are utterly useless for predicting the maximum temperature tomorrow! The only important information according to our simple tree is the temperature 1 day prior and the historical average. Visualizing the tree has increased our domain knowledge of the problem, and we now know what data to look for if we are asked to make a prediction!" }, { "code": null, "e": 21903, "s": 21492, "text": "In order to quantify the usefulness of all the variables in the entire random forest, we can look at the relative importances of the variables. The importances returned in Skicit-learn represent how much including a particular variable improves the prediction. The actual calculation of the importance is beyond the scope of this post, but we can use the numbers to make relative comparisons between variables." }, { "code": null, "e": 22197, "s": 21903, "text": "The code here takes advantage of a number of tricks in the Python language, namely list comprehensive, zip, sorting, and argument unpacking. It’s not that important to understand these at the moment, but if you want to become skilled at Python, these are tools you should have in your arsenal!" }, { "code": null, "e": 23352, "s": 22197, "text": "# Get numerical feature importancesimportances = list(rf.feature_importances_)# List of tuples with variable and importancefeature_importances = [(feature, round(importance, 2)) for feature, importance in zip(feature_list, importances)]# Sort the feature importances by most important firstfeature_importances = sorted(feature_importances, key = lambda x: x[1], reverse = True)# Print out the feature and importances [print('Variable: {:20} Importance: {}'.format(*pair)) for pair in feature_importances];Variable: temp_1 Importance: 0.7Variable: average Importance: 0.19Variable: day Importance: 0.03Variable: temp_2 Importance: 0.02Variable: friend Importance: 0.02Variable: month Importance: 0.01Variable: year Importance: 0.0Variable: week_Fri Importance: 0.0Variable: week_Mon Importance: 0.0Variable: week_Sat Importance: 0.0Variable: week_Sun Importance: 0.0Variable: week_Thurs Importance: 0.0Variable: week_Tues Importance: 0.0Variable: week_Wed Importance: 0.0" }, { "code": null, "e": 24080, "s": 23352, "text": "At the top of the list is temp_1, the max temperature of the day before. This tells us the best predictor of the max temperature for a day is the max temperature of the day before, a rather intuitive finding. The second most important factor is the historical average max temperature, also not that surprising. Your friend turns out to not be very helpful, along with the day of the week, the year, the month, and the temperature 2 days prior. These importances all make sense as we would not expect the day of the week to be a predictor of maximum temperature as it has nothing to do with weather. Moreover, the year is the same for all data points and hence provides us with no information for predicting the max temperature." }, { "code": null, "e": 24556, "s": 24080, "text": "In future implementations of the model, we can remove those variables that have no importance and the performance will not suffer. Additionally, if we are using a different model, say a support vector machine, we could use the random forest feature importances as a kind of feature selection method. Let’s quickly make a random forest with only the two most important variables, the max temperature 1 day prior and the historical average and see how the performance compares." }, { "code": null, "e": 25398, "s": 24556, "text": "# New random forest with only the two most important variablesrf_most_important = RandomForestRegressor(n_estimators= 1000, random_state=42)# Extract the two most important featuresimportant_indices = [feature_list.index('temp_1'), feature_list.index('average')]train_important = train_features[:, important_indices]test_important = test_features[:, important_indices]# Train the random forestrf_most_important.fit(train_important, train_labels)# Make predictions and determine the errorpredictions = rf_most_important.predict(test_important)errors = abs(predictions - test_labels)# Display the performance metricsprint('Mean Absolute Error:', round(np.mean(errors), 2), 'degrees.')mape = np.mean(100 * (errors / test_labels))accuracy = 100 - mapeprint('Accuracy:', round(accuracy, 2), '%.')Mean Absolute Error: 3.9 degrees.Accuracy: 93.8 %." }, { "code": null, "e": 25915, "s": 25398, "text": "This tells us that we actually do not need all the data we collected to make accurate predictions! If we were to continue using this model, we could only collect the two variables and achieve nearly the same performance. In a production setting, we would need to weigh the decrease in accuracy versus the extra time required to obtain more information. Knowing how to find the right balance between performance and cost is an essential skill for a machine learning engineer and will ultimately depend on the problem!" }, { "code": null, "e": 26632, "s": 25915, "text": "At this point we have covered pretty much everything there is to know for a basic implementation of the random forest for a supervised regression problem. We can feel confident that our model can predict the maximum temperature tomorrow with 94% accuracy from one year of historical data. From here, feel free to play around with this example, or use the model on a data set of your choice. I will wrap up this post by making a few visualizations. My two favorite parts of data science are graphing and modeling, so naturally I have to make some charts! In addition to being enjoyable to look at, charts can help us diagnose our model because they compress a lot of numbers into an image that we can quickly examine." }, { "code": null, "e": 27050, "s": 26632, "text": "The first chart I’ll make is a simple bar plot of the feature importances to illustrate the disparities in the relative significance of the variables. Plotting in Python is kind of non-intuitive, and I end up looking up almost everything on Stack Overflow when I make graphs. Don’t worry if the code here doesn’t quite make sense, sometimes fully understanding the code isn’t necessary to get the end result you want!" }, { "code": null, "e": 27557, "s": 27050, "text": "# Import matplotlib for plotting and use magic command for Jupyter Notebooksimport matplotlib.pyplot as plt%matplotlib inline# Set the styleplt.style.use('fivethirtyeight')# list of x locations for plottingx_values = list(range(len(importances)))# Make a bar chartplt.bar(x_values, importances, orientation = 'vertical')# Tick labels for x axisplt.xticks(x_values, feature_list, rotation='vertical')# Axis labels and titleplt.ylabel('Importance'); plt.xlabel('Variable'); plt.title('Variable Importances');" }, { "code": null, "e": 27792, "s": 27557, "text": "Next, we can plot the entire dataset with predictions highlighted. This requires a little data manipulation, but its not too difficult. We can use this plot to determine if there are any outliers in either the data or our predictions." }, { "code": null, "e": 29292, "s": 27792, "text": "# Use datetime for creating date objects for plottingimport datetime# Dates of training valuesmonths = features[:, feature_list.index('month')]days = features[:, feature_list.index('day')]years = features[:, feature_list.index('year')]# List and then convert to datetime objectdates = [str(int(year)) + '-' + str(int(month)) + '-' + str(int(day)) for year, month, day in zip(years, months, days)]dates = [datetime.datetime.strptime(date, '%Y-%m-%d') for date in dates]# Dataframe with true values and datestrue_data = pd.DataFrame(data = {'date': dates, 'actual': labels})# Dates of predictionsmonths = test_features[:, feature_list.index('month')]days = test_features[:, feature_list.index('day')]years = test_features[:, feature_list.index('year')]# Column of datestest_dates = [str(int(year)) + '-' + str(int(month)) + '-' + str(int(day)) for year, month, day in zip(years, months, days)]# Convert to datetime objectstest_dates = [datetime.datetime.strptime(date, '%Y-%m-%d') for date in test_dates]# Dataframe with predictions and datespredictions_data = pd.DataFrame(data = {'date': test_dates, 'prediction': predictions})# Plot the actual valuesplt.plot(true_data['date'], true_data['actual'], 'b-', label = 'actual')# Plot the predicted valuesplt.plot(predictions_data['date'], predictions_data['prediction'], 'ro', label = 'prediction')plt.xticks(rotation = '60'); plt.legend()# Graph labelsplt.xlabel('Date'); plt.ylabel('Maximum Temperature (F)'); plt.title('Actual and Predicted Values');" }, { "code": null, "e": 29874, "s": 29292, "text": "A little bit of work for a nice looking graph! It doesn’t look as if we have any noticeable outliers that need to be corrected. To further diagnose the model, we can plot residuals (the errors) to see if our model has a tendency to over-predict or under-predict, and we can also see if the residuals are normally distributed. However, I will just make one final chart showing the actual values, the temperature one day previous, the historical average, and our friend’s prediction. This will allow us to see the difference between useful variables and those that aren’t so helpful." }, { "code": null, "e": 30656, "s": 29874, "text": "# Make the data accessible for plottingtrue_data['temp_1'] = features[:, feature_list.index('temp_1')]true_data['average'] = features[:, feature_list.index('average')]true_data['friend'] = features[:, feature_list.index('friend')]# Plot all the data as linesplt.plot(true_data['date'], true_data['actual'], 'b-', label = 'actual', alpha = 1.0)plt.plot(true_data['date'], true_data['temp_1'], 'y-', label = 'temp_1', alpha = 1.0)plt.plot(true_data['date'], true_data['average'], 'k-', label = 'average', alpha = 0.8)plt.plot(true_data['date'], true_data['friend'], 'r-', label = 'friend', alpha = 0.3)# Formatting plotplt.legend(); plt.xticks(rotation = '60');# Lables and titleplt.xlabel('Date'); plt.ylabel('Maximum Temperature (F)'); plt.title('Actual Max Temp and Variables');" }, { "code": null, "e": 31254, "s": 30656, "text": "It is a little hard to make out all the lines, but we can see why the max temperature one day prior and the historical max temperature are useful for predicting max temperature while our friend is not (don’t give up on the friend yet, but maybe also don’t place so much weight on their estimate!). Graphs such as this are often helpful to make ahead of time so we can choose the variables to include, but they also can be used for diagnosis. Much as in the case of Anscombe’s quartet, graphs are often more revealing than quantitative numbers and should be a part of any machine learning workflow." }, { "code": null, "e": 32235, "s": 31254, "text": "With those graphs, we have completed an entire end-to-end machine learning example! At this point, if we want to improve our model, we could try different hyperparameters (settings) try a different algorithm, or the best approach of all, gather more data! The performance of any model is directly proportional to the amount of valid data it can learn from, and we were using a very limited amount of information for training. I would encourage anyone to try and improve this model and share the results. From here you can dig more into the random forest theory and application using numerous online (free) resources. For those looking for a single book to cover both theory and Python implementations of machine learning models, I highly recommend Hands-On Machine Learning with Scikit-Learn and Tensorflow. Moreover, I hope everyone who made it through has seen how accessible machine learning has become and is ready to join the welcoming and helpful machine learning community." } ]
Working with JSON Data in Java - GeeksforGeeks
10 Sep, 2020 JSON stands for JavaScript Object Notation which is a lightweight text-based open standard designed which is easy for human-readable data interchange. In general, JSON is extended from JavaScript. JSON is language independent and It is easy to read and write. The file extension of JSON is .json. Example – JSON format In the below given example, you will see how you can store values in JSON format. Consider student information where Stu_id, Stu_Name, Course is an entity you need to store then in JSON format you can store these values in key values pair form. Let’s have a look. { "Student": [ { "Stu_id" : "1001", "Stu_Name" : "Ashish", "Course" : "Java", }, { "Stu_id" : "1002", "Stu_Name" : "Rana", "Course" : "Advance Java", } ] } It is the method by which we can access means read or write JSON data in Java Programming Language. Here we simply use the json.simple library to access this feature through Java means we can encode or decode JSON Object using this json.simple library in Java Programming Language. Now, the json.simple package for Java contains the following files in it. So to access we first have to install json.simple package. For installation first, we required to set the json-simple.jar classpath or add the Maven dependency in different cases. Step 1: Download the json.simple using this link: Download link for json.sample Step 2: There is one more method to add the Maven dependency, so for that, we have to add the code given below to our pom.xml file. <dependency> <groupId>com.googlecode.json-simple</groupId> <artifactId>json-simple</artifactId> <version>1.1</version> </dependency> The above-downloaded .jar file contains these Java source files in it : // .jar file META-INF/MANIFEST.MF org.json.simple.ItemList.class org.json.simple.JSONArray.class org.json.simple.JSONAware.class org.json.simple.JSONObject.class org.json.simple.JSONStreamAware.class org.json.simple.JSONValue.class org.json.simple.parser.ContainerFactory.class org.json.simple.parser.ContentHandler.class org.json.simple.parser.JSONParser.class org.json.simple.parser.ParseException.class org.json.simple.parser.Yylex.class org.json.simple.parser.Yytoken.class As we discussed above, this json.simple library is used to read/write or encode/decode JSON objects in Java. So let’s see how we can code for encoding part of the JSON object using JSONObject function. Now we create a java file mainEncoding.java and save the below-written code in it. Java import org.json.simple.JSONObject; // Program for print data in JSON format.public class JavaJsonEncoding { public static void main(String args[]) { // In java JSONObject is used to create JSON object // which is a subclass of java.util.HashMap. JSONObject file = new JSONObject(); file.put("Full Name", "Ritu Sharma"); file.put("Roll No.", new Integer(1704310046)); file.put("Tution Fees", new Double(65400)); // To print in JSON format. System.out.print(file); }} Output : {"Full Name":"Ritu Sharma", "Roll No.":1704310046, "Tution Fees":65400} Now we will see how we can code for decoding part of the JSON object using JSONObjectfunction. Now we create a java file mainDecoding.java and save the below-written code in it. Java import org.json.simple.JSONObject;import org.json.simple.JSONValue; public class JavaJsonDecoding { public static void main(String[] args) { // Converting JSON data into Java String format String k = "{\"Full Name\":\"Ritu Sharma\", \"Tution Fees\":65400.0, \"Roll No.\":1704310046}"; Object file = JSONValue.parse(k); // In java JSONObject is used to create JSON object JSONObject jsonObjectdecode = (JSONObject)file; // Converting into Java Data type // format From Json is the step of Decoding. String name = (String)jsonObjectdecode.get("Full Name"); double fees = (Double)jsonObjectdecode.get("Tution Fees"); long rollno = (Long)jsonObjectdecode.get("Roll No."); System.out.println(name + " " + fees + " " + rollno); }} Output : Ritu Sharma 65400.0 1704310046 Note: Here Java JSON Encoding can also be done using a list or map. JSON Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Constructors in Java Stream In Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file in Java Java Programming Examples Internal Working of HashMap in Java Checked vs Unchecked Exceptions in Java Strings in Java StringBuilder Class in Java with Examples
[ { "code": null, "e": 23894, "s": 23866, "text": "\n10 Sep, 2020" }, { "code": null, "e": 24191, "s": 23894, "text": "JSON stands for JavaScript Object Notation which is a lightweight text-based open standard designed which is easy for human-readable data interchange. In general, JSON is extended from JavaScript. JSON is language independent and It is easy to read and write. The file extension of JSON is .json." }, { "code": null, "e": 24214, "s": 24191, "text": "Example – JSON format " }, { "code": null, "e": 24479, "s": 24214, "text": "In the below given example, you will see how you can store values in JSON format. Consider student information where Stu_id, Stu_Name, Course is an entity you need to store then in JSON format you can store these values in key values pair form. Let’s have a look. " }, { "code": null, "e": 24744, "s": 24479, "text": "{\n \"Student\": [\n \n {\n \"Stu_id\" : \"1001\",\n \"Stu_Name\" : \"Ashish\",\n \"Course\" : \"Java\",\n },\n \n {\n \"Stu_id\" : \"1002\",\n \"Stu_Name\" : \"Rana\",\n \"Course\" : \"Advance Java\",\n }\n ]\n}\n" }, { "code": null, "e": 25280, "s": 24744, "text": "It is the method by which we can access means read or write JSON data in Java Programming Language. Here we simply use the json.simple library to access this feature through Java means we can encode or decode JSON Object using this json.simple library in Java Programming Language. Now, the json.simple package for Java contains the following files in it. So to access we first have to install json.simple package. For installation first, we required to set the json-simple.jar classpath or add the Maven dependency in different cases." }, { "code": null, "e": 25361, "s": 25280, "text": "Step 1: Download the json.simple using this link: Download link for json.sample " }, { "code": null, "e": 25494, "s": 25361, "text": "Step 2: There is one more method to add the Maven dependency, so for that, we have to add the code given below to our pom.xml file. " }, { "code": null, "e": 25648, "s": 25494, "text": " <dependency>\n <groupId>com.googlecode.json-simple</groupId> \n <artifactId>json-simple</artifactId> \n <version>1.1</version> \n </dependency>\n" }, { "code": null, "e": 25721, "s": 25648, "text": "The above-downloaded .jar file contains these Java source files in it : " }, { "code": null, "e": 26201, "s": 25721, "text": "// .jar file \nMETA-INF/MANIFEST.MF\norg.json.simple.ItemList.class\norg.json.simple.JSONArray.class\norg.json.simple.JSONAware.class\norg.json.simple.JSONObject.class\norg.json.simple.JSONStreamAware.class\norg.json.simple.JSONValue.class\norg.json.simple.parser.ContainerFactory.class\norg.json.simple.parser.ContentHandler.class\norg.json.simple.parser.JSONParser.class\norg.json.simple.parser.ParseException.class\norg.json.simple.parser.Yylex.class\norg.json.simple.parser.Yytoken.class\n" }, { "code": null, "e": 26486, "s": 26201, "text": "As we discussed above, this json.simple library is used to read/write or encode/decode JSON objects in Java. So let’s see how we can code for encoding part of the JSON object using JSONObject function. Now we create a java file mainEncoding.java and save the below-written code in it." }, { "code": null, "e": 26491, "s": 26486, "text": "Java" }, { "code": "import org.json.simple.JSONObject; // Program for print data in JSON format.public class JavaJsonEncoding { public static void main(String args[]) { // In java JSONObject is used to create JSON object // which is a subclass of java.util.HashMap. JSONObject file = new JSONObject(); file.put(\"Full Name\", \"Ritu Sharma\"); file.put(\"Roll No.\", new Integer(1704310046)); file.put(\"Tution Fees\", new Double(65400)); // To print in JSON format. System.out.print(file); }}", "e": 27036, "s": 26491, "text": null }, { "code": null, "e": 27045, "s": 27036, "text": "Output :" }, { "code": null, "e": 27118, "s": 27045, "text": "{\"Full Name\":\"Ritu Sharma\", \"Roll No.\":1704310046, \"Tution Fees\":65400}\n" }, { "code": null, "e": 27297, "s": 27118, "text": "Now we will see how we can code for decoding part of the JSON object using JSONObjectfunction. Now we create a java file mainDecoding.java and save the below-written code in it. " }, { "code": null, "e": 27302, "s": 27297, "text": "Java" }, { "code": "import org.json.simple.JSONObject;import org.json.simple.JSONValue; public class JavaJsonDecoding { public static void main(String[] args) { // Converting JSON data into Java String format String k = \"{\\\"Full Name\\\":\\\"Ritu Sharma\\\", \\\"Tution Fees\\\":65400.0, \\\"Roll No.\\\":1704310046}\"; Object file = JSONValue.parse(k); // In java JSONObject is used to create JSON object JSONObject jsonObjectdecode = (JSONObject)file; // Converting into Java Data type // format From Json is the step of Decoding. String name = (String)jsonObjectdecode.get(\"Full Name\"); double fees = (Double)jsonObjectdecode.get(\"Tution Fees\"); long rollno = (Long)jsonObjectdecode.get(\"Roll No.\"); System.out.println(name + \" \" + fees + \" \" + rollno); }}", "e": 28123, "s": 27302, "text": null }, { "code": null, "e": 28132, "s": 28123, "text": "Output :" }, { "code": null, "e": 28164, "s": 28132, "text": "Ritu Sharma 65400.0 1704310046\n" }, { "code": null, "e": 28233, "s": 28164, "text": "Note: Here Java JSON Encoding can also be done using a list or map. " }, { "code": null, "e": 28238, "s": 28233, "text": "JSON" }, { "code": null, "e": 28243, "s": 28238, "text": "Java" }, { "code": null, "e": 28248, "s": 28243, "text": "Java" }, { "code": null, "e": 28346, "s": 28248, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28355, "s": 28346, "text": "Comments" }, { "code": null, "e": 28368, "s": 28355, "text": "Old Comments" }, { "code": null, "e": 28389, "s": 28368, "text": "Constructors in Java" }, { "code": null, "e": 28404, "s": 28389, "text": "Stream In Java" }, { "code": null, "e": 28423, "s": 28404, "text": "Exceptions in Java" }, { "code": null, "e": 28453, "s": 28423, "text": "Functional Interfaces in Java" }, { "code": null, "e": 28499, "s": 28453, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 28525, "s": 28499, "text": "Java Programming Examples" }, { "code": null, "e": 28561, "s": 28525, "text": "Internal Working of HashMap in Java" }, { "code": null, "e": 28601, "s": 28561, "text": "Checked vs Unchecked Exceptions in Java" }, { "code": null, "e": 28617, "s": 28601, "text": "Strings in Java" } ]
Understanding and implementing a fully convolutional network (FCN) | by Himanshu Rawlani | Towards Data Science
Convolutional neural networks (CNN) work great for computer vision tasks. Using a pre-trained model that is trained on huge datasets like ImageNet, COCO, etc. we can quickly specialize these architectures to work for our unique dataset. This process is termed as transfer learning. However, there’s a catch! Pre-trained models for image classification and object detection tasks are usually trained on fixed input image sizes. These typically range from 224x224x3 to somewhere around 512x512x3 and mostly have an aspect ratio of 1 i.e. the width and height of the image are equal. If they are not equal then the images are resized to be of equal height and width. Newer architectures do have the ability to handle variable input image sizes but it’s more common in object detection and segmentation tasks as compared to image classification tasks. Recently, I came across an interesting use case wherein I had 5 different classes of image and each of the classes had minuscule differences. Also, the aspect ratio of the images was higher than usual. The average height of the image was around 30 pixels and the width was around 300 pixels. This was an interesting one for the following reasons: Resizing the images easily distorted the important featuresPre-trained architectures were gargantuan and always overfitted the datasetThe task demanded low latency Resizing the images easily distorted the important features Pre-trained architectures were gargantuan and always overfitted the dataset The task demanded low latency I tried base models of MobileNet and EfficientNet but nothing worked. There was a need for a network which didn’t have any restrictions on input image size and could perform image classification task at hand. The first thing that struck me was fully convolutional networks (FCNs). FCN is a network that does not contain any “Dense” layers (as in traditional CNNs) instead it contains 1x1 convolutions that perform the task of fully connected layers (Dense layers). Though the absence of dense layers makes it possible to feed in variable inputs, there are a couple of techniques that enable us to use dense layers while cherishing variable input dimensions. This tutorial delineates some of those techniques. In this tutorial, we will go through the following steps: Building a fully convolutional network (FCN) in TensorFlow using KerasDownloading and splitting a sample datasetCreating a generator in Keras to load and process a batch of data in memoryTraining the network with variable batch dimensionsDeploying the model using TensorFlow Serving Building a fully convolutional network (FCN) in TensorFlow using Keras Downloading and splitting a sample dataset Creating a generator in Keras to load and process a batch of data in memory Training the network with variable batch dimensions Deploying the model using TensorFlow Serving Update: There are many hyperparameters that you'll come across while building and training an FCN from scratch. I've written another post where I give a walkthrough of hyperparameter optimization, including data augmentation, using the same FCN architecture discussed in this article. You can read about it here. towardsdatascience.com As always in my tutorials, here’s the link to the project uploaded on GitHub. Please clone the repo and follow the tutorial step by step for better understanding. Note: The code snippets in this article highlight only a part of the actual script, please refer to the GitHub repo for complete code. github.com We build our FCN model by stacking convolution blocks consisting of 2D convolution layers (Conv2D) and the required regularization (Dropout and BatchNormalization). Regularization prevents overfitting and helps in quick convergence. We also add an activation layer to incorporate non-linearity. In Keras, the input batch dimension is added automatically and we don’t need to specify it in the input layer. Since the height and width of our input images are variable, we specify input shape as (None, None, 3). The 3 is for the number of channels in our image which is fixed for colored images (RGB). After applying a convolution block on the input, the height and width of the input will decrease based on the values of kernel_size and strides. If the input image size is too small then we might fall short of the minimum required height and width (which should be greater than or equal to the kernel size) for the next convolution block. A trial and error way to determine the minimum input dimension is as follows: Decide the number of convolution blocks to stackChoose any input shape to say (32, 32, 3) and stack the convolution blocks with an increasing number of channelsTry building the model and print model.summary() to view the output shape of each layer.Ensure that you get (1, 1, num_of_filters) as the output dimension from the last convolution block (this will be input to fully connected layer).Try decreasing/increasing the input shape, kernel size or strides to satisfy the condition in step 4. The input shape, along with other configurations, which satisfies the condition is the minimum input dimension required by your network. Decide the number of convolution blocks to stack Choose any input shape to say (32, 32, 3) and stack the convolution blocks with an increasing number of channels Try building the model and print model.summary() to view the output shape of each layer. Ensure that you get (1, 1, num_of_filters) as the output dimension from the last convolution block (this will be input to fully connected layer). Try decreasing/increasing the input shape, kernel size or strides to satisfy the condition in step 4. The input shape, along with other configurations, which satisfies the condition is the minimum input dimension required by your network. There’s also a mathematical way to calculate the spatial size of the output volume as a function of the input volume which is illustrated here. After finding the minimum input dimension, we now need to pass the output of the last convolution block to the fully connected layers. However, any input that has dimension greater than the minimum input dimension needs to be pooled down to satisfy the condition in step 4. We understand how to do that using our main ingredient. The fully connected layers (FC layers) are the ones that will perform the classification tasks for us. There are two ways in which we can build FC layers: Dense layers1x1 convolutions Dense layers 1x1 convolutions If we want to use dense layers then the model input dimensions have to be fixed because the number of parameters, which goes as input to the dense layer, has to be predefined to create a dense layer. Specifically, we want the height and width in (height, width, num_of_filters) from the output of the last convolution block to be constant or 1. The number of filters is always going to be fixed as those values are defined by us in every convolution block. The input dimension to the 1x1 convolution could be (1, 1, num_of_filters) or (height, width, num_of_filters) as they mimic the functionality of FC layer along num_of_filters dimension. However, the input to the last layer (Softmax activation layer), after the 1x1 convolutions, must be of fixed length (number of classes). The main ingredient: GlobalMaxPooling2D() / GlobalAveragePooling2D(). These layers in Keras convert an input of dimension (height, width, num_of_filters) to (1, 1, num_of_filters) essentially taking max or average of the values along height and width dimensions for every filter along num_of_filters dimension. The code includes dense layers (commented out) and 1x1 convolutions. After building and training the model with both the configurations here are some of my observations: Both models contain equal number of trainable parameters.Similar training and inference time.Dense layers generalize better than 1x1 convolutions. Both models contain equal number of trainable parameters. Similar training and inference time. Dense layers generalize better than 1x1 convolutions. The third point cannot be generalized because it depends on factors such as number of images in the dataset, data augmentation used, model initialization, etc. However, these were the observations in my experiments. You can run the script independently, to test that the model is being built successfully, by firing the command $python model.py. The flowers dataset being used in this tutorial is primarily intended to understand the challenges that we face while training a model with variable input dimensions. Some interesting datasets to test our FCN model might come from medical imaging domain, which contains microscopic features that are crucial in classifying images, and other datasets containing geometric patterns/shapes that may get distorted after resizing the image. The script provided (data.py) needs to be run independently ($python data.py). It’ll perform the following tasks: Downloads flower dataset which contains 5 classes (‘daisy’, ‘dandelion’, ‘rose’, ‘sunflower’, ‘tulip’). More details about the dataset here.Splits the dataset into training and validation sets. You can set the number of images to be copied into training and validation sets.Gives statistics about the dataset like minimum, average and maximum height and width of the images. Downloads flower dataset which contains 5 classes (‘daisy’, ‘dandelion’, ‘rose’, ‘sunflower’, ‘tulip’). More details about the dataset here. Splits the dataset into training and validation sets. You can set the number of images to be copied into training and validation sets. Gives statistics about the dataset like minimum, average and maximum height and width of the images. This script downloads the .tar file and extracts its contents in the current directory using using keras.utils.get_file(). If you want to use TensorFlow Datasets (TFDS) you can check out this tutorial which illustrates the usage of TFDS along with data augmentation. We want to train our model on varying input dimensions. Every image in a given batch and across batches has different dimensions. So what’s the problem? Let’s take a step back and revisit how we train a traditional image classifier. In traditional image classifiers, the images are resized to a given dimension, packed into batches by converting into numpy array or tensors and this batch of data is forward propagated through the model. The metrics (loss, accuracy, etc.) are evaluated across this batch. The gradients to be backpropagated are calculated based on these metrics. We cannot resize our images (since we’ll lose our microscopic features). Now, since we cannot resize our images, converting them into batches of numpy array becomes impossible. That’s because if you have a list of 10 images of dimension (height, width, 3) with different values for height and width and you try to pass it to np.array(), the resulting array would have a shape of (10,) and not (10, height, width, 3)! However, our model expects the input dimensions to be of the latter shape. A workaround for this is to write a custom training loop that performs the following: We pass each image, in the list (batch), through the model by converting (height, width, 3) to (1, height, width, 3) using np.expand_dims(img, axis=0).Accumulate the metrics for each image in the python list (batch).Calculate the loss and the gradients using the accumulated metrics. Apply the gradient update to the model.Reset the values for the metrics and create a new list (batch) of images. We pass each image, in the list (batch), through the model by converting (height, width, 3) to (1, height, width, 3) using np.expand_dims(img, axis=0). Accumulate the metrics for each image in the python list (batch). Calculate the loss and the gradients using the accumulated metrics. Apply the gradient update to the model. Reset the values for the metrics and create a new list (batch) of images. I tried out the above-mentioned steps and my suggestion is not to go with the above strategy. It’s arduous, results in complex and unsustainable code and runs very slow! Everyone loves the elegant and kerassical model.fit() and model.fit_generator(). The latter is what we’ll use here! But first, the carburetor. A carburetor is a device that mixes air and fuel for internal combustion engines in the proper air-fuel ratio for combustion. And that’s what we need, air! We find the max height and width of images in a batch and pad every other image with zeros so that every image in the batch has an equal dimension. Now we can easily convert it to a numpy array or a tensor and pass it to the fit_generator(). The model automatically learns to ignore the zeros (basically black pixels) and learns features from the intended portion from the padded image. This way we have a batch with equal image dimensions but every batch has a different shape (due to difference in max height and width of images across batches). You can run generator.py file independently using $python generator.py and cross-check the output. Creating generators in Keras is dead simple and there’s a great tutorial to get started with it here. One great addition to generator.py would be to include support for data augmentation, you can get some inspiration for it here. The training script imports and instantiates the following classes: Generator: We need to specify the path to train and val directories created by data.py.FCN_model: We need to specify the number of classes required in the final output layer. Generator: We need to specify the path to train and val directories created by data.py. FCN_model: We need to specify the number of classes required in the final output layer. The above objects are passed to the train() function which compiles the model with Adam optimizer and categorical cross-entropy loss function. We create a checkpoint callback which saves the best model during training. The best model is determined based on the value of loss calculated on the validation set at the end of each epoch. As we can see fit_generator() function simplifies the code to a great extent and is pleasing to the eyes. I would suggest performing training on Google Colab unless you have a GPU in your local machine. The GitHub repo includes a Colab notebook which puts all the pieces together required for training. You can modify the python scripts in Colab itself and train different model configurations on the dataset of your choice. Once you’ve completed the training you can download the best snapshot to your local machine from the “Files” tab in Colab. After you’ve downloaded the model, you need to export it to SavedModel format using export_savedmodel.py. Specify the path to the downloaded model (.h5 file) in the main function and execute the script using the command $python export_savedmodel.py. This script uses the new features in TensorFlow 2.0 which loads a Keras model from .h5 file and saves it to TensorFlow SavedModel format. SavedModel will be exported to export_path specified in the script. This SavedModel is required by TensorFlow serving docker image. To start TensorFlow Serving server, go to the directory where the SavedModel is exported (./flower_classifier in this case) and run the following command (Note: You must have Docker installed on your machine): $ docker run --rm -t -p 8501:8501 -v "$(pwd):/models/flower_classifier" -e MODEL_NAME=flower_classifier --name flower_classifier tensorflow/serving The above command performs the following steps: Pulls the tensorflow/serving docker image if it is not present locally.The “-p” flag maps port 8501 on the local machine to port 8501 in the docker container.The “-v” flag mounts your current directory (specified by $(pwd)) to /models/flower_classifier in the docker container.The “-e” flag sets the environment variable in docker container which is used by the TensorFlow Serving server to create REST endpoint.The “ — rm” flag removes any anonymous volumes associated with the container when the container is removed.The “-t” shows the container logs in your current terminal. You can press CTRL+C to go back to your terminal and the container will continue to run in the background. Pulls the tensorflow/serving docker image if it is not present locally. The “-p” flag maps port 8501 on the local machine to port 8501 in the docker container. The “-v” flag mounts your current directory (specified by $(pwd)) to /models/flower_classifier in the docker container. The “-e” flag sets the environment variable in docker container which is used by the TensorFlow Serving server to create REST endpoint. The “ — rm” flag removes any anonymous volumes associated with the container when the container is removed. The “-t” shows the container logs in your current terminal. You can press CTRL+C to go back to your terminal and the container will continue to run in the background. You can verify that your container is running in the background using $ docker ps command. You can also see the container logs using $ docker logs your_container_id. The inference.py script contains the code to construct batches of uniform image dimensions and send those batches as a POST request to TensorFlow Serving server. The output received from the server is decoded and printed in the terminal. In this tutorial, we understood the following: Building a vanilla fully convolutional network for image classification with variable input dimensions.Training FCN models with equal image shapes in a batch and different batch shapes.Deploying trained models using TensorFlow Serving docker image. Building a vanilla fully convolutional network for image classification with variable input dimensions. Training FCN models with equal image shapes in a batch and different batch shapes. Deploying trained models using TensorFlow Serving docker image. Note that, this tutorial throws light on only a single component in a machine learning workflow. ML pipelines consist of enormous training, inference and monitoring cycles that are specific to organizations and their use-cases. Building these pipelines requires a deeper understanding of the driver, its passengers and the route of the vehicle. Only then it’s possible to deliver the dream conveyance! I hope you find this tutorial helpful in building your next awesome machine learning project. I’d love to have your suggestions and improvements to the repository, feel free to raise a GitHub issue for the same. If you find any information incorrect or missing in the article please do let me know in the comments section. Thanks!
[ { "code": null, "e": 835, "s": 171, "text": "Convolutional neural networks (CNN) work great for computer vision tasks. Using a pre-trained model that is trained on huge datasets like ImageNet, COCO, etc. we can quickly specialize these architectures to work for our unique dataset. This process is termed as transfer learning. However, there’s a catch! Pre-trained models for image classification and object detection tasks are usually trained on fixed input image sizes. These typically range from 224x224x3 to somewhere around 512x512x3 and mostly have an aspect ratio of 1 i.e. the width and height of the image are equal. If they are not equal then the images are resized to be of equal height and width." }, { "code": null, "e": 1366, "s": 835, "text": "Newer architectures do have the ability to handle variable input image sizes but it’s more common in object detection and segmentation tasks as compared to image classification tasks. Recently, I came across an interesting use case wherein I had 5 different classes of image and each of the classes had minuscule differences. Also, the aspect ratio of the images was higher than usual. The average height of the image was around 30 pixels and the width was around 300 pixels. This was an interesting one for the following reasons:" }, { "code": null, "e": 1530, "s": 1366, "text": "Resizing the images easily distorted the important featuresPre-trained architectures were gargantuan and always overfitted the datasetThe task demanded low latency" }, { "code": null, "e": 1590, "s": 1530, "text": "Resizing the images easily distorted the important features" }, { "code": null, "e": 1666, "s": 1590, "text": "Pre-trained architectures were gargantuan and always overfitted the dataset" }, { "code": null, "e": 1696, "s": 1666, "text": "The task demanded low latency" }, { "code": null, "e": 2463, "s": 1696, "text": "I tried base models of MobileNet and EfficientNet but nothing worked. There was a need for a network which didn’t have any restrictions on input image size and could perform image classification task at hand. The first thing that struck me was fully convolutional networks (FCNs). FCN is a network that does not contain any “Dense” layers (as in traditional CNNs) instead it contains 1x1 convolutions that perform the task of fully connected layers (Dense layers). Though the absence of dense layers makes it possible to feed in variable inputs, there are a couple of techniques that enable us to use dense layers while cherishing variable input dimensions. This tutorial delineates some of those techniques. In this tutorial, we will go through the following steps:" }, { "code": null, "e": 2746, "s": 2463, "text": "Building a fully convolutional network (FCN) in TensorFlow using KerasDownloading and splitting a sample datasetCreating a generator in Keras to load and process a batch of data in memoryTraining the network with variable batch dimensionsDeploying the model using TensorFlow Serving" }, { "code": null, "e": 2817, "s": 2746, "text": "Building a fully convolutional network (FCN) in TensorFlow using Keras" }, { "code": null, "e": 2860, "s": 2817, "text": "Downloading and splitting a sample dataset" }, { "code": null, "e": 2936, "s": 2860, "text": "Creating a generator in Keras to load and process a batch of data in memory" }, { "code": null, "e": 2988, "s": 2936, "text": "Training the network with variable batch dimensions" }, { "code": null, "e": 3033, "s": 2988, "text": "Deploying the model using TensorFlow Serving" }, { "code": null, "e": 3346, "s": 3033, "text": "Update: There are many hyperparameters that you'll come across while building and training an FCN from scratch. I've written another post where I give a walkthrough of hyperparameter optimization, including data augmentation, using the same FCN architecture discussed in this article. You can read about it here." }, { "code": null, "e": 3369, "s": 3346, "text": "towardsdatascience.com" }, { "code": null, "e": 3667, "s": 3369, "text": "As always in my tutorials, here’s the link to the project uploaded on GitHub. Please clone the repo and follow the tutorial step by step for better understanding. Note: The code snippets in this article highlight only a part of the actual script, please refer to the GitHub repo for complete code." }, { "code": null, "e": 3678, "s": 3667, "text": "github.com" }, { "code": null, "e": 4278, "s": 3678, "text": "We build our FCN model by stacking convolution blocks consisting of 2D convolution layers (Conv2D) and the required regularization (Dropout and BatchNormalization). Regularization prevents overfitting and helps in quick convergence. We also add an activation layer to incorporate non-linearity. In Keras, the input batch dimension is added automatically and we don’t need to specify it in the input layer. Since the height and width of our input images are variable, we specify input shape as (None, None, 3). The 3 is for the number of channels in our image which is fixed for colored images (RGB)." }, { "code": null, "e": 4695, "s": 4278, "text": "After applying a convolution block on the input, the height and width of the input will decrease based on the values of kernel_size and strides. If the input image size is too small then we might fall short of the minimum required height and width (which should be greater than or equal to the kernel size) for the next convolution block. A trial and error way to determine the minimum input dimension is as follows:" }, { "code": null, "e": 5327, "s": 4695, "text": "Decide the number of convolution blocks to stackChoose any input shape to say (32, 32, 3) and stack the convolution blocks with an increasing number of channelsTry building the model and print model.summary() to view the output shape of each layer.Ensure that you get (1, 1, num_of_filters) as the output dimension from the last convolution block (this will be input to fully connected layer).Try decreasing/increasing the input shape, kernel size or strides to satisfy the condition in step 4. The input shape, along with other configurations, which satisfies the condition is the minimum input dimension required by your network." }, { "code": null, "e": 5376, "s": 5327, "text": "Decide the number of convolution blocks to stack" }, { "code": null, "e": 5489, "s": 5376, "text": "Choose any input shape to say (32, 32, 3) and stack the convolution blocks with an increasing number of channels" }, { "code": null, "e": 5578, "s": 5489, "text": "Try building the model and print model.summary() to view the output shape of each layer." }, { "code": null, "e": 5724, "s": 5578, "text": "Ensure that you get (1, 1, num_of_filters) as the output dimension from the last convolution block (this will be input to fully connected layer)." }, { "code": null, "e": 5963, "s": 5724, "text": "Try decreasing/increasing the input shape, kernel size or strides to satisfy the condition in step 4. The input shape, along with other configurations, which satisfies the condition is the minimum input dimension required by your network." }, { "code": null, "e": 6437, "s": 5963, "text": "There’s also a mathematical way to calculate the spatial size of the output volume as a function of the input volume which is illustrated here. After finding the minimum input dimension, we now need to pass the output of the last convolution block to the fully connected layers. However, any input that has dimension greater than the minimum input dimension needs to be pooled down to satisfy the condition in step 4. We understand how to do that using our main ingredient." }, { "code": null, "e": 6592, "s": 6437, "text": "The fully connected layers (FC layers) are the ones that will perform the classification tasks for us. There are two ways in which we can build FC layers:" }, { "code": null, "e": 6621, "s": 6592, "text": "Dense layers1x1 convolutions" }, { "code": null, "e": 6634, "s": 6621, "text": "Dense layers" }, { "code": null, "e": 6651, "s": 6634, "text": "1x1 convolutions" }, { "code": null, "e": 7108, "s": 6651, "text": "If we want to use dense layers then the model input dimensions have to be fixed because the number of parameters, which goes as input to the dense layer, has to be predefined to create a dense layer. Specifically, we want the height and width in (height, width, num_of_filters) from the output of the last convolution block to be constant or 1. The number of filters is always going to be fixed as those values are defined by us in every convolution block." }, { "code": null, "e": 7432, "s": 7108, "text": "The input dimension to the 1x1 convolution could be (1, 1, num_of_filters) or (height, width, num_of_filters) as they mimic the functionality of FC layer along num_of_filters dimension. However, the input to the last layer (Softmax activation layer), after the 1x1 convolutions, must be of fixed length (number of classes)." }, { "code": null, "e": 7743, "s": 7432, "text": "The main ingredient: GlobalMaxPooling2D() / GlobalAveragePooling2D(). These layers in Keras convert an input of dimension (height, width, num_of_filters) to (1, 1, num_of_filters) essentially taking max or average of the values along height and width dimensions for every filter along num_of_filters dimension." }, { "code": null, "e": 7913, "s": 7743, "text": "The code includes dense layers (commented out) and 1x1 convolutions. After building and training the model with both the configurations here are some of my observations:" }, { "code": null, "e": 8060, "s": 7913, "text": "Both models contain equal number of trainable parameters.Similar training and inference time.Dense layers generalize better than 1x1 convolutions." }, { "code": null, "e": 8118, "s": 8060, "text": "Both models contain equal number of trainable parameters." }, { "code": null, "e": 8155, "s": 8118, "text": "Similar training and inference time." }, { "code": null, "e": 8209, "s": 8155, "text": "Dense layers generalize better than 1x1 convolutions." }, { "code": null, "e": 8555, "s": 8209, "text": "The third point cannot be generalized because it depends on factors such as number of images in the dataset, data augmentation used, model initialization, etc. However, these were the observations in my experiments. You can run the script independently, to test that the model is being built successfully, by firing the command $python model.py." }, { "code": null, "e": 8991, "s": 8555, "text": "The flowers dataset being used in this tutorial is primarily intended to understand the challenges that we face while training a model with variable input dimensions. Some interesting datasets to test our FCN model might come from medical imaging domain, which contains microscopic features that are crucial in classifying images, and other datasets containing geometric patterns/shapes that may get distorted after resizing the image." }, { "code": null, "e": 9105, "s": 8991, "text": "The script provided (data.py) needs to be run independently ($python data.py). It’ll perform the following tasks:" }, { "code": null, "e": 9480, "s": 9105, "text": "Downloads flower dataset which contains 5 classes (‘daisy’, ‘dandelion’, ‘rose’, ‘sunflower’, ‘tulip’). More details about the dataset here.Splits the dataset into training and validation sets. You can set the number of images to be copied into training and validation sets.Gives statistics about the dataset like minimum, average and maximum height and width of the images." }, { "code": null, "e": 9621, "s": 9480, "text": "Downloads flower dataset which contains 5 classes (‘daisy’, ‘dandelion’, ‘rose’, ‘sunflower’, ‘tulip’). More details about the dataset here." }, { "code": null, "e": 9756, "s": 9621, "text": "Splits the dataset into training and validation sets. You can set the number of images to be copied into training and validation sets." }, { "code": null, "e": 9857, "s": 9756, "text": "Gives statistics about the dataset like minimum, average and maximum height and width of the images." }, { "code": null, "e": 10124, "s": 9857, "text": "This script downloads the .tar file and extracts its contents in the current directory using using keras.utils.get_file(). If you want to use TensorFlow Datasets (TFDS) you can check out this tutorial which illustrates the usage of TFDS along with data augmentation." }, { "code": null, "e": 10704, "s": 10124, "text": "We want to train our model on varying input dimensions. Every image in a given batch and across batches has different dimensions. So what’s the problem? Let’s take a step back and revisit how we train a traditional image classifier. In traditional image classifiers, the images are resized to a given dimension, packed into batches by converting into numpy array or tensors and this batch of data is forward propagated through the model. The metrics (loss, accuracy, etc.) are evaluated across this batch. The gradients to be backpropagated are calculated based on these metrics." }, { "code": null, "e": 11282, "s": 10704, "text": "We cannot resize our images (since we’ll lose our microscopic features). Now, since we cannot resize our images, converting them into batches of numpy array becomes impossible. That’s because if you have a list of 10 images of dimension (height, width, 3) with different values for height and width and you try to pass it to np.array(), the resulting array would have a shape of (10,) and not (10, height, width, 3)! However, our model expects the input dimensions to be of the latter shape. A workaround for this is to write a custom training loop that performs the following:" }, { "code": null, "e": 11679, "s": 11282, "text": "We pass each image, in the list (batch), through the model by converting (height, width, 3) to (1, height, width, 3) using np.expand_dims(img, axis=0).Accumulate the metrics for each image in the python list (batch).Calculate the loss and the gradients using the accumulated metrics. Apply the gradient update to the model.Reset the values for the metrics and create a new list (batch) of images." }, { "code": null, "e": 11831, "s": 11679, "text": "We pass each image, in the list (batch), through the model by converting (height, width, 3) to (1, height, width, 3) using np.expand_dims(img, axis=0)." }, { "code": null, "e": 11897, "s": 11831, "text": "Accumulate the metrics for each image in the python list (batch)." }, { "code": null, "e": 12005, "s": 11897, "text": "Calculate the loss and the gradients using the accumulated metrics. Apply the gradient update to the model." }, { "code": null, "e": 12079, "s": 12005, "text": "Reset the values for the metrics and create a new list (batch) of images." }, { "code": null, "e": 12392, "s": 12079, "text": "I tried out the above-mentioned steps and my suggestion is not to go with the above strategy. It’s arduous, results in complex and unsustainable code and runs very slow! Everyone loves the elegant and kerassical model.fit() and model.fit_generator(). The latter is what we’ll use here! But first, the carburetor." }, { "code": null, "e": 13195, "s": 12392, "text": "A carburetor is a device that mixes air and fuel for internal combustion engines in the proper air-fuel ratio for combustion. And that’s what we need, air! We find the max height and width of images in a batch and pad every other image with zeros so that every image in the batch has an equal dimension. Now we can easily convert it to a numpy array or a tensor and pass it to the fit_generator(). The model automatically learns to ignore the zeros (basically black pixels) and learns features from the intended portion from the padded image. This way we have a batch with equal image dimensions but every batch has a different shape (due to difference in max height and width of images across batches). You can run generator.py file independently using $python generator.py and cross-check the output." }, { "code": null, "e": 13425, "s": 13195, "text": "Creating generators in Keras is dead simple and there’s a great tutorial to get started with it here. One great addition to generator.py would be to include support for data augmentation, you can get some inspiration for it here." }, { "code": null, "e": 13493, "s": 13425, "text": "The training script imports and instantiates the following classes:" }, { "code": null, "e": 13668, "s": 13493, "text": "Generator: We need to specify the path to train and val directories created by data.py.FCN_model: We need to specify the number of classes required in the final output layer." }, { "code": null, "e": 13756, "s": 13668, "text": "Generator: We need to specify the path to train and val directories created by data.py." }, { "code": null, "e": 13844, "s": 13756, "text": "FCN_model: We need to specify the number of classes required in the final output layer." }, { "code": null, "e": 14284, "s": 13844, "text": "The above objects are passed to the train() function which compiles the model with Adam optimizer and categorical cross-entropy loss function. We create a checkpoint callback which saves the best model during training. The best model is determined based on the value of loss calculated on the validation set at the end of each epoch. As we can see fit_generator() function simplifies the code to a great extent and is pleasing to the eyes." }, { "code": null, "e": 14726, "s": 14284, "text": "I would suggest performing training on Google Colab unless you have a GPU in your local machine. The GitHub repo includes a Colab notebook which puts all the pieces together required for training. You can modify the python scripts in Colab itself and train different model configurations on the dataset of your choice. Once you’ve completed the training you can download the best snapshot to your local machine from the “Files” tab in Colab." }, { "code": null, "e": 15246, "s": 14726, "text": "After you’ve downloaded the model, you need to export it to SavedModel format using export_savedmodel.py. Specify the path to the downloaded model (.h5 file) in the main function and execute the script using the command $python export_savedmodel.py. This script uses the new features in TensorFlow 2.0 which loads a Keras model from .h5 file and saves it to TensorFlow SavedModel format. SavedModel will be exported to export_path specified in the script. This SavedModel is required by TensorFlow serving docker image." }, { "code": null, "e": 15456, "s": 15246, "text": "To start TensorFlow Serving server, go to the directory where the SavedModel is exported (./flower_classifier in this case) and run the following command (Note: You must have Docker installed on your machine):" }, { "code": null, "e": 15604, "s": 15456, "text": "$ docker run --rm -t -p 8501:8501 -v \"$(pwd):/models/flower_classifier\" -e MODEL_NAME=flower_classifier --name flower_classifier tensorflow/serving" }, { "code": null, "e": 15652, "s": 15604, "text": "The above command performs the following steps:" }, { "code": null, "e": 16338, "s": 15652, "text": "Pulls the tensorflow/serving docker image if it is not present locally.The “-p” flag maps port 8501 on the local machine to port 8501 in the docker container.The “-v” flag mounts your current directory (specified by $(pwd)) to /models/flower_classifier in the docker container.The “-e” flag sets the environment variable in docker container which is used by the TensorFlow Serving server to create REST endpoint.The “ — rm” flag removes any anonymous volumes associated with the container when the container is removed.The “-t” shows the container logs in your current terminal. You can press CTRL+C to go back to your terminal and the container will continue to run in the background." }, { "code": null, "e": 16410, "s": 16338, "text": "Pulls the tensorflow/serving docker image if it is not present locally." }, { "code": null, "e": 16498, "s": 16410, "text": "The “-p” flag maps port 8501 on the local machine to port 8501 in the docker container." }, { "code": null, "e": 16618, "s": 16498, "text": "The “-v” flag mounts your current directory (specified by $(pwd)) to /models/flower_classifier in the docker container." }, { "code": null, "e": 16754, "s": 16618, "text": "The “-e” flag sets the environment variable in docker container which is used by the TensorFlow Serving server to create REST endpoint." }, { "code": null, "e": 16862, "s": 16754, "text": "The “ — rm” flag removes any anonymous volumes associated with the container when the container is removed." }, { "code": null, "e": 17029, "s": 16862, "text": "The “-t” shows the container logs in your current terminal. You can press CTRL+C to go back to your terminal and the container will continue to run in the background." }, { "code": null, "e": 17433, "s": 17029, "text": "You can verify that your container is running in the background using $ docker ps command. You can also see the container logs using $ docker logs your_container_id. The inference.py script contains the code to construct batches of uniform image dimensions and send those batches as a POST request to TensorFlow Serving server. The output received from the server is decoded and printed in the terminal." }, { "code": null, "e": 17480, "s": 17433, "text": "In this tutorial, we understood the following:" }, { "code": null, "e": 17729, "s": 17480, "text": "Building a vanilla fully convolutional network for image classification with variable input dimensions.Training FCN models with equal image shapes in a batch and different batch shapes.Deploying trained models using TensorFlow Serving docker image." }, { "code": null, "e": 17833, "s": 17729, "text": "Building a vanilla fully convolutional network for image classification with variable input dimensions." }, { "code": null, "e": 17916, "s": 17833, "text": "Training FCN models with equal image shapes in a batch and different batch shapes." }, { "code": null, "e": 17980, "s": 17916, "text": "Deploying trained models using TensorFlow Serving docker image." }, { "code": null, "e": 18382, "s": 17980, "text": "Note that, this tutorial throws light on only a single component in a machine learning workflow. ML pipelines consist of enormous training, inference and monitoring cycles that are specific to organizations and their use-cases. Building these pipelines requires a deeper understanding of the driver, its passengers and the route of the vehicle. Only then it’s possible to deliver the dream conveyance!" } ]
Can we define an abstract class without abstract method in java?
A method which does not have body is known as abstract method. It contains only method signature with a semi colon and, an abstract keyword before it. public abstract myMethod(); To use an abstract method, you need to inherit it by extending its class and provide implementation to it. A class which contains 0 or more abstract methods is known as abstract class. If it contains at least one abstract method, it must be declared abstract. And yes, you can declare abstract class without defining an abstract method in it. Once you declare a class abstract it indicates that the class is incomplete and, you cannot instantiate it. Hence, if you want to prevent instantiation of a class directly you can declare it abstract. If you want to use the concrete method in an abstract class you need to inherit the class, provide implementation to the abstract methods (if any) and then, you using the subclass object you can invoke the required methods. In the following Java example, the abstract class MyClass contains a concrete method with name display. From another class (AbstractClassExample) we are inheriting the class MyClass and invoking the its concrete method display using the subclass object. Live Demo abstract class MyClass { public void display() { System.out.println("This is a method of abstract class"); } } public class AbstractClassExample extends MyClass{ public static void main(String args[]) { new AbstractClassExample().display(); } } This is a method of abstract class
[ { "code": null, "e": 1213, "s": 1062, "text": "A method which does not have body is known as abstract method. It contains only method signature with a semi colon and, an abstract keyword before it." }, { "code": null, "e": 1241, "s": 1213, "text": "public abstract myMethod();" }, { "code": null, "e": 1348, "s": 1241, "text": "To use an abstract method, you need to inherit it by extending its class and provide implementation to it." }, { "code": null, "e": 1501, "s": 1348, "text": "A class which contains 0 or more abstract methods is known as abstract class. If it contains at least one abstract method, it must be declared abstract." }, { "code": null, "e": 1692, "s": 1501, "text": "And yes, you can declare abstract class without defining an abstract method in it. Once you declare a class abstract it indicates that the class is incomplete and, you cannot instantiate it." }, { "code": null, "e": 1785, "s": 1692, "text": "Hence, if you want to prevent instantiation of a class directly you can declare it abstract." }, { "code": null, "e": 2009, "s": 1785, "text": "If you want to use the concrete method in an abstract class you need to inherit the class, provide implementation to the abstract methods (if any) and then, you using the subclass object you can invoke the required methods." }, { "code": null, "e": 2113, "s": 2009, "text": "In the following Java example, the abstract class MyClass contains a concrete method with name display." }, { "code": null, "e": 2263, "s": 2113, "text": "From another class (AbstractClassExample) we are inheriting the class MyClass and invoking the its concrete method display using the subclass object." }, { "code": null, "e": 2274, "s": 2263, "text": " Live Demo" }, { "code": null, "e": 2543, "s": 2274, "text": "abstract class MyClass {\n public void display() {\n System.out.println(\"This is a method of abstract class\");\n }\n}\npublic class AbstractClassExample extends MyClass{\n public static void main(String args[]) {\n new AbstractClassExample().display();\n }\n}" }, { "code": null, "e": 2578, "s": 2543, "text": "This is a method of abstract class" } ]
Convert list of string into sorted list of integer in Python
Analysing data using python can bring us scenario when we have to deal with numbers represented as strings. In this article we will take a list which has numbers present as strings and we need to convert then to integers and then represent them in a sorted manner. In this approach we apply the int function to every element of the list using map. Then we apply the sorted function to the list which sorts the numbers. It can handle negative numbers also. Live Demo listA = ['54', '21', '-10', '92', '5'] # Given lists print("Given list : \n", listA) # Use mapp listint = map(int, listA) # Apply sort res = sorted(listint) # Result print("Sorted list of integers: \n",res) Running the above code gives us the following result − Given list : ['54', '21', '-10', '92', '5'] Sorted list of integers: [-10, 5, 21, 54, 92] In this approach we apply the int function by using a for loop and store the result into a list. Then the sort function is applied to the list. The final result shows the sorted list. Live Demo listA = ['54', '21', '-10', '92', '5'] # Given lists print("Given list : \n", listA) # Convert to int res = [int(x) for x in listA] # Apply sort res.sort() # Result print("Sorted list of integers: \n",res) Running the above code gives us the following result − Given list : ['54', '21', '-10', '92', '5'] Sorted list of integers: [-10, 5, 21, 54, 92] This approach is similar to above except that we apply int function through a for loop and enclose the result in the sorted function. It is a single expression which gives us the final result. Live Demo listA = ['54', '21', '-10', '92', '5'] # Given lists print("Given list : \n", listA) # Convert to int res = sorted(int(x) for x in listA) # Result print("Sorted list of integers: \n",res) Running the above code gives us the following result − Given list : ['54', '21', '-10', '92', '5'] Sorted list of integers: [-10, 5, 21, 54, 92]
[ { "code": null, "e": 1327, "s": 1062, "text": "Analysing data using python can bring us scenario when we have to deal with numbers represented as strings. In this article we will take a list which has numbers present as strings and we need to convert then to integers and then represent them in a sorted manner." }, { "code": null, "e": 1518, "s": 1327, "text": "In this approach we apply the int function to every element of the list using map. Then we apply the sorted function to the list which sorts the numbers. It can handle negative numbers also." }, { "code": null, "e": 1529, "s": 1518, "text": " Live Demo" }, { "code": null, "e": 1736, "s": 1529, "text": "listA = ['54', '21', '-10', '92', '5']\n# Given lists\nprint(\"Given list : \\n\", listA)\n# Use mapp\nlistint = map(int, listA)\n# Apply sort\nres = sorted(listint)\n# Result\nprint(\"Sorted list of integers: \\n\",res)" }, { "code": null, "e": 1791, "s": 1736, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 1881, "s": 1791, "text": "Given list :\n['54', '21', '-10', '92', '5']\nSorted list of integers:\n[-10, 5, 21, 54, 92]" }, { "code": null, "e": 2065, "s": 1881, "text": "In this approach we apply the int function by using a for loop and store the result into a list. Then the sort function is applied to the list. The final result shows the sorted list." }, { "code": null, "e": 2076, "s": 2065, "text": " Live Demo" }, { "code": null, "e": 2282, "s": 2076, "text": "listA = ['54', '21', '-10', '92', '5']\n# Given lists\nprint(\"Given list : \\n\", listA)\n# Convert to int\nres = [int(x) for x in listA]\n# Apply sort\nres.sort()\n# Result\nprint(\"Sorted list of integers: \\n\",res)" }, { "code": null, "e": 2337, "s": 2282, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2427, "s": 2337, "text": "Given list :\n['54', '21', '-10', '92', '5']\nSorted list of integers:\n[-10, 5, 21, 54, 92]" }, { "code": null, "e": 2620, "s": 2427, "text": "This approach is similar to above except that we apply int function through a for loop and enclose the result in the sorted function. It is a single expression which gives us the final result." }, { "code": null, "e": 2631, "s": 2620, "text": " Live Demo" }, { "code": null, "e": 2819, "s": 2631, "text": "listA = ['54', '21', '-10', '92', '5']\n# Given lists\nprint(\"Given list : \\n\", listA)\n# Convert to int\nres = sorted(int(x) for x in listA)\n# Result\nprint(\"Sorted list of integers: \\n\",res)" }, { "code": null, "e": 2874, "s": 2819, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2964, "s": 2874, "text": "Given list :\n['54', '21', '-10', '92', '5']\nSorted list of integers:\n[-10, 5, 21, 54, 92]" } ]
Apache Camel - Project
We will use Maven to build a Camel project. Although, we preferable use IntelliJ IDE for development. You may use any IDE of your choice for this project. Create a new Maven project and specify the following − GroupId: Basket ArtifactId: Basket Select the default location for your project or if you prefer specify the directory of your choice. You need to add few dependencies to use Camel. The dependencies are added in pom.xml. So open pom.xml and add following two dependencies − <dependencies> <dependency> <groupId>org.apache.camel</groupId> <artifactId>camel-core</artifactId> <version>2.20.0</version> </dependency> <dependency> <groupId>org.apache.camel</groupId> <artifactId>camel-stream</artifactId> <version>2.20.0</version> </dependency> </dependencies> Note − We need the bare minimum dependencies for our application. As you use more Camel components from its libraries, you will need to add the corresponding dependencies in this pom.xml file. Next, you will write your filtering and routing code in a Java DSL. Create a new Java class called DistributeOrderDSL. Add the following code to it − public class DistributeOrderDSL { public static void main(String[] args) throws Exception { CamelContext context = new DefaultCamelContext(); try { context.addRoutes(new RouteBuilder() { @Override public void configure() throws Exception { from("direct:DistributeOrderDSL") .split(xpath("//order[@product='soaps']/items")).to("stream:out"); // .to("file:src/main/resources/order/"); } }); context.start(); ProducerTemplate orderProducerTemplate = context.createProducerTemplate(); InputStream orderInputStream = new FileInputStream(ClassLoader.getSystemClassLoader() .getResource("order.xml").getFile()); orderProducerTemplate.sendBody("direct:DistributeOrderDSL", orderInputStream); } finally { context.stop(); } } } In the main method, first we create CamelContext by instantiating a default implementation provided in DefaultCamelContext class. CamelContext context = new DefaultCamelContext(); Next, we add a route by creating an anonymous RouteBuilder instance − context.addRoutes(new RouteBuilder() { We override the configure method to add a route from a direct URI DistributeOrderDSL to the system console. We provide some filtering by using the xpath query. public void configure() throws Exception { from("direct:DistributeOrderDSL") .split(xpath("//order[@product = 'soaps']/items")).to("stream:out"); // .to("file:src/main/resources/order/"); } After adding the route, we start the context − context.start(); Next, we add the code for creating our direct URI - DistributeOrderDSL. ProducerTemplate orderProducerTemplate = context.createProducerTemplate(); InputStream orderInputStream = new FileInputStream(ClassLoader.getSystemClassLoader() .getResource("order.xml").getFile()); Finally, we start the processing − orderProducerTemplate.sendBody("direct:DistributeOrderDSL", orderInputStream); Now, as your Java DSL code is completed, the only thing that remains before testing the application is to add the order.xml file to your project. You may use the sample XML shown in the Introduction chapter for this purpose. When you run the application, you would see the following output − <items> <item> <Brand>Cinthol</Brand> <Type>Original</Type> <Quantity>4</Quantity> <Price>25</Price> </item> <item> <Brand>Cinthol</Brand> <Type>Lime</Type> <Quantity>6</Quantity> <Price>30</Price> </item> </items> Note that only orders for Soaps are listed here. If you wish to store this to a local file, just comment the stream.out line and uncomment the following line in your configure method − // .to("file:src/main/resources/order/"); In our subsequent section, we will learn how to use Camel with Spring. 46 Lectures 3.5 hours Arnab Chakraborty 23 Lectures 1.5 hours Mukund Kumar Mishra 16 Lectures 1 hours Nilay Mehta 52 Lectures 1.5 hours Bigdata Engineer 14 Lectures 1 hours Bigdata Engineer 23 Lectures 1 hours Bigdata Engineer Print Add Notes Bookmark this page
[ { "code": null, "e": 2026, "s": 1871, "text": "We will use Maven to build a Camel project. Although, we preferable use IntelliJ IDE for development. You may use any IDE of your choice for this project." }, { "code": null, "e": 2081, "s": 2026, "text": "Create a new Maven project and specify the following −" }, { "code": null, "e": 2117, "s": 2081, "text": "GroupId: Basket\nArtifactId: Basket\n" }, { "code": null, "e": 2217, "s": 2117, "text": "Select the default location for your project or if you prefer specify the directory of your choice." }, { "code": null, "e": 2356, "s": 2217, "text": "You need to add few dependencies to use Camel. The dependencies are added in pom.xml. So open pom.xml and add following two dependencies −" }, { "code": null, "e": 2687, "s": 2356, "text": "<dependencies>\n <dependency>\n <groupId>org.apache.camel</groupId>\n <artifactId>camel-core</artifactId>\n <version>2.20.0</version>\n </dependency>\n <dependency>\n <groupId>org.apache.camel</groupId>\n <artifactId>camel-stream</artifactId>\n <version>2.20.0</version>\n </dependency>\n</dependencies>" }, { "code": null, "e": 2880, "s": 2687, "text": "Note − We need the bare minimum dependencies for our application. As you use more Camel components from its libraries, you will need to add the corresponding dependencies in this pom.xml file." }, { "code": null, "e": 3030, "s": 2880, "text": "Next, you will write your filtering and routing code in a Java DSL. Create a new Java class called DistributeOrderDSL. Add the following code to it −" }, { "code": null, "e": 3953, "s": 3030, "text": "public class DistributeOrderDSL {\n public static void main(String[] args) throws Exception {\n CamelContext context = new DefaultCamelContext();\n try {\n context.addRoutes(new RouteBuilder() {\n @Override\n public void configure() throws Exception {\n from(\"direct:DistributeOrderDSL\")\n .split(xpath(\"//order[@product='soaps']/items\")).to(\"stream:out\");\n \n // .to(\"file:src/main/resources/order/\");\n }\n });\n context.start();\n ProducerTemplate orderProducerTemplate = context.createProducerTemplate();\n InputStream orderInputStream = new FileInputStream(ClassLoader.getSystemClassLoader()\n .getResource(\"order.xml\").getFile());\n orderProducerTemplate.sendBody(\"direct:DistributeOrderDSL\", orderInputStream);\n } finally {\n context.stop();\n }\n }\n}" }, { "code": null, "e": 4083, "s": 3953, "text": "In the main method, first we create CamelContext by instantiating a default implementation provided in DefaultCamelContext class." }, { "code": null, "e": 4134, "s": 4083, "text": "CamelContext context = new DefaultCamelContext();\n" }, { "code": null, "e": 4204, "s": 4134, "text": "Next, we add a route by creating an anonymous RouteBuilder instance −" }, { "code": null, "e": 4244, "s": 4204, "text": "context.addRoutes(new RouteBuilder() {\n" }, { "code": null, "e": 4404, "s": 4244, "text": "We override the configure method to add a route from a direct URI DistributeOrderDSL to the system console. We provide some filtering by using the xpath query." }, { "code": null, "e": 4607, "s": 4404, "text": "public void configure() throws Exception {\n from(\"direct:DistributeOrderDSL\")\n .split(xpath(\"//order[@product = 'soaps']/items\")).to(\"stream:out\");\n // .to(\"file:src/main/resources/order/\");\n}\n" }, { "code": null, "e": 4654, "s": 4607, "text": "After adding the route, we start the context −" }, { "code": null, "e": 4672, "s": 4654, "text": "context.start();\n" }, { "code": null, "e": 4744, "s": 4672, "text": "Next, we add the code for creating our direct URI - DistributeOrderDSL." }, { "code": null, "e": 4947, "s": 4744, "text": "ProducerTemplate orderProducerTemplate = context.createProducerTemplate();\nInputStream orderInputStream = new FileInputStream(ClassLoader.getSystemClassLoader()\n .getResource(\"order.xml\").getFile());\n" }, { "code": null, "e": 4982, "s": 4947, "text": "Finally, we start the processing −" }, { "code": null, "e": 5062, "s": 4982, "text": "orderProducerTemplate.sendBody(\"direct:DistributeOrderDSL\", orderInputStream);\n" }, { "code": null, "e": 5287, "s": 5062, "text": "Now, as your Java DSL code is completed, the only thing that remains before testing the application is to add the order.xml file to your project. You may use the sample XML shown in the Introduction chapter for this purpose." }, { "code": null, "e": 5354, "s": 5287, "text": "When you run the application, you would see the following output −" }, { "code": null, "e": 5629, "s": 5354, "text": "<items>\n <item>\n <Brand>Cinthol</Brand>\n <Type>Original</Type>\n <Quantity>4</Quantity>\n <Price>25</Price>\n </item>\n <item>\n <Brand>Cinthol</Brand>\n <Type>Lime</Type>\n <Quantity>6</Quantity>\n <Price>30</Price>\n </item>\n</items>" }, { "code": null, "e": 5814, "s": 5629, "text": "Note that only orders for Soaps are listed here. If you wish to store this to a local file, just comment the stream.out line and uncomment the following line in your configure method −" }, { "code": null, "e": 5857, "s": 5814, "text": "// .to(\"file:src/main/resources/order/\");\n" }, { "code": null, "e": 5928, "s": 5857, "text": "In our subsequent section, we will learn how to use Camel with Spring." }, { "code": null, "e": 5963, "s": 5928, "text": "\n 46 Lectures \n 3.5 hours \n" }, { "code": null, "e": 5982, "s": 5963, "text": " Arnab Chakraborty" }, { "code": null, "e": 6017, "s": 5982, "text": "\n 23 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6038, "s": 6017, "text": " Mukund Kumar Mishra" }, { "code": null, "e": 6071, "s": 6038, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 6084, "s": 6071, "text": " Nilay Mehta" }, { "code": null, "e": 6119, "s": 6084, "text": "\n 52 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6137, "s": 6119, "text": " Bigdata Engineer" }, { "code": null, "e": 6170, "s": 6137, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 6188, "s": 6170, "text": " Bigdata Engineer" }, { "code": null, "e": 6221, "s": 6188, "text": "\n 23 Lectures \n 1 hours \n" }, { "code": null, "e": 6239, "s": 6221, "text": " Bigdata Engineer" }, { "code": null, "e": 6246, "s": 6239, "text": " Print" }, { "code": null, "e": 6257, "s": 6246, "text": " Add Notes" } ]
Check if a key is present in every segment of size k in an array - GeeksforGeeks
19 Jan, 2022 Given an array arr[] and size of array is n and one another key x, and give you a segment size k. The task is to find that the key x present in every segment of size k in arr[].Examples: Input : arr[] = { 3, 5, 2, 4, 9, 3, 1, 7, 3, 11, 12, 3} x = 3 k = 3 Output : Yes There are 4 non-overlapping segments of size k in the array, {3, 5, 2}, {4, 9, 3}, {1, 7, 3} and {11, 12, 3}. 3 is present all segments.Input : arr[] = { 21, 23, 56, 65, 34, 54, 76, 32, 23, 45, 21, 23, 25} x = 23 k = 5 Output :Yes There are three segments and last segment is not full {21, 23, 56, 65, 34}, {54, 76, 32, 23, 45} and {21, 23, 25}. 23 is present all window.Input :arr[] = { 5, 8, 7, 12, 14, 3, 9} x = 8 k = 2 Output : No The idea is simple, we consider every segment of size k and check if x is present in the window or not. We need to carefully handle the last segment.Below is the implementation of the above approach: C++ Java Python 3 C# PHP Javascript // C++ code to find the every segment size of// array have a search key x#include <bits/stdc++.h>using namespace std; bool findxinkwindowSize(int arr[], int x, int k, int n){ int i; for (i = 0; i < n; i = i + k) { // Search x in segment starting // from index i. int j; for (j = 0; j < k; j++) if (arr[i + j] == x) break; // If loop didn't break if (j == k) return false; } // If n is a multiple of k if (i == n) return true; // Check in last segment if n // is not multiple of k. int j; for (j=i-k; j<n; j++) if (arr[j] == x) break; if (j == n) return false; return true;} // main driverint main(){ int arr[] = { 3, 5, 2, 4, 9, 3, 1, 7, 3, 11, 12, 3 }; int x = 3, k = 3; int n = sizeof(arr) / sizeof(arr[0]); if (findxinkwindowSize(arr, x, k, n)) cout << "Yes" << endl; else cout << "No" << endl; return 0;} // Java code to find the every// segment size of array have// a search key ximport java.util.*;class GFG { static boolean findxinkwindowSize(int N, int[] arr, int x, int k) { int i; boolean b = false; // Iterate from 0 to N - 1 for (i = 0; i < N; i = i + k) { // Iterate from 0 to k - 1 for (int j = 0; j < k; j++) { if (i + j < N && arr[i + j] == x) break; if (j == k) return false; if (i + j >= N) return false; } } if (i >= N) return true; else return b; } // Driver Code public static void main(String args[]) { int arr[] = new int[] { 3, 5, 2, 4, 9, 3, 1, 7, 3, 11, 12, 3 }; int x = 3, k = 3; int n = arr.length; if (findxinkwindowSize(n, arr, x, k)) System.out.println("Yes"); else System.out.println("No"); }} // This code is contributed by Vivek258709 # Python 3 program to find# the every segment size of# array have a search key x def findxinkwindowSize(arr, x, k, n) : i = 0 while i < n : j = 0 # Search x in segment # starting from index i while j < k : if arr[i + j] == x : break j += 1 # If loop didn't break if j == k : return False i += k # If n is a multiple of k if i == n : return True j = i - k # Check in last segment if n # is not multiple of k. while j < n : if arr[j] == x : break j += 1 if j == n : return False return True # Driver Codeif __name__ == "__main__" : arr = [ 3, 5, 2, 4, 9, 3, 1, 7, 3, 11, 12, 3 ] x, k = 3, 3 n = len(arr) if (findxinkwindowSize(arr, x, k, n)) : print("Yes") else : print("No") # This code is contributed# by ANKITRAI1 // C# code to find the every// segment size of array have// a search key xusing System; class GFG{static bool findxinkwindowSize(int[] arr, int x, int k, int n){ int i; for (i = 0; i < n; i = i + k) { // Search x in segment // starting from index i. int j; for (j = 0; j < k; j++) if (arr[i + j] == x) break; // If loop didn't break if (j == k) return false; } // If n is a multiple of k if (i == n) return true; // Check in last segment if // n is not multiple of k. int l; for (l = i - k; l < n; l++) if (arr[l] == x) break; if (l == n) return false; return true;} // Driver Codepublic static void Main(){ int[] arr = new int[] {3, 5, 2, 4, 9, 3, 1, 7, 3, 11, 12, 3}; int x = 3, k = 3; int n = arr.Length; if (findxinkwindowSize(arr, x, k, n)) Console.Write("Yes"); else Console.Write("No");}} // This code is contributed by ChitraNayal <?php// PHP code to find the every// segment size of array have// a search key x function findxinkwindowSize(&$arr, $x, $k, $n){ for ($i = 0; $i < $n; $i = $i + $k) { // Search x in segment // starting from index i. for ($j = 0; $j < $k; $j++) if ($arr[$i + $j] == $x) break; // If loop didn't break if ($j == $k) return false; } // If n is a multiple of k if ($i == $n) return true; // Check in last segment if n // is not multiple of k. for ($j = $i - $k; $j < $n; $j++) if ($arr[$j] == $x) break; if ($j == $n) return false; return true;} // Driver Code$arr = array(3, 5, 2, 4, 9, 3, 1, 7, 3, 11, 12, 3);$x = 3;$k = 3;$n = sizeof($arr);if (findxinkwindowSize($arr, $x, $k, $n)) echo "Yes" ;else echo "No" ; // This code is contributed// by Shivi_Aggarwal?> <script> // JavaScript code to find the every segment size of// array have a search key x function findxinkwindowSize( arr, x, k, n){ let i; for (i = 0; i < n; i = i + k) { // Search x in segment starting // from index i. let j; for (j = 0; j < k; j++) if (arr[i + j] == x) break; // If loop didn't break if (j == k) return false; } // If n is a multiple of k if (i == n) return true; // Check in last segment if n // is not multiple of k. let j; for (j=i-k; j<n; j++) if (arr[j] == x) break; if (j == n) return false; return true;} // main driver let arr = [ 3, 5, 2, 4, 9, 3, 1, 7, 3, 11, 12, 3 ]; let x = 3, k = 3; let n = arr.length; if (findxinkwindowSize(arr, x, k, n)) document.write("Yes"); else document.write("No"); // This code contributed by aashish1995 </script> Yes Time Complexity: O(n) Kirti_Mangal ankthon Shivi_Aggarwal ukasp vivek258709 aashish1995 adnanirshad158 Arrays Searching Arrays Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Trapping Rain Water Program to find sum of elements in a given array Reversal algorithm for array rotation Window Sliding Technique Find duplicates in O(n) time and O(1) extra space | Set 1 Binary Search Median of two sorted arrays of different sizes Most frequent element in an array Find the index of an array element in Java Count number of occurrences (or frequency) in a sorted array
[ { "code": null, "e": 24740, "s": 24712, "text": "\n19 Jan, 2022" }, { "code": null, "e": 24928, "s": 24740, "text": "Given an array arr[] and size of array is n and one another key x, and give you a segment size k. The task is to find that the key x present in every segment of size k in arr[].Examples: " }, { "code": null, "e": 25444, "s": 24928, "text": "Input : arr[] = { 3, 5, 2, 4, 9, 3, 1, 7, 3, 11, 12, 3} x = 3 k = 3 Output : Yes There are 4 non-overlapping segments of size k in the array, {3, 5, 2}, {4, 9, 3}, {1, 7, 3} and {11, 12, 3}. 3 is present all segments.Input : arr[] = { 21, 23, 56, 65, 34, 54, 76, 32, 23, 45, 21, 23, 25} x = 23 k = 5 Output :Yes There are three segments and last segment is not full {21, 23, 56, 65, 34}, {54, 76, 32, 23, 45} and {21, 23, 25}. 23 is present all window.Input :arr[] = { 5, 8, 7, 12, 14, 3, 9} x = 8 k = 2 Output : No" }, { "code": null, "e": 25645, "s": 25444, "text": "The idea is simple, we consider every segment of size k and check if x is present in the window or not. We need to carefully handle the last segment.Below is the implementation of the above approach: " }, { "code": null, "e": 25649, "s": 25645, "text": "C++" }, { "code": null, "e": 25654, "s": 25649, "text": "Java" }, { "code": null, "e": 25663, "s": 25654, "text": "Python 3" }, { "code": null, "e": 25666, "s": 25663, "text": "C#" }, { "code": null, "e": 25670, "s": 25666, "text": "PHP" }, { "code": null, "e": 25681, "s": 25670, "text": "Javascript" }, { "code": "// C++ code to find the every segment size of// array have a search key x#include <bits/stdc++.h>using namespace std; bool findxinkwindowSize(int arr[], int x, int k, int n){ int i; for (i = 0; i < n; i = i + k) { // Search x in segment starting // from index i. int j; for (j = 0; j < k; j++) if (arr[i + j] == x) break; // If loop didn't break if (j == k) return false; } // If n is a multiple of k if (i == n) return true; // Check in last segment if n // is not multiple of k. int j; for (j=i-k; j<n; j++) if (arr[j] == x) break; if (j == n) return false; return true;} // main driverint main(){ int arr[] = { 3, 5, 2, 4, 9, 3, 1, 7, 3, 11, 12, 3 }; int x = 3, k = 3; int n = sizeof(arr) / sizeof(arr[0]); if (findxinkwindowSize(arr, x, k, n)) cout << \"Yes\" << endl; else cout << \"No\" << endl; return 0;}", "e": 26671, "s": 25681, "text": null }, { "code": "// Java code to find the every// segment size of array have// a search key ximport java.util.*;class GFG { static boolean findxinkwindowSize(int N, int[] arr, int x, int k) { int i; boolean b = false; // Iterate from 0 to N - 1 for (i = 0; i < N; i = i + k) { // Iterate from 0 to k - 1 for (int j = 0; j < k; j++) { if (i + j < N && arr[i + j] == x) break; if (j == k) return false; if (i + j >= N) return false; } } if (i >= N) return true; else return b; } // Driver Code public static void main(String args[]) { int arr[] = new int[] { 3, 5, 2, 4, 9, 3, 1, 7, 3, 11, 12, 3 }; int x = 3, k = 3; int n = arr.length; if (findxinkwindowSize(n, arr, x, k)) System.out.println(\"Yes\"); else System.out.println(\"No\"); }} // This code is contributed by Vivek258709", "e": 27804, "s": 26671, "text": null }, { "code": "# Python 3 program to find# the every segment size of# array have a search key x def findxinkwindowSize(arr, x, k, n) : i = 0 while i < n : j = 0 # Search x in segment # starting from index i while j < k : if arr[i + j] == x : break j += 1 # If loop didn't break if j == k : return False i += k # If n is a multiple of k if i == n : return True j = i - k # Check in last segment if n # is not multiple of k. while j < n : if arr[j] == x : break j += 1 if j == n : return False return True # Driver Codeif __name__ == \"__main__\" : arr = [ 3, 5, 2, 4, 9, 3, 1, 7, 3, 11, 12, 3 ] x, k = 3, 3 n = len(arr) if (findxinkwindowSize(arr, x, k, n)) : print(\"Yes\") else : print(\"No\") # This code is contributed# by ANKITRAI1", "e": 28800, "s": 27804, "text": null }, { "code": "// C# code to find the every// segment size of array have// a search key xusing System; class GFG{static bool findxinkwindowSize(int[] arr, int x, int k, int n){ int i; for (i = 0; i < n; i = i + k) { // Search x in segment // starting from index i. int j; for (j = 0; j < k; j++) if (arr[i + j] == x) break; // If loop didn't break if (j == k) return false; } // If n is a multiple of k if (i == n) return true; // Check in last segment if // n is not multiple of k. int l; for (l = i - k; l < n; l++) if (arr[l] == x) break; if (l == n) return false; return true;} // Driver Codepublic static void Main(){ int[] arr = new int[] {3, 5, 2, 4, 9, 3, 1, 7, 3, 11, 12, 3}; int x = 3, k = 3; int n = arr.Length; if (findxinkwindowSize(arr, x, k, n)) Console.Write(\"Yes\"); else Console.Write(\"No\");}} // This code is contributed by ChitraNayal", "e": 29857, "s": 28800, "text": null }, { "code": "<?php// PHP code to find the every// segment size of array have// a search key x function findxinkwindowSize(&$arr, $x, $k, $n){ for ($i = 0; $i < $n; $i = $i + $k) { // Search x in segment // starting from index i. for ($j = 0; $j < $k; $j++) if ($arr[$i + $j] == $x) break; // If loop didn't break if ($j == $k) return false; } // If n is a multiple of k if ($i == $n) return true; // Check in last segment if n // is not multiple of k. for ($j = $i - $k; $j < $n; $j++) if ($arr[$j] == $x) break; if ($j == $n) return false; return true;} // Driver Code$arr = array(3, 5, 2, 4, 9, 3, 1, 7, 3, 11, 12, 3);$x = 3;$k = 3;$n = sizeof($arr);if (findxinkwindowSize($arr, $x, $k, $n)) echo \"Yes\" ;else echo \"No\" ; // This code is contributed// by Shivi_Aggarwal?>", "e": 30793, "s": 29857, "text": null }, { "code": "<script> // JavaScript code to find the every segment size of// array have a search key x function findxinkwindowSize( arr, x, k, n){ let i; for (i = 0; i < n; i = i + k) { // Search x in segment starting // from index i. let j; for (j = 0; j < k; j++) if (arr[i + j] == x) break; // If loop didn't break if (j == k) return false; } // If n is a multiple of k if (i == n) return true; // Check in last segment if n // is not multiple of k. let j; for (j=i-k; j<n; j++) if (arr[j] == x) break; if (j == n) return false; return true;} // main driver let arr = [ 3, 5, 2, 4, 9, 3, 1, 7, 3, 11, 12, 3 ]; let x = 3, k = 3; let n = arr.length; if (findxinkwindowSize(arr, x, k, n)) document.write(\"Yes\"); else document.write(\"No\"); // This code contributed by aashish1995 </script>", "e": 31756, "s": 30793, "text": null }, { "code": null, "e": 31760, "s": 31756, "text": "Yes" }, { "code": null, "e": 31784, "s": 31762, "text": "Time Complexity: O(n)" }, { "code": null, "e": 31797, "s": 31784, "text": "Kirti_Mangal" }, { "code": null, "e": 31805, "s": 31797, "text": "ankthon" }, { "code": null, "e": 31820, "s": 31805, "text": "Shivi_Aggarwal" }, { "code": null, "e": 31826, "s": 31820, "text": "ukasp" }, { "code": null, "e": 31838, "s": 31826, "text": "vivek258709" }, { "code": null, "e": 31850, "s": 31838, "text": "aashish1995" }, { "code": null, "e": 31865, "s": 31850, "text": "adnanirshad158" }, { "code": null, "e": 31872, "s": 31865, "text": "Arrays" }, { "code": null, "e": 31882, "s": 31872, "text": "Searching" }, { "code": null, "e": 31889, "s": 31882, "text": "Arrays" }, { "code": null, "e": 31899, "s": 31889, "text": "Searching" }, { "code": null, "e": 31997, "s": 31899, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32006, "s": 31997, "text": "Comments" }, { "code": null, "e": 32019, "s": 32006, "text": "Old Comments" }, { "code": null, "e": 32039, "s": 32019, "text": "Trapping Rain Water" }, { "code": null, "e": 32088, "s": 32039, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 32126, "s": 32088, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 32151, "s": 32126, "text": "Window Sliding Technique" }, { "code": null, "e": 32209, "s": 32151, "text": "Find duplicates in O(n) time and O(1) extra space | Set 1" }, { "code": null, "e": 32223, "s": 32209, "text": "Binary Search" }, { "code": null, "e": 32270, "s": 32223, "text": "Median of two sorted arrays of different sizes" }, { "code": null, "e": 32304, "s": 32270, "text": "Most frequent element in an array" }, { "code": null, "e": 32347, "s": 32304, "text": "Find the index of an array element in Java" } ]
How to get the first day of the previous month in MySQL?
With the help of following MySQL query, we can get the first day of previous month − mysql> SELECT DATE_FORMAT(CURDATE() - INTERVAL 1 MONTH,'%Y-%m-01') AS 'FIRST DAY OF PREVOIUS MONTH'; +-----------------------------+ | FIRST DAY OF PREVOIUS MONTH | +-----------------------------+ | 2017-09-01 | +-----------------------------+ 1 row in set (0.00 sec)
[ { "code": null, "e": 1147, "s": 1062, "text": "With the help of following MySQL query, we can get the first day of previous month −" }, { "code": null, "e": 1432, "s": 1147, "text": "mysql> SELECT DATE_FORMAT(CURDATE() - INTERVAL 1 MONTH,'%Y-%m-01') AS 'FIRST DAY OF PREVOIUS MONTH';\n+-----------------------------+\n| FIRST DAY OF PREVOIUS MONTH |\n+-----------------------------+\n| 2017-09-01 |\n+-----------------------------+\n1 row in set (0.00 sec)" } ]
Python DateTime - DateTime Class - GeeksforGeeks
19 Aug, 2021 DateTime class of the DateTime module as the name suggests contains information on both date as well as time. Like a date object, DateTime assumes the current Gregorian calendar extended in both directions; like a time object, DateTime assumes there are exactly 3600*24 seconds in every day. But unlike date class, the objects of DateTime class are potentially aware objects i.e. it contains information regarding time zone as well. Syntax: class datetime.datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0) The year, month, and day arguments are mandatory. tzinfo can be None, rest all the attributes must be an integer in the following range – MINYEAR(1) <= year <= MAXYEAR(9999) 1 <= month <= 12 1 <= day <= number of days in the given month and year 0 <= hour < 24 0 <= minute < 60 0 <= second < 60 0 <= microsecond < 1000000 fold in [0, 1] Note: Passing an argument other than integer will raise a TypeError and passing arguments outside the range will raise ValueError. Example: Creating an instance of DateTime class Python3 # Python program to# demonstrate datetime object from datetime import datetime # Initializing constructora = datetime(2022, 10, 22)print(a) # Initializing constructor# with time parameters as wella = datetime(2022, 10, 22, 6, 2, 32, 5456)print(a) 2022-10-22 00:00:00 2022-10-22 06:02:32.005456 Let’s see the attributes provided by this class – Example 1: Getting the minimum and maximum representable DateTime object Python3 from datetime import datetime # Getting min datetimemindatetime = datetime.minprint("Min DateTime supported", mindatetime) # Getting max datetimemaxdatetime = datetime.maxprint("Max DateTime supported", maxdatetime) Min DateTime supported 0001-01-01 00:00:00 Max DateTime supported 9999-12-31 23:59:59.999999 Example 2: Accessing the attributes of date and time object Python3 from datetime import datetime # Getting Today's Datetimetoday = datetime.now() # Accessing Attributesprint("Day: ", today.day)print("Month: ", today.month)print("Year: ", today.year)print("Hour: ", today.hour)print("Minute: ", today.minute)print("Second: ", today.second) Day: 26 Month: 7 Year: 2021 Hour: 16 Minute: 24 Second: 7 The DateTime class provides various functions to deal with the DateTime objects like we can convert DateTime object to string and string to DateTime objects, we can also get the weekday for the particular day of the week of the particular month, we can also set the time zone for a particular DateTime object, etc. Example 1: Getting Today’s Date Python3 from datetime import datetime # Getting Today's Datetimetoday = datetime.now()print("Today's date using now() method:", today) today = datetime.today()print("Today's date using today() method:", today) Output Today’s date using now() method: 2021-07-26 22:23:22.725573 Today’s date using today() method: 2021-07-26 22:23:22.725764 Example 2: Getting DateTime from timestamp and ordinal Python3 from datetime import datetime # Getting Datetime from timestampdate_time = datetime.fromtimestamp(1887639468)print("Datetime from timestamp:", date_time) # Getting Datetime from ordinaldate_time = datetime.fromordinal(737994)print("Datetime from ordinal:", date_time) Datetime from timestamp: 2029-10-25 16:17:48 Datetime from ordinal: 2021-07-23 00:00:00 Note: For more information on Python Datetime, refer to Python Datetime Tutorial Python-datetime 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 Selecting rows in pandas DataFrame based on conditions How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | os.path.join() method Python | Get unique values from a list Defaultdict in Python Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24292, "s": 24264, "text": "\n19 Aug, 2021" }, { "code": null, "e": 24725, "s": 24292, "text": "DateTime class of the DateTime module as the name suggests contains information on both date as well as time. Like a date object, DateTime assumes the current Gregorian calendar extended in both directions; like a time object, DateTime assumes there are exactly 3600*24 seconds in every day. But unlike date class, the objects of DateTime class are potentially aware objects i.e. it contains information regarding time zone as well." }, { "code": null, "e": 24733, "s": 24725, "text": "Syntax:" }, { "code": null, "e": 24842, "s": 24733, "text": "class datetime.datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)" }, { "code": null, "e": 24982, "s": 24842, "text": "The year, month, and day arguments are mandatory. tzinfo can be None, rest all the attributes must be an integer in the following range – " }, { "code": null, "e": 25018, "s": 24982, "text": "MINYEAR(1) <= year <= MAXYEAR(9999)" }, { "code": null, "e": 25035, "s": 25018, "text": "1 <= month <= 12" }, { "code": null, "e": 25090, "s": 25035, "text": "1 <= day <= number of days in the given month and year" }, { "code": null, "e": 25105, "s": 25090, "text": "0 <= hour < 24" }, { "code": null, "e": 25122, "s": 25105, "text": "0 <= minute < 60" }, { "code": null, "e": 25139, "s": 25122, "text": "0 <= second < 60" }, { "code": null, "e": 25166, "s": 25139, "text": "0 <= microsecond < 1000000" }, { "code": null, "e": 25181, "s": 25166, "text": "fold in [0, 1]" }, { "code": null, "e": 25312, "s": 25181, "text": "Note: Passing an argument other than integer will raise a TypeError and passing arguments outside the range will raise ValueError." }, { "code": null, "e": 25360, "s": 25312, "text": "Example: Creating an instance of DateTime class" }, { "code": null, "e": 25368, "s": 25360, "text": "Python3" }, { "code": "# Python program to# demonstrate datetime object from datetime import datetime # Initializing constructora = datetime(2022, 10, 22)print(a) # Initializing constructor# with time parameters as wella = datetime(2022, 10, 22, 6, 2, 32, 5456)print(a)", "e": 25618, "s": 25368, "text": null }, { "code": null, "e": 25665, "s": 25618, "text": "2022-10-22 00:00:00\n2022-10-22 06:02:32.005456" }, { "code": null, "e": 25716, "s": 25665, "text": "Let’s see the attributes provided by this class – " }, { "code": null, "e": 25789, "s": 25716, "text": "Example 1: Getting the minimum and maximum representable DateTime object" }, { "code": null, "e": 25797, "s": 25789, "text": "Python3" }, { "code": "from datetime import datetime # Getting min datetimemindatetime = datetime.minprint(\"Min DateTime supported\", mindatetime) # Getting max datetimemaxdatetime = datetime.maxprint(\"Max DateTime supported\", maxdatetime)", "e": 26015, "s": 25797, "text": null }, { "code": null, "e": 26108, "s": 26015, "text": "Min DateTime supported 0001-01-01 00:00:00\nMax DateTime supported 9999-12-31 23:59:59.999999" }, { "code": null, "e": 26168, "s": 26108, "text": "Example 2: Accessing the attributes of date and time object" }, { "code": null, "e": 26176, "s": 26168, "text": "Python3" }, { "code": "from datetime import datetime # Getting Today's Datetimetoday = datetime.now() # Accessing Attributesprint(\"Day: \", today.day)print(\"Month: \", today.month)print(\"Year: \", today.year)print(\"Hour: \", today.hour)print(\"Minute: \", today.minute)print(\"Second: \", today.second)", "e": 26450, "s": 26176, "text": null }, { "code": null, "e": 26514, "s": 26450, "text": "Day: 26\nMonth: 7\nYear: 2021\nHour: 16\nMinute: 24\nSecond: 7" }, { "code": null, "e": 26829, "s": 26514, "text": "The DateTime class provides various functions to deal with the DateTime objects like we can convert DateTime object to string and string to DateTime objects, we can also get the weekday for the particular day of the week of the particular month, we can also set the time zone for a particular DateTime object, etc." }, { "code": null, "e": 26861, "s": 26829, "text": "Example 1: Getting Today’s Date" }, { "code": null, "e": 26869, "s": 26861, "text": "Python3" }, { "code": "from datetime import datetime # Getting Today's Datetimetoday = datetime.now()print(\"Today's date using now() method:\", today) today = datetime.today()print(\"Today's date using today() method:\", today)", "e": 27073, "s": 26869, "text": null }, { "code": null, "e": 27080, "s": 27073, "text": "Output" }, { "code": null, "e": 27140, "s": 27080, "text": "Today’s date using now() method: 2021-07-26 22:23:22.725573" }, { "code": null, "e": 27202, "s": 27140, "text": "Today’s date using today() method: 2021-07-26 22:23:22.725764" }, { "code": null, "e": 27257, "s": 27202, "text": "Example 2: Getting DateTime from timestamp and ordinal" }, { "code": null, "e": 27265, "s": 27257, "text": "Python3" }, { "code": "from datetime import datetime # Getting Datetime from timestampdate_time = datetime.fromtimestamp(1887639468)print(\"Datetime from timestamp:\", date_time) # Getting Datetime from ordinaldate_time = datetime.fromordinal(737994)print(\"Datetime from ordinal:\", date_time)", "e": 27535, "s": 27265, "text": null }, { "code": null, "e": 27623, "s": 27535, "text": "Datetime from timestamp: 2029-10-25 16:17:48\nDatetime from ordinal: 2021-07-23 00:00:00" }, { "code": null, "e": 27704, "s": 27623, "text": "Note: For more information on Python Datetime, refer to Python Datetime Tutorial" }, { "code": null, "e": 27720, "s": 27704, "text": "Python-datetime" }, { "code": null, "e": 27727, "s": 27720, "text": "Python" }, { "code": null, "e": 27825, "s": 27727, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27834, "s": 27825, "text": "Comments" }, { "code": null, "e": 27847, "s": 27834, "text": "Old Comments" }, { "code": null, "e": 27879, "s": 27847, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27935, "s": 27879, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27990, "s": 27935, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 28032, "s": 27990, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28074, "s": 28032, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28105, "s": 28074, "text": "Python | os.path.join() method" }, { "code": null, "e": 28144, "s": 28105, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28166, "s": 28144, "text": "Defaultdict in Python" }, { "code": null, "e": 28195, "s": 28166, "text": "Create a directory in Python" } ]
Sentiment Analysis in R — Good vs Not Good — handling Negations | by AbdulMajedRaja RS | Towards Data Science
Sentiment Analysis is one of the most obvious things Data Analysts with unlabelled Text data (with no score or no rating) end up doing in an attempt to extract some insights out of it and the same Sentiment analysis is also one of the potential research areas for any NLP (Natural Language Processing) enthusiasts. For an analyst, the same sentiment analysis is a pain in the neck because most of the primitive packages/libraries handling sentiment analysis perform a simple dictionary lookup and calculate a final composite score based on the number of occurrences of positive and negative words. But that often ends up in a lot of false positives, with a very obvious case being ‘good’ vs ‘not good’ — Negations, in general Valence Shifters. Consider this sentence: ‘I am not very good’. Any Primitive Sentiment Analysis Algorithm would just flag this sentence positive because of the word ‘good’ that apparently would appear in the positive dictionary. But reading this sentence we know this is not a positive sentence. While we could build our own way to handle these negations, there are couple of new R-packages that could do this with ease. One such package is sentimentrdeveloped by Tyler Rinker. sentimentr can be installed from CRAN or the development version can be installed from github. install.packages('sentimentr')#orlibrary(devtools)install_github('trinker/sentimentr') The author of the package himself explaining what does sentimentr do that other packages don’t and why does it matter? “sentimentr attempts to take into account valence shifters (i.e., negators, amplifiers (intensifiers), de-amplifiers (downtoners), and adversative conjunctions) while maintaining speed. Simply put, sentimentr is an augmented dictionary lookup. The next questions address why it matters.” sentimentr offers sentiment analysis with two functions: 1. sentiment_by() 2. sentiment() Aggregated (Averaged) Sentiment Score for a given text with sentiment_by sentiment_by('I am not very good', by = NULL)element_id sentence_id word_count sentiment1: 1 1 5 -0.06708204 But this might not help much when we have multiple sentences with different polarity, hence sentence-level scoring with sentiment would help here. sentiment('I am not very good. He is very good')element_id sentence_id word_count sentiment1: 1 1 5 -0.067082042: 1 2 4 0.67500000 Both the functions return a dataframe with four columns: 1. element_id – ID / Serial Number of the given text2. sentence_id – ID / Serial Number of the sentence and this is equal to element_id in case of sentiment_by3. word_count – Number of words in the given sentence4. sentiment – Sentiment Score of the given sentence The extract_sentiment_terms() function helps us extract the keywords – both positive and negative that was part of the sentiment score calculation. sentimentr also supports pipe operator %>% which makes it easier to write multiple lines of code with less assignment and also cleaner code. 'My life has become terrible since I met you and lost money' %>% extract_sentiment_terms() element_id sentence_id negative positive1: 1 1 terrible,lost money And finally, the highight() function coupled with sentiment_by() that gives a html output with parts of sentences nicely highlighted with green and red color to show its polarity. Trust me, This might seem trivial but it really helps while making Presentations to share the results, discuss False positives and to identify the room for improvements in the accuracy. 'My life has become terrible since I met you and lost money. But I still have got a little hope left in me' %>% sentiment_by(by = NULL) %>% highlight() Output Screenshot: Try using sentimentr for your sentiment analysis and text analytics project and do share your feedback in comments. Complete code used here is available on my github. For more info, check out this datacamp course — Sentiment Analysis in R — The Tidy Way
[ { "code": null, "e": 487, "s": 172, "text": "Sentiment Analysis is one of the most obvious things Data Analysts with unlabelled Text data (with no score or no rating) end up doing in an attempt to extract some insights out of it and the same Sentiment analysis is also one of the potential research areas for any NLP (Natural Language Processing) enthusiasts." }, { "code": null, "e": 916, "s": 487, "text": "For an analyst, the same sentiment analysis is a pain in the neck because most of the primitive packages/libraries handling sentiment analysis perform a simple dictionary lookup and calculate a final composite score based on the number of occurrences of positive and negative words. But that often ends up in a lot of false positives, with a very obvious case being ‘good’ vs ‘not good’ — Negations, in general Valence Shifters." }, { "code": null, "e": 1195, "s": 916, "text": "Consider this sentence: ‘I am not very good’. Any Primitive Sentiment Analysis Algorithm would just flag this sentence positive because of the word ‘good’ that apparently would appear in the positive dictionary. But reading this sentence we know this is not a positive sentence." }, { "code": null, "e": 1377, "s": 1195, "text": "While we could build our own way to handle these negations, there are couple of new R-packages that could do this with ease. One such package is sentimentrdeveloped by Tyler Rinker." }, { "code": null, "e": 1472, "s": 1377, "text": "sentimentr can be installed from CRAN or the development version can be installed from github." }, { "code": null, "e": 1559, "s": 1472, "text": "install.packages('sentimentr')#orlibrary(devtools)install_github('trinker/sentimentr')" }, { "code": null, "e": 1678, "s": 1559, "text": "The author of the package himself explaining what does sentimentr do that other packages don’t and why does it matter?" }, { "code": null, "e": 1966, "s": 1678, "text": "“sentimentr attempts to take into account valence shifters (i.e., negators, amplifiers (intensifiers), de-amplifiers (downtoners), and adversative conjunctions) while maintaining speed. Simply put, sentimentr is an augmented dictionary lookup. The next questions address why it matters.”" }, { "code": null, "e": 2056, "s": 1966, "text": "sentimentr offers sentiment analysis with two functions: 1. sentiment_by() 2. sentiment()" }, { "code": null, "e": 2129, "s": 2056, "text": "Aggregated (Averaged) Sentiment Score for a given text with sentiment_by" }, { "code": null, "e": 2268, "s": 2129, "text": "sentiment_by('I am not very good', by = NULL)element_id sentence_id word_count sentiment1: 1 1 5 -0.06708204" }, { "code": null, "e": 2415, "s": 2268, "text": "But this might not help much when we have multiple sentences with different polarity, hence sentence-level scoring with sentiment would help here." }, { "code": null, "e": 2605, "s": 2415, "text": "sentiment('I am not very good. He is very good')element_id sentence_id word_count sentiment1: 1 1 5 -0.067082042: 1 2 4 0.67500000" }, { "code": null, "e": 2662, "s": 2605, "text": "Both the functions return a dataframe with four columns:" }, { "code": null, "e": 2927, "s": 2662, "text": "1. element_id – ID / Serial Number of the given text2. sentence_id – ID / Serial Number of the sentence and this is equal to element_id in case of sentiment_by3. word_count – Number of words in the given sentence4. sentiment – Sentiment Score of the given sentence" }, { "code": null, "e": 3216, "s": 2927, "text": "The extract_sentiment_terms() function helps us extract the keywords – both positive and negative that was part of the sentiment score calculation. sentimentr also supports pipe operator %>% which makes it easier to write multiple lines of code with less assignment and also cleaner code." }, { "code": null, "e": 3403, "s": 3216, "text": "'My life has become terrible since I met you and lost money' %>% extract_sentiment_terms() element_id sentence_id negative positive1: 1 1 terrible,lost money" }, { "code": null, "e": 3769, "s": 3403, "text": "And finally, the highight() function coupled with sentiment_by() that gives a html output with parts of sentences nicely highlighted with green and red color to show its polarity. Trust me, This might seem trivial but it really helps while making Presentations to share the results, discuss False positives and to identify the room for improvements in the accuracy." }, { "code": null, "e": 3924, "s": 3769, "text": "'My life has become terrible since I met you and lost money. But I still have got a little hope left in me' %>% sentiment_by(by = NULL) %>% highlight()" }, { "code": null, "e": 3943, "s": 3924, "text": "Output Screenshot:" } ]
IntStream sum() in Java - GeeksforGeeks
06 Dec, 2018 IntStream sum() returns the sum of elements in this stream. This is a special case of a reduction. IntStream sum() is a terminal operation i.e, it may traverse the stream to produce a result or a side-effect. Note : A reduction operation (also called a fold) takes a sequence of input elements and combines them into a single summary result by repeated application of a combining operation, such as finding the sum or maximum of a set of numbers. Syntax : int sum() Return Value : The function returns the sum of elements in this stream. Example 1 : // Java code for IntStream.sum() to// find the sum of elements in IntStreamimport java.util.*;import java.util.stream.IntStream; class GFG { // Driver code public static void main(String[] args) { // Creating an IntStream IntStream stream = IntStream.of(2, 4, 6, -2, -4); // Using IntStream.sum() to find // sum of elements in IntStream int sumOfElements = stream.sum(); // Displaying the calculated sum System.out.println(sumOfElements); }} 6 Example 2 : // Java code for IntStream.sum() to// find the sum of elements// divisible by 3 in given rangeimport java.util.*;import java.util.stream.IntStream; class GFG { // Driver code public static void main(String[] args) { // Using IntStream.sum() to find // sum of elements dividible by 3 // in given range int sumOfElements = IntStream.range(2, 10) .filter(num -> num % 3 == 0) .sum(); // Displaying the calculated sum System.out.println(sumOfElements); }} 18 Java - util package Java-Functions java-intstream java-stream Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments HashMap in Java with Examples Object Oriented Programming (OOPs) Concept in Java Initialize an ArrayList in Java Interfaces in Java ArrayList in Java How to iterate any Map in Java Multidimensional Arrays in Java Multithreading in Java Singleton Class in Java LinkedList in Java
[ { "code": null, "e": 24106, "s": 24078, "text": "\n06 Dec, 2018" }, { "code": null, "e": 24315, "s": 24106, "text": "IntStream sum() returns the sum of elements in this stream. This is a special case of a reduction. IntStream sum() is a terminal operation i.e, it may traverse the stream to produce a result or a side-effect." }, { "code": null, "e": 24553, "s": 24315, "text": "Note : A reduction operation (also called a fold) takes a sequence of input elements and combines them into a single summary result by repeated application of a combining operation, such as finding the sum or maximum of a set of numbers." }, { "code": null, "e": 24562, "s": 24553, "text": "Syntax :" }, { "code": null, "e": 24573, "s": 24562, "text": "int sum()\n" }, { "code": null, "e": 24645, "s": 24573, "text": "Return Value : The function returns the sum of elements in this stream." }, { "code": null, "e": 24657, "s": 24645, "text": "Example 1 :" }, { "code": "// Java code for IntStream.sum() to// find the sum of elements in IntStreamimport java.util.*;import java.util.stream.IntStream; class GFG { // Driver code public static void main(String[] args) { // Creating an IntStream IntStream stream = IntStream.of(2, 4, 6, -2, -4); // Using IntStream.sum() to find // sum of elements in IntStream int sumOfElements = stream.sum(); // Displaying the calculated sum System.out.println(sumOfElements); }}", "e": 25167, "s": 24657, "text": null }, { "code": null, "e": 25170, "s": 25167, "text": "6\n" }, { "code": null, "e": 25182, "s": 25170, "text": "Example 2 :" }, { "code": "// Java code for IntStream.sum() to// find the sum of elements// divisible by 3 in given rangeimport java.util.*;import java.util.stream.IntStream; class GFG { // Driver code public static void main(String[] args) { // Using IntStream.sum() to find // sum of elements dividible by 3 // in given range int sumOfElements = IntStream.range(2, 10) .filter(num -> num % 3 == 0) .sum(); // Displaying the calculated sum System.out.println(sumOfElements); }}", "e": 25745, "s": 25182, "text": null }, { "code": null, "e": 25749, "s": 25745, "text": "18\n" }, { "code": null, "e": 25769, "s": 25749, "text": "Java - util package" }, { "code": null, "e": 25784, "s": 25769, "text": "Java-Functions" }, { "code": null, "e": 25799, "s": 25784, "text": "java-intstream" }, { "code": null, "e": 25811, "s": 25799, "text": "java-stream" }, { "code": null, "e": 25816, "s": 25811, "text": "Java" }, { "code": null, "e": 25821, "s": 25816, "text": "Java" }, { "code": null, "e": 25919, "s": 25821, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25928, "s": 25919, "text": "Comments" }, { "code": null, "e": 25941, "s": 25928, "text": "Old Comments" }, { "code": null, "e": 25971, "s": 25941, "text": "HashMap in Java with Examples" }, { "code": null, "e": 26022, "s": 25971, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 26054, "s": 26022, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 26073, "s": 26054, "text": "Interfaces in Java" }, { "code": null, "e": 26091, "s": 26073, "text": "ArrayList in Java" }, { "code": null, "e": 26122, "s": 26091, "text": "How to iterate any Map in Java" }, { "code": null, "e": 26154, "s": 26122, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 26177, "s": 26154, "text": "Multithreading in Java" }, { "code": null, "e": 26201, "s": 26177, "text": "Singleton Class in Java" } ]
How to customize the position of an alert box using JavaScript?
To customize the position of an alert box, use the CSS “top” and “left” properties. We have a custom alert box, which we’ve created using jQuery and styled with CSS. You can try to run the following code to customize the position of an alert box − Live Demo <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> function functionAlert(msg, myYes) { var confirmBox = $("#confirm"); confirmBox.find(".message").text(msg); confirmBox.find(".yes").unbind().click(function() { confirmBox.hide(); }); confirmBox.find(".yes").click(myYes); confirmBox.show(); } </script> <style> #confirm { display: none; background-color: #F3F5F6; color: #000000; border: 1px solid #aaa; position: fixed; width: 300px; height: 100px; left: 30%; top: 30%; box-sizing: border-box; text-align: center; } #confirm button { background-color: #FFFFFF; display: inline-block; border-radius: 12px; border: 4px solid #aaa; padding: 5px; text-align: center; width: 60px; cursor: pointer; } #confirm .message { text-align: left; } </style> </head> <body> <div id="confirm"> <div class="message">This is a warning message.</div><br> <button class="yes">OK</button> </div> <input type="button" value="Click Me" onclick="functionAlert();" /> </body> </html>
[ { "code": null, "e": 1228, "s": 1062, "text": "To customize the position of an alert box, use the CSS “top” and “left” properties. We have a custom alert box, which we’ve created using jQuery and styled with CSS." }, { "code": null, "e": 1310, "s": 1228, "text": "You can try to run the following code to customize the position of an alert box −" }, { "code": null, "e": 1320, "s": 1310, "text": "Live Demo" }, { "code": null, "e": 2834, "s": 1320, "text": "<!DOCTYPE html>\n<html>\n <head>\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\"></script>\n <script>\n function functionAlert(msg, myYes) {\n var confirmBox = $(\"#confirm\");\n confirmBox.find(\".message\").text(msg);\n confirmBox.find(\".yes\").unbind().click(function() {\n confirmBox.hide();\n });\n confirmBox.find(\".yes\").click(myYes);\n confirmBox.show();\n }\n </script>\n <style>\n #confirm {\n display: none;\n background-color: #F3F5F6;\n color: #000000;\n border: 1px solid #aaa;\n position: fixed;\n width: 300px;\n height: 100px;\n left: 30%;\n top: 30%;\n box-sizing: border-box;\n text-align: center;\n }\n #confirm button {\n background-color: #FFFFFF;\n display: inline-block;\n border-radius: 12px;\n border: 4px solid #aaa;\n padding: 5px;\n text-align: center;\n width: 60px;\n cursor: pointer;\n }\n #confirm .message {\n text-align: left;\n }\n </style>\n </head>\n <body>\n <div id=\"confirm\">\n <div class=\"message\">This is a warning message.</div><br>\n <button class=\"yes\">OK</button>\n </div>\n <input type=\"button\" value=\"Click Me\" onclick=\"functionAlert();\" />\n </body>\n</html>" } ]
File globbing in Linux - GeeksforGeeks
30 Jan, 2021 Before we move to file globbing, let’s understand what are wildcard patterns, these are the patterns containing strings like ‘?’, ‘*’ File globbing is the operation that recognizes these patterns and does the job of file path expansion. See the below example for clear understanding, path expansion for ‘*’ If you observe the image above, I created several directories whose starting characters are HELLO and hello, and then tried to delete these directories. When I used rm -rf hello*, it deleted the directories hello1, hello2, hello3, the ‘*’ symbol used after ‘hello’ recognizes the first characters as ‘hello’ and then zero or more occurrences of any other characters. Examples using other wildcard characters : 1) asterisk (*) * is used to match any number of characters(zero or more), to understand more you can refer to the example taken above. 2) question mark(?) ? is used to match exactly one character. In the above image, you can observe that ‘?’ can match exactly one character and is used at the end of the line. So using ‘hello?’ will match all files or directories whose starting characters are ‘hello’ and it will recognize one more character. 3) Square Brackets [] Square brackets are used to match the characters inside [], refer below image, [] can be used to match exact characters or you can also specify a range, like in the above example, using ‘hello[1-5]’ will display all files and directories starting with ‘hello’, then the next character can be a number from 1 to 5. 4) exclamation mark (!) ! is used to exclude characters from the list that is specified within the square brackets. For example: ls hello[!3] It will display the directories starting with hello, ending with any character but not 3 5) Named character classes ([[:named:]]) It is used to print named values. Their interpretation depends on the LC_CTYPE locale; Some of them are listed below. ‘[:alnum:]’ : Prints all those files having alphabets and digits. Both lower and uppercases are considered. ‘[:alpha:]’ : Prints all those files having alphabets only. Both lower and uppercases are considered. ‘[:digit:]’ : Prints all those files having digits. ‘[:lower:]’: Prints all those files having lower-case letters. ‘[:punct:]’ : Prints all those files having punctuation characters. Will search for ! ” # $ % & ‘ ( ) * + , – . / : ; < = > ? @ [ \ ] ^ _ ` { | } ~. ‘[:space:]’: Prints all those files having space characters. ‘[:upper:]’: Prints all those files having lower-case letters. Note: They can be used with asterisk (*) ,question mark(?) or square brackets([]) to generate useful outputs. For example: ls [[:alpha:]]* : Will display the directories starting with a alphabet (either in lower or uppercase) and ending with any characters. ls *[[:alnum:]]*.* : Will display the files (of any type) containing a alphabet or a digit but may start or end with any length of characters. ls *[[:digit:]] : Will display the directories which may start with any length of characters but ending with a digit. ls ?[[:lower:]] : Will display the directories starting with exactly one character and ending with a lowercase character. ls *[[:upper:]]* : Will display the directories containing a alphabet or digit which may start or end with any length of characters. Note: Any combinations of *, ? Can be used with any named class. yashbeersingh42 Articles Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Const keyword in C++ What's the difference between Scripting and Programming Languages? Service-Oriented Architecture Amazon’s most frequently asked interview questions | Set 2 Must Do Questions for Companies like TCS, CTS, HCL, IBM ... TCP Server-Client implementation in C ZIP command in Linux with examples tar command in Linux with examples UDP Server-Client implementation in C curl command in Linux with Examples
[ { "code": null, "e": 24494, "s": 24466, "text": "\n30 Jan, 2021" }, { "code": null, "e": 24629, "s": 24494, "text": "Before we move to file globbing, let’s understand what are wildcard patterns, these are the patterns containing strings like ‘?’, ‘*’ " }, { "code": null, "e": 24733, "s": 24629, "text": "File globbing is the operation that recognizes these patterns and does the job of file path expansion. " }, { "code": null, "e": 24781, "s": 24733, "text": "See the below example for clear understanding, " }, { "code": null, "e": 24806, "s": 24783, "text": "path expansion for ‘*’" }, { "code": null, "e": 24960, "s": 24806, "text": "If you observe the image above, I created several directories whose starting characters are HELLO and hello, and then tried to delete these directories. " }, { "code": null, "e": 25175, "s": 24960, "text": "When I used rm -rf hello*, it deleted the directories hello1, hello2, hello3, the ‘*’ symbol used after ‘hello’ recognizes the first characters as ‘hello’ and then zero or more occurrences of any other characters. " }, { "code": null, "e": 25219, "s": 25175, "text": "Examples using other wildcard characters : " }, { "code": null, "e": 25356, "s": 25219, "text": "1) asterisk (*) * is used to match any number of characters(zero or more), to understand more you can refer to the example taken above. " }, { "code": null, "e": 25420, "s": 25356, "text": "2) question mark(?) ? is used to match exactly one character. " }, { "code": null, "e": 25668, "s": 25420, "text": "In the above image, you can observe that ‘?’ can match exactly one character and is used at the end of the line. So using ‘hello?’ will match all files or directories whose starting characters are ‘hello’ and it will recognize one more character. " }, { "code": null, "e": 25771, "s": 25668, "text": "3) Square Brackets [] Square brackets are used to match the characters inside [], refer below image, " }, { "code": null, "e": 26007, "s": 25771, "text": "[] can be used to match exact characters or you can also specify a range, like in the above example, using ‘hello[1-5]’ will display all files and directories starting with ‘hello’, then the next character can be a number from 1 to 5. " }, { "code": null, "e": 26124, "s": 26007, "text": "4) exclamation mark (!) ! is used to exclude characters from the list that is specified within the square brackets. " }, { "code": null, "e": 26139, "s": 26124, "text": "For example: " }, { "code": null, "e": 26242, "s": 26139, "text": "ls hello[!3]\n\nIt will display the directories starting with hello, ending with any character but not 3" }, { "code": null, "e": 26283, "s": 26242, "text": "5) Named character classes ([[:named:]])" }, { "code": null, "e": 26401, "s": 26283, "text": "It is used to print named values. Their interpretation depends on the LC_CTYPE locale; Some of them are listed below." }, { "code": null, "e": 26509, "s": 26401, "text": "‘[:alnum:]’ : Prints all those files having alphabets and digits. Both lower and uppercases are considered." }, { "code": null, "e": 26611, "s": 26509, "text": "‘[:alpha:]’ : Prints all those files having alphabets only. Both lower and uppercases are considered." }, { "code": null, "e": 26663, "s": 26611, "text": "‘[:digit:]’ : Prints all those files having digits." }, { "code": null, "e": 26726, "s": 26663, "text": "‘[:lower:]’: Prints all those files having lower-case letters." }, { "code": null, "e": 26876, "s": 26726, "text": "‘[:punct:]’ : Prints all those files having punctuation characters. Will search for ! ” # $ % & ‘ ( ) * + , – . / : ; < = > ? @ [ \\ ] ^ _ ` { | } ~." }, { "code": null, "e": 26937, "s": 26876, "text": "‘[:space:]’: Prints all those files having space characters." }, { "code": null, "e": 27000, "s": 26937, "text": "‘[:upper:]’: Prints all those files having lower-case letters." }, { "code": null, "e": 27111, "s": 27000, "text": "Note: They can be used with asterisk (*) ,question mark(?) or square brackets([]) to generate useful outputs. " }, { "code": null, "e": 27125, "s": 27111, "text": "For example: " }, { "code": null, "e": 27823, "s": 27125, "text": "ls [[:alpha:]]* : Will display the directories starting with a alphabet (either in lower or uppercase) and ending \n with any characters.\nls *[[:alnum:]]*.* : Will display the files (of any type) containing a alphabet or a digit but may start \n or end with any length of characters.\nls *[[:digit:]] : Will display the directories which may start with any length of characters but ending with a digit.\nls ?[[:lower:]] : Will display the directories starting with exactly one character and ending with a lowercase \n character.\nls *[[:upper:]]* : Will display the directories containing a alphabet or digit which may start or end with any \n length of characters." }, { "code": null, "e": 27888, "s": 27823, "text": "Note: Any combinations of *, ? Can be used with any named class." }, { "code": null, "e": 27904, "s": 27888, "text": "yashbeersingh42" }, { "code": null, "e": 27913, "s": 27904, "text": "Articles" }, { "code": null, "e": 27924, "s": 27913, "text": "Linux-Unix" }, { "code": null, "e": 28022, "s": 27924, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28031, "s": 28022, "text": "Comments" }, { "code": null, "e": 28044, "s": 28031, "text": "Old Comments" }, { "code": null, "e": 28065, "s": 28044, "text": "Const keyword in C++" }, { "code": null, "e": 28132, "s": 28065, "text": "What's the difference between Scripting and Programming Languages?" }, { "code": null, "e": 28162, "s": 28132, "text": "Service-Oriented Architecture" }, { "code": null, "e": 28221, "s": 28162, "text": "Amazon’s most frequently asked interview questions | Set 2" }, { "code": null, "e": 28281, "s": 28221, "text": "Must Do Questions for Companies like TCS, CTS, HCL, IBM ..." }, { "code": null, "e": 28319, "s": 28281, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 28354, "s": 28319, "text": "ZIP command in Linux with examples" }, { "code": null, "e": 28389, "s": 28354, "text": "tar command in Linux with examples" }, { "code": null, "e": 28427, "s": 28389, "text": "UDP Server-Client implementation in C" } ]
MySQL Tryit Editor v1.0
SELECT SUBSTR(CustomerName, 2, 5) AS ExtractString FROM Customers; ​ Edit the SQL Statement, and click "Run SQL" to see the result. This SQL-Statement is not supported in the WebSQL Database. The example still works, because it uses a modified version of SQL. Your browser does not support WebSQL. Your are now using a light-version of the Try-SQL Editor, with a read-only Database. If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time. Our Try-SQL Editor uses WebSQL to demonstrate SQL. A Database-object is created in your browser, for testing purposes. You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button. WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object. WebSQL is supported in Chrome, Safari, and Opera. If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data.
[ { "code": null, "e": 51, "s": 0, "text": "SELECT SUBSTR(CustomerName, 2, 5) AS ExtractString" }, { "code": null, "e": 67, "s": 51, "text": "FROM Customers;" }, { "code": null, "e": 69, "s": 67, "text": "​" }, { "code": null, "e": 141, "s": 78, "text": "Edit the SQL Statement, and click \"Run SQL\" to see the result." }, { "code": null, "e": 201, "s": 141, "text": "This SQL-Statement is not supported in the WebSQL Database." }, { "code": null, "e": 269, "s": 201, "text": "The example still works, because it uses a modified version of SQL." }, { "code": null, "e": 307, "s": 269, "text": "Your browser does not support WebSQL." }, { "code": null, "e": 392, "s": 307, "text": "Your are now using a light-version of the Try-SQL Editor, with a read-only Database." }, { "code": null, "e": 566, "s": 392, "text": "If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time." }, { "code": null, "e": 617, "s": 566, "text": "Our Try-SQL Editor uses WebSQL to demonstrate SQL." }, { "code": null, "e": 685, "s": 617, "text": "A Database-object is created in your browser, for testing purposes." }, { "code": null, "e": 856, "s": 685, "text": "You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the \"Restore Database\" button." }, { "code": null, "e": 956, "s": 856, "text": "WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object." }, { "code": null, "e": 1006, "s": 956, "text": "WebSQL is supported in Chrome, Safari, and Opera." } ]
GATE | GATE-CS-2015 (Set 1) | Question 62 - GeeksforGeeks
09 Dec, 2021 Suppose that the stop-and-wait protocol is used on a link with a bit rate of 64 kilobits per second and 20 milliseconds propagation delay. Assume that the transmission time for the acknowledgment and the processing time at nodes are negligible. Then the minimum frame size in bytes to achieve a link utilization of at least 50% is _________.(A) 160(B) 320(C) 640(D) 220Answer: (B)Explanation: Transmission or Link speed = 64 kb per sec Propagation Delay = 20 millisec Since stop and wait is used, a packet is sent only when previous one is acknowledged. Let x be size of packet, transmission time = x / 64 millisec Since utilization is at least 50%, minimum possible total time for one packet is twice of transmission delay, which means x/64 * 2 = x/32 x/32 > x/64 + 2*20 x/64 > 40 x > 2560 bits = 320 bytes Answer in GATE keys says 160 bytes, but the answer keys seem incorrect. See question 36 here.Quiz of this Question adnanirshad158 GATE-CS-2015 (Set 1) GATE-GATE-CS-2015 (Set 1) GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments GATE | GATE-CS-2016 (Set 2) | Question 48 GATE | GATE-CS-2014-(Set-1) | Question 30 GATE | GATE-CS-2001 | Question 23 GATE | GATE-CS-2015 (Set 1) | Question 65 GATE | GATE CS 2010 | Question 45 GATE | GATE-CS-2015 (Set 3) | Question 65 GATE | GATE-CS-2004 | Question 3 GATE | GATE-CS-2014-(Set-1) | Question 65 C++ Program to count Vowels in a string using Pointer GATE | GATE-CS-2015 (Set 1) | Question 42
[ { "code": null, "e": 24171, "s": 24143, "text": "\n09 Dec, 2021" }, { "code": null, "e": 24564, "s": 24171, "text": "Suppose that the stop-and-wait protocol is used on a link with a bit rate of 64 kilobits per second and 20 milliseconds propagation delay. Assume that the transmission time for the acknowledgment and the processing time at nodes are negligible. Then the minimum frame size in bytes to achieve a link utilization of at least 50% is _________.(A) 160(B) 320(C) 640(D) 220Answer: (B)Explanation:" }, { "code": null, "e": 24984, "s": 24564, "text": "Transmission or Link speed = 64 kb per sec\nPropagation Delay = 20 millisec\n\nSince stop and wait is used, a packet is sent only\nwhen previous one is acknowledged.\n\nLet x be size of packet, transmission time = x / 64 millisec\n\nSince utilization is at least 50%, minimum possible total time\nfor one packet is twice of transmission delay, which means \nx/64 * 2 = x/32\n\nx/32 > x/64 + 2*20\nx/64 > 40\nx > 2560 bits = 320 bytes" }, { "code": null, "e": 25099, "s": 24984, "text": "Answer in GATE keys says 160 bytes, but the answer keys seem incorrect. See question 36 here.Quiz of this Question" }, { "code": null, "e": 25114, "s": 25099, "text": "adnanirshad158" }, { "code": null, "e": 25135, "s": 25114, "text": "GATE-CS-2015 (Set 1)" }, { "code": null, "e": 25161, "s": 25135, "text": "GATE-GATE-CS-2015 (Set 1)" }, { "code": null, "e": 25166, "s": 25161, "text": "GATE" }, { "code": null, "e": 25264, "s": 25166, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25273, "s": 25264, "text": "Comments" }, { "code": null, "e": 25286, "s": 25273, "text": "Old Comments" }, { "code": null, "e": 25328, "s": 25286, "text": "GATE | GATE-CS-2016 (Set 2) | Question 48" }, { "code": null, "e": 25370, "s": 25328, "text": "GATE | GATE-CS-2014-(Set-1) | Question 30" }, { "code": null, "e": 25404, "s": 25370, "text": "GATE | GATE-CS-2001 | Question 23" }, { "code": null, "e": 25446, "s": 25404, "text": "GATE | GATE-CS-2015 (Set 1) | Question 65" }, { "code": null, "e": 25480, "s": 25446, "text": "GATE | GATE CS 2010 | Question 45" }, { "code": null, "e": 25522, "s": 25480, "text": "GATE | GATE-CS-2015 (Set 3) | Question 65" }, { "code": null, "e": 25555, "s": 25522, "text": "GATE | GATE-CS-2004 | Question 3" }, { "code": null, "e": 25597, "s": 25555, "text": "GATE | GATE-CS-2014-(Set-1) | Question 65" }, { "code": null, "e": 25651, "s": 25597, "text": "C++ Program to count Vowels in a string using Pointer" } ]
Scala - while Loop
Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body. A while loop statement repeatedly executes a target statement as long as a given condition is true. The following is a syntax for while loop. while(condition){ statement(s); } Here, statement(s) may be a single statement or a block of statements. The condition may be any expression, and true is any nonzero value. The loop iterates while the condition is true. When the condition becomes false, program control passes to the line immediately following the loop. Here, key point of the while loop is that the loop might not ever run. When the condition is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed. Try the following example program to understand loop control statements (while statement) in Scala Programming Language. object Demo { def main(args: Array[String]) { // Local variable declaration: var a = 10; // while loop execution while( a < 20 ){ println( "Value of a: " + a ); a = a + 1; } } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. \>scalac Demo.scala \>scala Demo value of a: 10 value of a: 11 value of a: 12 value of a: 13 value of a: 14 value of a: 15 value of a: 16 value of a: 17 value of a: 18 value of a: 19 82 Lectures 7 hours Arnab Chakraborty 23 Lectures 1.5 hours Mukund Kumar Mishra 52 Lectures 1.5 hours Bigdata Engineer 76 Lectures 5.5 hours Bigdata Engineer 69 Lectures 7.5 hours Bigdata Engineer 46 Lectures 4.5 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 2229, "s": 1998, "text": "Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body. A while loop statement repeatedly executes a target statement as long as a given condition is true." }, { "code": null, "e": 2271, "s": 2229, "text": "The following is a syntax for while loop." }, { "code": null, "e": 2309, "s": 2271, "text": "while(condition){\n statement(s);\n}\n" }, { "code": null, "e": 2596, "s": 2309, "text": "Here, statement(s) may be a single statement or a block of statements. The condition may be any expression, and true is any nonzero value. The loop iterates while the condition is true. When the condition becomes false, program control passes to the line immediately following the loop." }, { "code": null, "e": 2814, "s": 2596, "text": "Here, key point of the while loop is that the loop might not ever run. When the condition is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed." }, { "code": null, "e": 2935, "s": 2814, "text": "Try the following example program to understand loop control statements (while statement) in Scala Programming Language." }, { "code": null, "e": 3168, "s": 2935, "text": "object Demo {\n def main(args: Array[String]) {\n // Local variable declaration:\n var a = 10;\n\n // while loop execution\n while( a < 20 ){\n println( \"Value of a: \" + a );\n a = a + 1;\n }\n }\n}" }, { "code": null, "e": 3275, "s": 3168, "text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program." }, { "code": null, "e": 3309, "s": 3275, "text": "\\>scalac Demo.scala\n\\>scala Demo\n" }, { "code": null, "e": 3460, "s": 3309, "text": "value of a: 10\nvalue of a: 11\nvalue of a: 12\nvalue of a: 13\nvalue of a: 14\nvalue of a: 15\nvalue of a: 16\nvalue of a: 17\nvalue of a: 18\nvalue of a: 19\n" }, { "code": null, "e": 3493, "s": 3460, "text": "\n 82 Lectures \n 7 hours \n" }, { "code": null, "e": 3512, "s": 3493, "text": " Arnab Chakraborty" }, { "code": null, "e": 3547, "s": 3512, "text": "\n 23 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3568, "s": 3547, "text": " Mukund Kumar Mishra" }, { "code": null, "e": 3603, "s": 3568, "text": "\n 52 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3621, "s": 3603, "text": " Bigdata Engineer" }, { "code": null, "e": 3656, "s": 3621, "text": "\n 76 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3674, "s": 3656, "text": " Bigdata Engineer" }, { "code": null, "e": 3709, "s": 3674, "text": "\n 69 Lectures \n 7.5 hours \n" }, { "code": null, "e": 3727, "s": 3709, "text": " Bigdata Engineer" }, { "code": null, "e": 3762, "s": 3727, "text": "\n 46 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3785, "s": 3762, "text": " Stone River ELearning" }, { "code": null, "e": 3792, "s": 3785, "text": " Print" }, { "code": null, "e": 3803, "s": 3792, "text": " Add Notes" } ]
Scapy - Packet Manipulation in Kali Linux - GeeksforGeeks
15 Apr, 2021 Scapy is a free and open-source tool available on Github. Scapy is written in Python language. Scapy is used for packet manipulation programs. Scapy tool forges the data packet that is coming from a source. Scapy decodes data packets and captures them. This tool reads packets using pcap files, and then it matches the request and replies. Scapy tool also performs scannings such as trace-routing, unit tests, You can also perform nmap scanning using scapy tool. This tool also performs very well at a lot of other specific tasks that most other tools can’t handle, like sending invalid frames, VLAN hopping+ARP cache poisoning, VoIP decoding on WEP protected channel can be performed by scapy tool. As this tool is written in Python language that’s why scapy tool supports Python2.7 Python 3 (3.4 to 3.7). This tool is a multi-platform tool this is available for Windows, Linux OSX, *BSD operating systems. Scapy tool can be used as a shell to interact with incoming traffic and outgoing traffic of the network. To use scapy tool you don’t need to install any external Python module on Linux and BSD like operating systems you just need to install some dependencies as described in the documentation of the tool. Features of scapy: Scapy is a free and open-source tool that is available on Github. Scapy is written in Python language. Using Scapy network can be manipulated easily. Scapy can decode data packets and can capture them. Scapy tool can be used as a shell to interact with incoming traffic and outgoing traffic of the network. Scapy can work with built-in modules you don’t need any external module to work. Scapy can be used for trace-routing with built-in modules. Uses of Scapy: Scapy is used for packet manipulation programs. Scapy tool forges the data packet that is coming from a source. Scapy decodes data packets and captures them. Scapy tool can be used as a shell to interact with incoming traffic and outgoing traffic of the network. VoIP decoding on WEP-protected channels can be performed by scapy tool. You can use Scapy tool on any operating system it’s available for all operating systems. Linux’s users can clone the tool from this link. It’s a free and open-source tool available on GitHub, Linux users can download it freely. Step 1. Open your Kali Linux. And move to the desktop using the following command. cd Desktop Step 2. Now you are on the desktop. Create a new directory here on the desktop because you have to install the scapy tool here. Create a new directory using the following command. mkdir scapy Step 3. A new directory has been created. Now move to this directory using the following command. cd scapy Step 4. Now you are in scapy directory here you have to clone the tool from GitHub. Use the following command to clone the tool in this directory. git clone https://github.com/secdev/scapy Step 5. Scapy tool has been downloaded into your Kali linux. Now to list out the contents of this tool use the following command. ls Step 6. As you listed out the contents of the tool you found the directory that has been downloaded with the tool. Move to this directory using the following command. cd scapy Step 7. On this step you have to list out the contents of the directory using the following command. ls Step 8. You can see the files of tool, License of tool etc, Now to run the tool use the following command. ./run_scapy This is the first interface of the tool. The tool is running now. All the installation process has been done. Now it’s time to see some examples of the tool. Example 1. Show the configuration of the tool and show the details of packets. To show the configuration of the tool use the following command. This command not only shows the configurations but also shows the packets that are coming from a source. conf Example 2. Show the routing table of networks. The following command will show the route table. You can add and delete data in this table as per your requirements. Use following command for routing. conf.route Example 3. List out all the commands of scapy tool that you can use with the tool. To know all the commands of the tool use the following command. lsc() Kali-Linux 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++ mv command in Linux with examples nohup Command in Linux with Examples scp command in Linux with Examples Docker - COPY Instruction chown command in Linux with Examples nslookup command in Linux with Examples SED command in Linux | Set 2 Named Pipe or FIFO with example C program uniq Command in LINUX with examples
[ { "code": null, "e": 24015, "s": 23987, "text": "\n15 Apr, 2021" }, { "code": null, "e": 24479, "s": 24015, "text": "Scapy is a free and open-source tool available on Github. Scapy is written in Python language. Scapy is used for packet manipulation programs. Scapy tool forges the data packet that is coming from a source. Scapy decodes data packets and captures them. This tool reads packets using pcap files, and then it matches the request and replies. Scapy tool also performs scannings such as trace-routing, unit tests, You can also perform nmap scanning using scapy tool. " }, { "code": null, "e": 24924, "s": 24479, "text": "This tool also performs very well at a lot of other specific tasks that most other tools can’t handle, like sending invalid frames, VLAN hopping+ARP cache poisoning, VoIP decoding on WEP protected channel can be performed by scapy tool. As this tool is written in Python language that’s why scapy tool supports Python2.7 Python 3 (3.4 to 3.7). This tool is a multi-platform tool this is available for Windows, Linux OSX, *BSD operating systems." }, { "code": null, "e": 25231, "s": 24924, "text": " Scapy tool can be used as a shell to interact with incoming traffic and outgoing traffic of the network. To use scapy tool you don’t need to install any external Python module on Linux and BSD like operating systems you just need to install some dependencies as described in the documentation of the tool." }, { "code": null, "e": 25250, "s": 25231, "text": "Features of scapy:" }, { "code": null, "e": 25316, "s": 25250, "text": "Scapy is a free and open-source tool that is available on Github." }, { "code": null, "e": 25353, "s": 25316, "text": "Scapy is written in Python language." }, { "code": null, "e": 25400, "s": 25353, "text": "Using Scapy network can be manipulated easily." }, { "code": null, "e": 25452, "s": 25400, "text": "Scapy can decode data packets and can capture them." }, { "code": null, "e": 25557, "s": 25452, "text": "Scapy tool can be used as a shell to interact with incoming traffic and outgoing traffic of the network." }, { "code": null, "e": 25638, "s": 25557, "text": "Scapy can work with built-in modules you don’t need any external module to work." }, { "code": null, "e": 25697, "s": 25638, "text": "Scapy can be used for trace-routing with built-in modules." }, { "code": null, "e": 25712, "s": 25697, "text": "Uses of Scapy:" }, { "code": null, "e": 25760, "s": 25712, "text": "Scapy is used for packet manipulation programs." }, { "code": null, "e": 25824, "s": 25760, "text": "Scapy tool forges the data packet that is coming from a source." }, { "code": null, "e": 25870, "s": 25824, "text": "Scapy decodes data packets and captures them." }, { "code": null, "e": 25975, "s": 25870, "text": "Scapy tool can be used as a shell to interact with incoming traffic and outgoing traffic of the network." }, { "code": null, "e": 26047, "s": 25975, "text": "VoIP decoding on WEP-protected channels can be performed by scapy tool." }, { "code": null, "e": 26136, "s": 26047, "text": "You can use Scapy tool on any operating system it’s available for all operating systems." }, { "code": null, "e": 26275, "s": 26136, "text": "Linux’s users can clone the tool from this link. It’s a free and open-source tool available on GitHub, Linux users can download it freely." }, { "code": null, "e": 26358, "s": 26275, "text": "Step 1. Open your Kali Linux. And move to the desktop using the following command." }, { "code": null, "e": 26369, "s": 26358, "text": "cd Desktop" }, { "code": null, "e": 26549, "s": 26369, "text": "Step 2. Now you are on the desktop. Create a new directory here on the desktop because you have to install the scapy tool here. Create a new directory using the following command." }, { "code": null, "e": 26562, "s": 26549, "text": " mkdir scapy" }, { "code": null, "e": 26660, "s": 26562, "text": "Step 3. A new directory has been created. Now move to this directory using the following command." }, { "code": null, "e": 26669, "s": 26660, "text": "cd scapy" }, { "code": null, "e": 26816, "s": 26669, "text": "Step 4. Now you are in scapy directory here you have to clone the tool from GitHub. Use the following command to clone the tool in this directory." }, { "code": null, "e": 26858, "s": 26816, "text": "git clone https://github.com/secdev/scapy" }, { "code": null, "e": 26988, "s": 26858, "text": "Step 5. Scapy tool has been downloaded into your Kali linux. Now to list out the contents of this tool use the following command." }, { "code": null, "e": 26991, "s": 26988, "text": "ls" }, { "code": null, "e": 27158, "s": 26991, "text": "Step 6. As you listed out the contents of the tool you found the directory that has been downloaded with the tool. Move to this directory using the following command." }, { "code": null, "e": 27167, "s": 27158, "text": "cd scapy" }, { "code": null, "e": 27268, "s": 27167, "text": "Step 7. On this step you have to list out the contents of the directory using the following command." }, { "code": null, "e": 27271, "s": 27268, "text": "ls" }, { "code": null, "e": 27378, "s": 27271, "text": "Step 8. You can see the files of tool, License of tool etc, Now to run the tool use the following command." }, { "code": null, "e": 27390, "s": 27378, "text": "./run_scapy" }, { "code": null, "e": 27548, "s": 27390, "text": "This is the first interface of the tool. The tool is running now. All the installation process has been done. Now it’s time to see some examples of the tool." }, { "code": null, "e": 27627, "s": 27548, "text": "Example 1. Show the configuration of the tool and show the details of packets." }, { "code": null, "e": 27797, "s": 27627, "text": "To show the configuration of the tool use the following command. This command not only shows the configurations but also shows the packets that are coming from a source." }, { "code": null, "e": 27802, "s": 27797, "text": "conf" }, { "code": null, "e": 27849, "s": 27802, "text": "Example 2. Show the routing table of networks." }, { "code": null, "e": 28001, "s": 27849, "text": "The following command will show the route table. You can add and delete data in this table as per your requirements. Use following command for routing." }, { "code": null, "e": 28012, "s": 28001, "text": "conf.route" }, { "code": null, "e": 28095, "s": 28012, "text": "Example 3. List out all the commands of scapy tool that you can use with the tool." }, { "code": null, "e": 28159, "s": 28095, "text": "To know all the commands of the tool use the following command." }, { "code": null, "e": 28165, "s": 28159, "text": "lsc()" }, { "code": null, "e": 28176, "s": 28165, "text": "Kali-Linux" }, { "code": null, "e": 28187, "s": 28176, "text": "Linux-Unix" }, { "code": null, "e": 28285, "s": 28187, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28294, "s": 28285, "text": "Comments" }, { "code": null, "e": 28307, "s": 28294, "text": "Old Comments" }, { "code": null, "e": 28333, "s": 28307, "text": "Thread functions in C/C++" }, { "code": null, "e": 28367, "s": 28333, "text": "mv command in Linux with examples" }, { "code": null, "e": 28404, "s": 28367, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 28439, "s": 28404, "text": "scp command in Linux with Examples" }, { "code": null, "e": 28465, "s": 28439, "text": "Docker - COPY Instruction" }, { "code": null, "e": 28502, "s": 28465, "text": "chown command in Linux with Examples" }, { "code": null, "e": 28542, "s": 28502, "text": "nslookup command in Linux with Examples" }, { "code": null, "e": 28571, "s": 28542, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 28613, "s": 28571, "text": "Named Pipe or FIFO with example C program" } ]
p5.js | position() Function - GeeksforGeeks
20 Aug, 2019 The position() function is used to set the position of the element relative to origin (0, 0) coordinate. If this function is not containing any parameters then it returns the x and y position of the element. Note: This function requires the p5.dom library. So add the following line in the head section of the index.html file. <script language="javascript" type="text/javascript" src="path/to/p5.dom.js"></script> Syntax: position() or position( x, y ) Parameters: x: This parameter holds the x-position relative to top-left of window. y: This parameter holds the y-position relative to top-left of window. Return Value: This function returns an object containing the x and y position of the element. Below examples illustrate the position() function in p5.js: Example 1: function setup() { // Create canvas of given size createCanvas(400, 200); // Set background color background('green'); // Create an input element var div_cont = createDiv('Welcome to GeeksforGeeks'); // Set the position of div element div_cont.position(60, 80); // Set font color div_cont.style('color', '#ffffff'); // Set width of input field div_cont.style('width', '250px'); // Set font-size of input text div_cont.style('font-size', '20px'); } Output: Example 2: function setup() { // Create canvas of given size createCanvas(400, 200); // Set background color background('green'); // Create an input element var input_val = createInput(''); // Set the attribute and its value input_val.attribute('value', 'Welcome to GeeksforGeeks'); // Set the position of div element input_val.position(60, 80); // Set width of input field input_val.style('width', '250px'); // Set font-size of input text input_val.style('font-size', '20px'); } Output: JavaScript-p5.js JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Convert a string to an integer in JavaScript Set the value of an input field in JavaScript Differences between Functional Components and Class Components in React How to Open URL in New Tab using JavaScript ? Form validation using HTML and JavaScript Express.js express.Router() Function Installation of Node.js on Linux Convert a string to an integer in JavaScript How to set the default value for an HTML <select> element ? Top 10 Angular Libraries For Web Developers
[ { "code": null, "e": 24919, "s": 24891, "text": "\n20 Aug, 2019" }, { "code": null, "e": 25127, "s": 24919, "text": "The position() function is used to set the position of the element relative to origin (0, 0) coordinate. If this function is not containing any parameters then it returns the x and y position of the element." }, { "code": null, "e": 25246, "s": 25127, "text": "Note: This function requires the p5.dom library. So add the following line in the head section of the index.html file." }, { "code": "<script language=\"javascript\" type=\"text/javascript\" src=\"path/to/p5.dom.js\"></script>", "e": 25337, "s": 25246, "text": null }, { "code": null, "e": 25345, "s": 25337, "text": "Syntax:" }, { "code": null, "e": 25356, "s": 25345, "text": "position()" }, { "code": null, "e": 25359, "s": 25356, "text": "or" }, { "code": null, "e": 25376, "s": 25359, "text": "position( x, y )" }, { "code": null, "e": 25388, "s": 25376, "text": "Parameters:" }, { "code": null, "e": 25459, "s": 25388, "text": "x: This parameter holds the x-position relative to top-left of window." }, { "code": null, "e": 25530, "s": 25459, "text": "y: This parameter holds the y-position relative to top-left of window." }, { "code": null, "e": 25624, "s": 25530, "text": "Return Value: This function returns an object containing the x and y position of the element." }, { "code": null, "e": 25684, "s": 25624, "text": "Below examples illustrate the position() function in p5.js:" }, { "code": null, "e": 25695, "s": 25684, "text": "Example 1:" }, { "code": "function setup() { // Create canvas of given size createCanvas(400, 200); // Set background color background('green'); // Create an input element var div_cont = createDiv('Welcome to GeeksforGeeks'); // Set the position of div element div_cont.position(60, 80); // Set font color div_cont.style('color', '#ffffff'); // Set width of input field div_cont.style('width', '250px'); // Set font-size of input text div_cont.style('font-size', '20px'); } ", "e": 26226, "s": 25695, "text": null }, { "code": null, "e": 26234, "s": 26226, "text": "Output:" }, { "code": null, "e": 26245, "s": 26234, "text": "Example 2:" }, { "code": "function setup() { // Create canvas of given size createCanvas(400, 200); // Set background color background('green'); // Create an input element var input_val = createInput(''); // Set the attribute and its value input_val.attribute('value', 'Welcome to GeeksforGeeks'); // Set the position of div element input_val.position(60, 80); // Set width of input field input_val.style('width', '250px'); // Set font-size of input text input_val.style('font-size', '20px'); } ", "e": 26805, "s": 26245, "text": null }, { "code": null, "e": 26813, "s": 26805, "text": "Output:" }, { "code": null, "e": 26830, "s": 26813, "text": "JavaScript-p5.js" }, { "code": null, "e": 26841, "s": 26830, "text": "JavaScript" }, { "code": null, "e": 26858, "s": 26841, "text": "Web Technologies" }, { "code": null, "e": 26956, "s": 26858, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26965, "s": 26956, "text": "Comments" }, { "code": null, "e": 26978, "s": 26965, "text": "Old Comments" }, { "code": null, "e": 27023, "s": 26978, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 27069, "s": 27023, "text": "Set the value of an input field in JavaScript" }, { "code": null, "e": 27141, "s": 27069, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 27187, "s": 27141, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 27229, "s": 27187, "text": "Form validation using HTML and JavaScript" }, { "code": null, "e": 27266, "s": 27229, "text": "Express.js express.Router() Function" }, { "code": null, "e": 27299, "s": 27266, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27344, "s": 27299, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 27404, "s": 27344, "text": "How to set the default value for an HTML <select> element ?" } ]
Correlation for data science | Towards Data Science
Correlation (to be exact Correlation in Statistic) is a measure of a mutual relationship between two variables whether they are causal or not. This degree of measurement could be measured on any kind of data type (Continous and Continous, Categorical and Categorical, Continous and Categorical). Although correlation stated how it measured the mutual relationship, the presence of correlation measurement does not provide strong evidence toward causation. It implies that correlation does not mean causation. How then correlation could be useful? Correlation is useful because it can indicate a predictive relationship that could be exploited in the practice. For example, the number of Ice cream sold are more frequently with a higher temperature in the day. This could also imply causation because when the weather is hotter, people tend to bought Ice cream compared when it is colder. However, just like I stated before; most of the time correlation cannot imply any causation. Before we went into correlation and how it calculated, let me show the concept of covariance. In statistics, covariance is a measure of the association between variable X and Y. To be exact, it measures the linear relationship tendency of the variables. Here I would show how covariance is calculated. Covariance is calculated by subtracting each member of the variable by its mean (Centering the data). These centered scores are multiplied to measure whether the increase or decrease in one variable is associated with one another. Finally, the expected value (E) of these centered scores is calculated as a summary of the association. The expected value itself in another term is the average or mean (μ). The problem with covariance is that X and Y could take any kind of value with their respective scale. This blur the interpretation process and rendering the covariances comparison with each other to be impossible. As an example, Cov(X, Y) = 7 and Cov(A, B) = 5 would tell us that these pairs respectively are positively associated, but it is difficult to tell whether the relationship between X and Y is stronger than A and B without any additional information. This is where correlation becomes useful — by standardizing covariance via variability measurement in the data, it would produce a product that has intuitive interpretations and consistent scale. Now, let us get through to our first correlation. Pearson Correlation is one of the most used correlations during the data analysis process. Pearson correlation measures the linear relationship between variable continuous X and variable continuous Y and has a value between 1 and -1. In other words, the Pearson Correlation Coefficient measures the relationship between 2 variables via a line. Let us see how the Pearson Correlation Coefficient calculated. If you notice, the top side of the fraction equation (numerator) is similar to the covariance equation we previously just discussed. This means we could also state the Pearson Correlation Coefficient as below. The equation above stated that the covariance is divided by multiplication of the X standard deviation (σX)and Y standard deviation (σY). The division process by the standard deviation is to standardize our data and ensuring the correlation value would fall within the 1 to -1 range. This eases our correlation interpretation. So, how can we interpret the Pearson correlation? When the correlation coefficient is closer to value 1, it means there is a positive relationship between variable X and Y. A positive relationship indicates an increase in one variable associated with an increase in the other. On the other hand, the closer correlation coefficient is to -1 would mean there is a negative relationship which is the increase in one variable would result in a decrease in the other. If X and Y are independent, then the correlation coefficient is close to 0 although the Pearson correlation can be small even if there is a strong relationship between two variables. If you realize from the above explanation, actually there is a clear connection between the Pearson Correlation Coefficient and the slope of the regression line. First, let me show an example of a scatter plot with their regression line. In the figure above, the regression line is optimal because it minimizes the distance of all points to the regression line. Because of this property, the slope of the regression line of Y and X is mathematically equivalent to the correlation between X and Y, standardized by their standard deviations. In other words, the Pearson correlation coefficient reflects the association and amount of variability between the two variables. This property also implies that the Pearson correlation is susceptible to the outlier. This relationship with the slope of the line has shown why Pearson correlation describes the linear relationship and why correlation is important in predictive modeling. What if we want to measure the non-linear relationship between the variable? There are some other measurements to describe this non-linear relationship which I would show next. Unlike the Pearson Correlation Coefficient, Spearman Rank Correlation measures the monotonic relationship (Strictly increase or decrease, not both) between two variables and measured by the rank order of the values. The correlation still measured between continuous variable X and continuous variable Y, although the Spearman Rank Correlation method still relevant to the discrete ordinal variable. Here we calculate the Spearman Rank Correlation based on the data rank instead of the scores. Which means we calculate the covariance between the data rank and the rank standard deviation. If all the rank is unique or no tie between the rank, we could simplify the equation as below. Where n is the number of observation and d is the difference between rank. This formula only strictly used when no ties present. Spearman rank correlation could be interpreted similarly as the Pearson correlation coefficient as their value falls between -1 to 1. The closer the score to 1 means that there is a positive monotonic relationship between the variable (the data keep increasing) and vice versa. If variable X and variable Y independent, the value would be equal to 0. While we talk about rank, what is exactly rank is? Below is an example of the ranking process I have taken from Wikipedia. The easier way to understand the ranking is that we order the data from the smallest to the largest and we assigning the ranking depending on the data order. 1 is the smallest ranking, it means that rank 1 is assigned to the smallest value of the respective column. Why the respective column? we could see from the table above that we rank the data based on their respective columns and because we want to know the covariance between the ranking of column X and column Y; we assign the rank w.r.t. each column. To be precise, what we want is the ranking difference between each row. The difference between Pearson and Spearman Correlation is best illustrated in the picture below. Since our data above showing the perfect positive monotonic relationship (the data is always increasing) and non-linear relationships; our Spearman correlation is equal to 1. In this case, the Pearson relationship is weaker but still shown a strong association as there is a partial linearity relationship between the data. Another way to measure the non-linear relationship between variables is by applying Kendall’s Tau Rank Correlation. Kendall Tau rank correlation coefficient measures the degree of similarity between two sets of ranks given to the same set of objects. However, unlike Spearman’s coefficient, Kendall Tau only measures directional agreement, not the rank differences. Therefore, this coefficient is more appropriate for discrete data. Below is how we measure the Kendall Tau Correlation. Where Concordant pairs are pairs of values ((x1, y1), (x2, y2))in which ranks coincide: x1 < x2 and y1 < y2 or x1 > x2 and y1 > y2. Discordant pairs are ranks pair not following these From the equation above, we could see the measurement would depend upon the number of inversions of pairs of objects. In order to evaluate them, each rank order is represented by the set of all pairs of objects (e.g., [a, b] and [b, a] are the two pairs representing the objects a and b). Let’s use a sample dataset to measure our correlation. Above is a sample dataset with ranking in their respective columns. We would need to count the number of concordant pairs and the discordant pairs according to our previous rule. (1,2) and (2,7) are concordant pair as 1<2 and 2<7 while (1,2) and (4,1) are discordant pairs because 1 < 4 but 2 > 1. If our dataset example case, the concordant pairs are: (1,2) and (2,7) (1,2) and (3,5) and the discordant pairs are: (1,2) and (4,1) (2,7) and (3,5) (2,7) and (4,1) (3,5) and (4,1) This means we have 2 concordant pairs and 4 discordant pairs. Using the previous equation 2–4/(4(4–1)/2) would yield -0.33. Kendall Tau will take values between −1 and +1 with a value closer to −1 means when one rank order is the exact reverse of the other rank order and the closer the value to +1 means both rank orders are identical. Kendall Tau correlation could be also interpreted as a probability difference between the probability of object in the same order (concordant) with observation in a different order (discordant). Kendall Tau is good to be used in the case we want to know if the order of the variables is similar or not; especially if our data is discrete. However, there are other ways to measure discrete variable correlation (Shaked Zychlinski have written a really good article about it here but I want to elaborate it even more) Cramer’s V is a measure of association between two discrete variables. The measurement is based on the Pearson chi-square statistic and has an output range between 0 to 1; The closer the value to 0 means less association between the two variables and 1 means strong association between the two variables. There is no negative (-) value as an output because there is no such thing as a negative association. Cramer’s V calculation is calculated in the equation below. Where χ2 is chi-square statistic, n is the number of observations, k is the number of the columns, and r is the number of the rows. Because Cramer’s V overestimate the association strength (chi-square statistic value tends to increase with the increasing of differences between the number of the row and columns), we need to correct the bias. This was done by the equation below. where Luckily scipy and pandas module in python has provided us an easy way to calculate all the numbers. In my case, I would use the tips sample dataset from seaborn. #Importing the important moduleimport pandas as pdimport matplotlib.pyplot as pltimport seaborn as sns#Load the datasettips = sns.load_dataset('tips')#Creating new category based on the tip feature (0: tip below 3 and 1 tip equal or more than 3)tips['tip_category'] = tips['tip'].apply(lambda x: 1 if x>3 else 0) Let’s say we want to know the relationship between the total_bill and tip feature. Using the pandas method .corr, we could get our correlation measured in a matter of seconds. Pandas .corr method only provides 3 kinds of correlation measurement; Pearson, Spearman, and Kendall. #Using the .corr method from pandas, default is Pearson Corellation tips[['total_bill', 'tip']].corr() tips['total_bill', 'tip']].corr('spearman') If we need the correlation result as statistical hypothesis testing, we could use the function from the scipy module to calculate this. from scipy.stats import pearsonr, spearmanrpearsonr(tips['total_bill'], tips['tip'])#Output: (0.6757341092113647, 6.6924706468630016e-34)spearmanr(tips['total_bill'], tips['tip'])#Output: SpearmanrResult(correlation=0.6789681219001009, pvalue=2.501158440923619e-34)#Where the first number represent the Correlation Coefficient and #the second number represent the p-value. In correlation analysis, we could test the statistical hypothesis whether there is a relationship between the variable or not. Formally it is stated as: H0: There is no statistically significant relationship between variable X and variable Y H1: There is a statistically significant relationship between variable X and variable Y Just like any other hypothesis testing, we evaluate our hypothesis based on the p-value. Commonly, we set the alpha level 95% means if the p-value is below 0.05 then we reject the H0 and accept the H1. In this case, H0 is similar if we say that Variable X and Variable Y are independent. We could also calculate the Kendall Tau correlation similarly to the way above. As I previously stated that Kendall Tau correlation is more appropriate to be applied for a discrete variable, for that I would take an example relationship between size and tip_category. tips[['size', 'tip_category']].corr('kendall') from scipy.stats import kendalltaukendalltau(tips['size'], tips['tip_category'])#Output: KendalltauResult(correlation=0.3528363722264162, pvalue=6.456364135002584e-09) Calculating Cramer’s V need an additional module and the corrected bias version needs to be defined on our own. For the uncorrected version, we could use the researchpy module to help calculate our Cramer’s V. Let’s applied it in the relationship between sex and size variable. pip install researchpy #only if you never have this module beforefrom researchpy import crosstabcross, res = crosstab(tips['sex'], tips['size'], test = 'chi-square')res Using researchpy, we would get the information we need regarding the statistical test and the correlation analysis. Although, as I said before it has not corrected yet which means it overestimates the association strength. For that reason, I would use the bias-corrected Cramer’s V function defined by Shaked Zychlinski previously. def cramers_v(x, y): import scipy.stats as ss confusion_matrix = pd.crosstab(x,y) chi2 = ss.chi2_contingency(confusion_matrix)[0] n = confusion_matrix.sum().sum() phi2 = chi2/n r,k = confusion_matrix.shape phi2corr = max(0, phi2-((k-1)*(r-1))/(n-1)) rcorr = r-((r-1)**2)/(n-1) kcorr = k-((k-1)**2)/(n-1) return np.sqrt(phi2corr/min((kcorr-1),(rcorr-1)))cramers_v(tips['sex'], tips['size'])#output: 0.058202656344848294 As we could see above, the association strength between the corrected and uncorrected versions would be different. I have shown a few ways to measure the relationship between variables and how we could interpret the measurement. It is tempting to conclude that there is causation between the correlated values, but as many have said before ‘correlation does not imply causation’. Things might not be as straightforward as the number is shown. What we need is critical thinking to dissect information we get from this correlation before we could conclude anything. If you are not subscribed as a Medium Member, please consider subscribing through my referral.
[ { "code": null, "e": 719, "s": 172, "text": "Correlation (to be exact Correlation in Statistic) is a measure of a mutual relationship between two variables whether they are causal or not. This degree of measurement could be measured on any kind of data type (Continous and Continous, Categorical and Categorical, Continous and Categorical). Although correlation stated how it measured the mutual relationship, the presence of correlation measurement does not provide strong evidence toward causation. It implies that correlation does not mean causation. How then correlation could be useful?" }, { "code": null, "e": 1153, "s": 719, "text": "Correlation is useful because it can indicate a predictive relationship that could be exploited in the practice. For example, the number of Ice cream sold are more frequently with a higher temperature in the day. This could also imply causation because when the weather is hotter, people tend to bought Ice cream compared when it is colder. However, just like I stated before; most of the time correlation cannot imply any causation." }, { "code": null, "e": 1247, "s": 1153, "text": "Before we went into correlation and how it calculated, let me show the concept of covariance." }, { "code": null, "e": 1455, "s": 1247, "text": "In statistics, covariance is a measure of the association between variable X and Y. To be exact, it measures the linear relationship tendency of the variables. Here I would show how covariance is calculated." }, { "code": null, "e": 1860, "s": 1455, "text": "Covariance is calculated by subtracting each member of the variable by its mean (Centering the data). These centered scores are multiplied to measure whether the increase or decrease in one variable is associated with one another. Finally, the expected value (E) of these centered scores is calculated as a summary of the association. The expected value itself in another term is the average or mean (μ)." }, { "code": null, "e": 2518, "s": 1860, "text": "The problem with covariance is that X and Y could take any kind of value with their respective scale. This blur the interpretation process and rendering the covariances comparison with each other to be impossible. As an example, Cov(X, Y) = 7 and Cov(A, B) = 5 would tell us that these pairs respectively are positively associated, but it is difficult to tell whether the relationship between X and Y is stronger than A and B without any additional information. This is where correlation becomes useful — by standardizing covariance via variability measurement in the data, it would produce a product that has intuitive interpretations and consistent scale." }, { "code": null, "e": 2568, "s": 2518, "text": "Now, let us get through to our first correlation." }, { "code": null, "e": 2912, "s": 2568, "text": "Pearson Correlation is one of the most used correlations during the data analysis process. Pearson correlation measures the linear relationship between variable continuous X and variable continuous Y and has a value between 1 and -1. In other words, the Pearson Correlation Coefficient measures the relationship between 2 variables via a line." }, { "code": null, "e": 2975, "s": 2912, "text": "Let us see how the Pearson Correlation Coefficient calculated." }, { "code": null, "e": 3185, "s": 2975, "text": "If you notice, the top side of the fraction equation (numerator) is similar to the covariance equation we previously just discussed. This means we could also state the Pearson Correlation Coefficient as below." }, { "code": null, "e": 3562, "s": 3185, "text": "The equation above stated that the covariance is divided by multiplication of the X standard deviation (σX)and Y standard deviation (σY). The division process by the standard deviation is to standardize our data and ensuring the correlation value would fall within the 1 to -1 range. This eases our correlation interpretation. So, how can we interpret the Pearson correlation?" }, { "code": null, "e": 4158, "s": 3562, "text": "When the correlation coefficient is closer to value 1, it means there is a positive relationship between variable X and Y. A positive relationship indicates an increase in one variable associated with an increase in the other. On the other hand, the closer correlation coefficient is to -1 would mean there is a negative relationship which is the increase in one variable would result in a decrease in the other. If X and Y are independent, then the correlation coefficient is close to 0 although the Pearson correlation can be small even if there is a strong relationship between two variables." }, { "code": null, "e": 4396, "s": 4158, "text": "If you realize from the above explanation, actually there is a clear connection between the Pearson Correlation Coefficient and the slope of the regression line. First, let me show an example of a scatter plot with their regression line." }, { "code": null, "e": 4698, "s": 4396, "text": "In the figure above, the regression line is optimal because it minimizes the distance of all points to the regression line. Because of this property, the slope of the regression line of Y and X is mathematically equivalent to the correlation between X and Y, standardized by their standard deviations." }, { "code": null, "e": 4915, "s": 4698, "text": "In other words, the Pearson correlation coefficient reflects the association and amount of variability between the two variables. This property also implies that the Pearson correlation is susceptible to the outlier." }, { "code": null, "e": 5085, "s": 4915, "text": "This relationship with the slope of the line has shown why Pearson correlation describes the linear relationship and why correlation is important in predictive modeling." }, { "code": null, "e": 5262, "s": 5085, "text": "What if we want to measure the non-linear relationship between the variable? There are some other measurements to describe this non-linear relationship which I would show next." }, { "code": null, "e": 5661, "s": 5262, "text": "Unlike the Pearson Correlation Coefficient, Spearman Rank Correlation measures the monotonic relationship (Strictly increase or decrease, not both) between two variables and measured by the rank order of the values. The correlation still measured between continuous variable X and continuous variable Y, although the Spearman Rank Correlation method still relevant to the discrete ordinal variable." }, { "code": null, "e": 5945, "s": 5661, "text": "Here we calculate the Spearman Rank Correlation based on the data rank instead of the scores. Which means we calculate the covariance between the data rank and the rank standard deviation. If all the rank is unique or no tie between the rank, we could simplify the equation as below." }, { "code": null, "e": 6074, "s": 5945, "text": "Where n is the number of observation and d is the difference between rank. This formula only strictly used when no ties present." }, { "code": null, "e": 6425, "s": 6074, "text": "Spearman rank correlation could be interpreted similarly as the Pearson correlation coefficient as their value falls between -1 to 1. The closer the score to 1 means that there is a positive monotonic relationship between the variable (the data keep increasing) and vice versa. If variable X and variable Y independent, the value would be equal to 0." }, { "code": null, "e": 6548, "s": 6425, "text": "While we talk about rank, what is exactly rank is? Below is an example of the ranking process I have taken from Wikipedia." }, { "code": null, "e": 7131, "s": 6548, "text": "The easier way to understand the ranking is that we order the data from the smallest to the largest and we assigning the ranking depending on the data order. 1 is the smallest ranking, it means that rank 1 is assigned to the smallest value of the respective column. Why the respective column? we could see from the table above that we rank the data based on their respective columns and because we want to know the covariance between the ranking of column X and column Y; we assign the rank w.r.t. each column. To be precise, what we want is the ranking difference between each row." }, { "code": null, "e": 7229, "s": 7131, "text": "The difference between Pearson and Spearman Correlation is best illustrated in the picture below." }, { "code": null, "e": 7553, "s": 7229, "text": "Since our data above showing the perfect positive monotonic relationship (the data is always increasing) and non-linear relationships; our Spearman correlation is equal to 1. In this case, the Pearson relationship is weaker but still shown a strong association as there is a partial linearity relationship between the data." }, { "code": null, "e": 8039, "s": 7553, "text": "Another way to measure the non-linear relationship between variables is by applying Kendall’s Tau Rank Correlation. Kendall Tau rank correlation coefficient measures the degree of similarity between two sets of ranks given to the same set of objects. However, unlike Spearman’s coefficient, Kendall Tau only measures directional agreement, not the rank differences. Therefore, this coefficient is more appropriate for discrete data. Below is how we measure the Kendall Tau Correlation." }, { "code": null, "e": 8223, "s": 8039, "text": "Where Concordant pairs are pairs of values ((x1, y1), (x2, y2))in which ranks coincide: x1 < x2 and y1 < y2 or x1 > x2 and y1 > y2. Discordant pairs are ranks pair not following these" }, { "code": null, "e": 8567, "s": 8223, "text": "From the equation above, we could see the measurement would depend upon the number of inversions of pairs of objects. In order to evaluate them, each rank order is represented by the set of all pairs of objects (e.g., [a, b] and [b, a] are the two pairs representing the objects a and b). Let’s use a sample dataset to measure our correlation." }, { "code": null, "e": 8920, "s": 8567, "text": "Above is a sample dataset with ranking in their respective columns. We would need to count the number of concordant pairs and the discordant pairs according to our previous rule. (1,2) and (2,7) are concordant pair as 1<2 and 2<7 while (1,2) and (4,1) are discordant pairs because 1 < 4 but 2 > 1. If our dataset example case, the concordant pairs are:" }, { "code": null, "e": 8936, "s": 8920, "text": "(1,2) and (2,7)" }, { "code": null, "e": 8952, "s": 8936, "text": "(1,2) and (3,5)" }, { "code": null, "e": 8982, "s": 8952, "text": "and the discordant pairs are:" }, { "code": null, "e": 8998, "s": 8982, "text": "(1,2) and (4,1)" }, { "code": null, "e": 9014, "s": 8998, "text": "(2,7) and (3,5)" }, { "code": null, "e": 9030, "s": 9014, "text": "(2,7) and (4,1)" }, { "code": null, "e": 9046, "s": 9030, "text": "(3,5) and (4,1)" }, { "code": null, "e": 9170, "s": 9046, "text": "This means we have 2 concordant pairs and 4 discordant pairs. Using the previous equation 2–4/(4(4–1)/2) would yield -0.33." }, { "code": null, "e": 9578, "s": 9170, "text": "Kendall Tau will take values between −1 and +1 with a value closer to −1 means when one rank order is the exact reverse of the other rank order and the closer the value to +1 means both rank orders are identical. Kendall Tau correlation could be also interpreted as a probability difference between the probability of object in the same order (concordant) with observation in a different order (discordant)." }, { "code": null, "e": 9899, "s": 9578, "text": "Kendall Tau is good to be used in the case we want to know if the order of the variables is similar or not; especially if our data is discrete. However, there are other ways to measure discrete variable correlation (Shaked Zychlinski have written a really good article about it here but I want to elaborate it even more)" }, { "code": null, "e": 10366, "s": 9899, "text": "Cramer’s V is a measure of association between two discrete variables. The measurement is based on the Pearson chi-square statistic and has an output range between 0 to 1; The closer the value to 0 means less association between the two variables and 1 means strong association between the two variables. There is no negative (-) value as an output because there is no such thing as a negative association. Cramer’s V calculation is calculated in the equation below." }, { "code": null, "e": 10498, "s": 10366, "text": "Where χ2 is chi-square statistic, n is the number of observations, k is the number of the columns, and r is the number of the rows." }, { "code": null, "e": 10746, "s": 10498, "text": "Because Cramer’s V overestimate the association strength (chi-square statistic value tends to increase with the increasing of differences between the number of the row and columns), we need to correct the bias. This was done by the equation below." }, { "code": null, "e": 10752, "s": 10746, "text": "where" }, { "code": null, "e": 10914, "s": 10752, "text": "Luckily scipy and pandas module in python has provided us an easy way to calculate all the numbers. In my case, I would use the tips sample dataset from seaborn." }, { "code": null, "e": 11227, "s": 10914, "text": "#Importing the important moduleimport pandas as pdimport matplotlib.pyplot as pltimport seaborn as sns#Load the datasettips = sns.load_dataset('tips')#Creating new category based on the tip feature (0: tip below 3 and 1 tip equal or more than 3)tips['tip_category'] = tips['tip'].apply(lambda x: 1 if x>3 else 0)" }, { "code": null, "e": 11505, "s": 11227, "text": "Let’s say we want to know the relationship between the total_bill and tip feature. Using the pandas method .corr, we could get our correlation measured in a matter of seconds. Pandas .corr method only provides 3 kinds of correlation measurement; Pearson, Spearman, and Kendall." }, { "code": null, "e": 11608, "s": 11505, "text": "#Using the .corr method from pandas, default is Pearson Corellation tips[['total_bill', 'tip']].corr()" }, { "code": null, "e": 11652, "s": 11608, "text": "tips['total_bill', 'tip']].corr('spearman')" }, { "code": null, "e": 11788, "s": 11652, "text": "If we need the correlation result as statistical hypothesis testing, we could use the function from the scipy module to calculate this." }, { "code": null, "e": 12161, "s": 11788, "text": "from scipy.stats import pearsonr, spearmanrpearsonr(tips['total_bill'], tips['tip'])#Output: (0.6757341092113647, 6.6924706468630016e-34)spearmanr(tips['total_bill'], tips['tip'])#Output: SpearmanrResult(correlation=0.6789681219001009, pvalue=2.501158440923619e-34)#Where the first number represent the Correlation Coefficient and #the second number represent the p-value." }, { "code": null, "e": 12314, "s": 12161, "text": "In correlation analysis, we could test the statistical hypothesis whether there is a relationship between the variable or not. Formally it is stated as:" }, { "code": null, "e": 12403, "s": 12314, "text": "H0: There is no statistically significant relationship between variable X and variable Y" }, { "code": null, "e": 12491, "s": 12403, "text": "H1: There is a statistically significant relationship between variable X and variable Y" }, { "code": null, "e": 12779, "s": 12491, "text": "Just like any other hypothesis testing, we evaluate our hypothesis based on the p-value. Commonly, we set the alpha level 95% means if the p-value is below 0.05 then we reject the H0 and accept the H1. In this case, H0 is similar if we say that Variable X and Variable Y are independent." }, { "code": null, "e": 13047, "s": 12779, "text": "We could also calculate the Kendall Tau correlation similarly to the way above. As I previously stated that Kendall Tau correlation is more appropriate to be applied for a discrete variable, for that I would take an example relationship between size and tip_category." }, { "code": null, "e": 13094, "s": 13047, "text": "tips[['size', 'tip_category']].corr('kendall')" }, { "code": null, "e": 13262, "s": 13094, "text": "from scipy.stats import kendalltaukendalltau(tips['size'], tips['tip_category'])#Output: KendalltauResult(correlation=0.3528363722264162, pvalue=6.456364135002584e-09)" }, { "code": null, "e": 13540, "s": 13262, "text": "Calculating Cramer’s V need an additional module and the corrected bias version needs to be defined on our own. For the uncorrected version, we could use the researchpy module to help calculate our Cramer’s V. Let’s applied it in the relationship between sex and size variable." }, { "code": null, "e": 13709, "s": 13540, "text": "pip install researchpy #only if you never have this module beforefrom researchpy import crosstabcross, res = crosstab(tips['sex'], tips['size'], test = 'chi-square')res" }, { "code": null, "e": 14041, "s": 13709, "text": "Using researchpy, we would get the information we need regarding the statistical test and the correlation analysis. Although, as I said before it has not corrected yet which means it overestimates the association strength. For that reason, I would use the bias-corrected Cramer’s V function defined by Shaked Zychlinski previously." }, { "code": null, "e": 14490, "s": 14041, "text": "def cramers_v(x, y): import scipy.stats as ss confusion_matrix = pd.crosstab(x,y) chi2 = ss.chi2_contingency(confusion_matrix)[0] n = confusion_matrix.sum().sum() phi2 = chi2/n r,k = confusion_matrix.shape phi2corr = max(0, phi2-((k-1)*(r-1))/(n-1)) rcorr = r-((r-1)**2)/(n-1) kcorr = k-((k-1)**2)/(n-1) return np.sqrt(phi2corr/min((kcorr-1),(rcorr-1)))cramers_v(tips['sex'], tips['size'])#output: 0.058202656344848294" }, { "code": null, "e": 14605, "s": 14490, "text": "As we could see above, the association strength between the corrected and uncorrected versions would be different." }, { "code": null, "e": 14719, "s": 14605, "text": "I have shown a few ways to measure the relationship between variables and how we could interpret the measurement." }, { "code": null, "e": 15054, "s": 14719, "text": "It is tempting to conclude that there is causation between the correlated values, but as many have said before ‘correlation does not imply causation’. Things might not be as straightforward as the number is shown. What we need is critical thinking to dissect information we get from this correlation before we could conclude anything." } ]
Fake Job Classification with BERT | by Sadrach Pierre, Ph.D. | Towards Data Science
Recently, The University of the Aegean published the Employment Scam Aegean Dataset. The data contains about 18K real-life job advertisements. The aim is to provide a clear picture of the Employment Scam problem to the research community. In this post, we will use BERT to classify fake job descriptions in the Employment Scam Aegean Dataset. Before we get started, let’s briefly review the BERT method. BERT stands for Bidirectional Encoder Representations from Transformers. The paper describing the BERT algorithm was published by Google and can be found here. BERT works by randomly masking word tokens and representing each masked word with a vector based on its context. The two applications of BERT are “pre-training” and “fine-tuning”. PRE-TRAINING BERT For the pre-training BERT algorithm, researchers trained two unsupervised learning tasks. The first task is described as Masked LM. This works by randomly masking 15% of a document and predicting those masked tokens. The second task is Next-Sentence Prediction (NSP). This is motivated by tasks such as Question Answering and Natural Language Inference. These tasks require models to accurately capture relationships between sentences. In order to tackle this, they pre-train for a binarized prediction task that can be trivially generated from any corpus in a single language. The example they give in the paper is as follows: if you have sentence A and B, 50% of the time A is labelled as “isNext” and the other 50% of the time it is a sentence that is randomly selected from the corpus and is labelled as “notNext”. Pre-training towards this tasks proves to be beneficial for Question Answering and Natural Language Inference tasks. FINE-TUNING BERT Fine Tuning BERT works by encoding concatenated text pairs with self attention. Self-attention is the process of learning correlations between current words and previous words. An early application of this is in the Long Short-Term Memory (LSTM) paper (Dong2016) where researchers used self-attention to do machine reading. The nice thing about BERT is through encoding concatenated texts with self attention bidirectional cross attention between pairs of sentences is captured. In this article, we will apply BERT to predict whether or not a job posting is fraudulent. This post is inspired by BERT to the Rescue which uses BERT for sentiment classification of the IMDB data set. The code from BERT to the Rescue can be found here. Since we are interested in single sentence classification, the relevant architecture is: In the figure above, the input for the BERT algorithm is a sequence of words and the outputs are the encoded word representations (vectors). For single sentence classification we use the vector representation of each word as the input to a classification model. Now let’s get started! IMPORT PACKAGES IMPORT PACKAGES import pandas as pd import numpy as np import torch.nn as nnfrom pytorch_pretrained_bert import BertTokenizer, BertModelimport torchfrom keras.preprocessing.sequence import pad_sequencesfrom sklearn.metrics import classification_report 2. DATA EXPLORATION First let’s read the data into a data frame and print the first five rows. We can also set the max number of display columns to ‘None’: pd.set_option('display.max_columns', None)df = pd.read_csv("fake_job_postings.csv")print(df.head()) For simplicity, let’s look at the ‘description’ and ‘fraudulent’ columns: df = df[['description', 'fraudulent']]print(df.head()) The target for our classification model is in the column ‘fraudulent’. To get an idea of the distribution in and kinds of values for ‘fraudulent’ we can use ‘Counter’ from the collections module: from collections import Counterprint(Counter(df['fraudulent'].values)) The ‘0’ value corresponds to a normal job posting and the ‘1’ value corresponds to a fraudulent posting. tWe see that the data is slightly imbalanced, meaning there are more normal job posting (17K) than fraudulent postings (866). Before proceeding, let’s drop ‘NaN’ values: df.dropna(inplace = True) Next we want to balance our data set such that we have an equal number of ‘fraudulent’ and ‘not fraudulent’ types. We also should randomly shuffle the targets: df_fraudulent= df[df['fraudulent'] == 1] df_normal = df[df['fraudulent'] == 0] df_normal = df_normal.sample(n=len(df_fraudulent))df = df_normal.append(df_fraudulent)df = df.sample(frac=1, random_state = 24).reset_index(drop=True) Again, verifying that we get the desired result: print(Counter(df['fraudulent'].values)) Next, we want to format the data such that it can be used as input into our BERT model. We split our data into training and testing sets: train_data = df.head(866)test_data = df.tail(866) We generate a list of dictionaries with ‘description’ and ‘fraudulent’ keys: train_data = [{'description': description, 'fraudulent': fraudulent } for description in list(train_data['description']) for fraudulent in list(train_data['fraudulent'])]test_data = [{'description': description, 'fraudulent': fraudulent } for description in list(test_data['description']) for fraudulent in list(test_data['fraudulent'])] Generate a list of tuples from the list of dictionaries : train_texts, train_labels = list(zip(*map(lambda d: (d['description'], d['fraudulent']), train_data)))test_texts, test_labels = list(zip(*map(lambda d: (d['description'], d['fraudulent']), test_data))) Generate tokens and token ids: tokenizer = BertTokenizer.from_pretrained('bert-base-uncased', do_lower_case=True)train_tokens = list(map(lambda t: ['[CLS]'] + tokenizer.tokenize(t)[:511], train_texts))test_tokens = list(map(lambda t: ['[CLS]'] + tokenizer.tokenize(t)[:511], test_texts))train_tokens_ids = list(map(tokenizer.convert_tokens_to_ids, train_tokens))test_tokens_ids = list(map(tokenizer.convert_tokens_to_ids, test_tokens))train_tokens_ids = pad_sequences(train_tokens_ids, maxlen=512, truncating="post", padding="post", dtype="int")test_tokens_ids = pad_sequences(test_tokens_ids, maxlen=512, truncating="post", padding="post", dtype="int") Notice we truncate the input strings to 512 characters because that is the maximum number of tokens BERT can handle. Finally, generate a boolean array based on the value of ‘fraudulent’ for our testing and training sets: train_y = np.array(train_labels) == 1test_y = np.array(test_labels) == 1 4. MODEL BUILDING We create our BERT classifier which contains an ‘initialization’ method and a ‘forward’ method that returns token probabilities: class BertBinaryClassifier(nn.Module): def __init__(self, dropout=0.1): super(BertBinaryClassifier, self).__init__() self.bert = BertModel.from_pretrained('bert-base-uncased') self.dropout = nn.Dropout(dropout) self.linear = nn.Linear(768, 1) self.sigmoid = nn.Sigmoid() def forward(self, tokens, masks=None): _, pooled_output = self.bert(tokens, attention_mask=masks, output_all_encoded_layers=False) dropout_output = self.dropout(pooled_output) linear_output = self.linear(dropout_output) proba = self.sigmoid(linear_output) return proba Next, we generate training and testing masks: train_masks = [[float(i > 0) for i in ii] for ii in train_tokens_ids]test_masks = [[float(i > 0) for i in ii] for ii in test_tokens_ids]train_masks_tensor = torch.tensor(train_masks)test_masks_tensor = torch.tensor(test_masks) Generate token tensors for training and testing: train_tokens_tensor = torch.tensor(train_tokens_ids)train_y_tensor = torch.tensor(train_y.reshape(-1, 1)).float()test_tokens_tensor = torch.tensor(test_tokens_ids)test_y_tensor = torch.tensor(test_y.reshape(-1, 1)).float() and finally, prepare our data loaders: BATCH_SIZE = 1train_dataset = torch.utils.data.TensorDataset(train_tokens_tensor, train_masks_tensor, train_y_tensor)train_sampler = torch.utils.data.RandomSampler(train_dataset)train_dataloader = torch.utils.data.DataLoader(train_dataset, sampler=train_sampler, batch_size=BATCH_SIZE)test_dataset = torch.utils.data.TensorDataset(test_tokens_tensor, test_masks_tensor, test_y_tensor)test_sampler = torch.utils.data.SequentialSampler(test_dataset)test_dataloader = torch.utils.data.DataLoader(test_dataset, sampler=test_sampler, batch_size=BATCH_SIZE) 5. FINE TUNING We use the Adam optimizer to minimize the Binary Cross Entropy loss and we train with a batch size of 1 for 1 EPOCHS: BATCH_SIZE = 1EPOCHS = 1bert_clf = BertBinaryClassifier()optimizer = torch.optim.Adam(bert_clf.parameters(), lr=3e-6)for epoch_num in range(EPOCHS): bert_clf.train() train_loss = 0 for step_num, batch_data in enumerate(train_dataloader): token_ids, masks, labels = tuple(t for t in batch_data) probas = bert_clf(token_ids, masks) loss_func = nn.BCELoss() batch_loss = loss_func(probas, labels) train_loss += batch_loss.item() bert_clf.zero_grad() batch_loss.backward() optimizer.step() print('Epoch: ', epoch_num + 1) print("\r" + "{0}/{1} loss: {2} ".format(step_num, len(train_data) / BATCH_SIZE, train_loss / (step_num + 1))) And we evaluate our model: bert_clf.eval()bert_predicted = []all_logits = []with torch.no_grad(): for step_num, batch_data in enumerate(test_dataloader):token_ids, masks, labels = tuple(t for t in batch_data)logits = bert_clf(token_ids, masks) loss_func = nn.BCELoss() loss = loss_func(logits, labels) numpy_logits = logits.cpu().detach().numpy() bert_predicted += list(numpy_logits[:, 0] > 0.5) all_logits += list(numpy_logits[:, 0]) print(classification_report(test_y, bert_predicted)) This model does a decent job at predicting real postings. The performance for predicting fraudulent posts isn’t as good but can be improved by increasing the number of epochs and further feature engineering. I encourage you to play around with hyper-parameter tuning and the training data to see if you can improve classification performance. To summarize, we built a BERT classifier to predict whether or not job postings were real or fraudulent. If you are interested in other applications of BERT, you can read Fake News Classification with BERT and Russian Troll Tweets: Classification with BERT. If you are interested in a thorough walkthrough of the BERT method, I encourage you to read BERT to the Rescue. The code from this post is available on GitHub. Thank you for reading!
[ { "code": null, "e": 515, "s": 172, "text": "Recently, The University of the Aegean published the Employment Scam Aegean Dataset. The data contains about 18K real-life job advertisements. The aim is to provide a clear picture of the Employment Scam problem to the research community. In this post, we will use BERT to classify fake job descriptions in the Employment Scam Aegean Dataset." }, { "code": null, "e": 576, "s": 515, "text": "Before we get started, let’s briefly review the BERT method." }, { "code": null, "e": 916, "s": 576, "text": "BERT stands for Bidirectional Encoder Representations from Transformers. The paper describing the BERT algorithm was published by Google and can be found here. BERT works by randomly masking word tokens and representing each masked word with a vector based on its context. The two applications of BERT are “pre-training” and “fine-tuning”." }, { "code": null, "e": 934, "s": 916, "text": "PRE-TRAINING BERT" }, { "code": null, "e": 1870, "s": 934, "text": "For the pre-training BERT algorithm, researchers trained two unsupervised learning tasks. The first task is described as Masked LM. This works by randomly masking 15% of a document and predicting those masked tokens. The second task is Next-Sentence Prediction (NSP). This is motivated by tasks such as Question Answering and Natural Language Inference. These tasks require models to accurately capture relationships between sentences. In order to tackle this, they pre-train for a binarized prediction task that can be trivially generated from any corpus in a single language. The example they give in the paper is as follows: if you have sentence A and B, 50% of the time A is labelled as “isNext” and the other 50% of the time it is a sentence that is randomly selected from the corpus and is labelled as “notNext”. Pre-training towards this tasks proves to be beneficial for Question Answering and Natural Language Inference tasks." }, { "code": null, "e": 1887, "s": 1870, "text": "FINE-TUNING BERT" }, { "code": null, "e": 2366, "s": 1887, "text": "Fine Tuning BERT works by encoding concatenated text pairs with self attention. Self-attention is the process of learning correlations between current words and previous words. An early application of this is in the Long Short-Term Memory (LSTM) paper (Dong2016) where researchers used self-attention to do machine reading. The nice thing about BERT is through encoding concatenated texts with self attention bidirectional cross attention between pairs of sentences is captured." }, { "code": null, "e": 2620, "s": 2366, "text": "In this article, we will apply BERT to predict whether or not a job posting is fraudulent. This post is inspired by BERT to the Rescue which uses BERT for sentiment classification of the IMDB data set. The code from BERT to the Rescue can be found here." }, { "code": null, "e": 2709, "s": 2620, "text": "Since we are interested in single sentence classification, the relevant architecture is:" }, { "code": null, "e": 2971, "s": 2709, "text": "In the figure above, the input for the BERT algorithm is a sequence of words and the outputs are the encoded word representations (vectors). For single sentence classification we use the vector representation of each word as the input to a classification model." }, { "code": null, "e": 2994, "s": 2971, "text": "Now let’s get started!" }, { "code": null, "e": 3010, "s": 2994, "text": "IMPORT PACKAGES" }, { "code": null, "e": 3026, "s": 3010, "text": "IMPORT PACKAGES" }, { "code": null, "e": 3262, "s": 3026, "text": "import pandas as pd import numpy as np import torch.nn as nnfrom pytorch_pretrained_bert import BertTokenizer, BertModelimport torchfrom keras.preprocessing.sequence import pad_sequencesfrom sklearn.metrics import classification_report" }, { "code": null, "e": 3282, "s": 3262, "text": "2. DATA EXPLORATION" }, { "code": null, "e": 3418, "s": 3282, "text": "First let’s read the data into a data frame and print the first five rows. We can also set the max number of display columns to ‘None’:" }, { "code": null, "e": 3518, "s": 3418, "text": "pd.set_option('display.max_columns', None)df = pd.read_csv(\"fake_job_postings.csv\")print(df.head())" }, { "code": null, "e": 3592, "s": 3518, "text": "For simplicity, let’s look at the ‘description’ and ‘fraudulent’ columns:" }, { "code": null, "e": 3647, "s": 3592, "text": "df = df[['description', 'fraudulent']]print(df.head())" }, { "code": null, "e": 3843, "s": 3647, "text": "The target for our classification model is in the column ‘fraudulent’. To get an idea of the distribution in and kinds of values for ‘fraudulent’ we can use ‘Counter’ from the collections module:" }, { "code": null, "e": 3914, "s": 3843, "text": "from collections import Counterprint(Counter(df['fraudulent'].values))" }, { "code": null, "e": 4145, "s": 3914, "text": "The ‘0’ value corresponds to a normal job posting and the ‘1’ value corresponds to a fraudulent posting. tWe see that the data is slightly imbalanced, meaning there are more normal job posting (17K) than fraudulent postings (866)." }, { "code": null, "e": 4189, "s": 4145, "text": "Before proceeding, let’s drop ‘NaN’ values:" }, { "code": null, "e": 4215, "s": 4189, "text": "df.dropna(inplace = True)" }, { "code": null, "e": 4375, "s": 4215, "text": "Next we want to balance our data set such that we have an equal number of ‘fraudulent’ and ‘not fraudulent’ types. We also should randomly shuffle the targets:" }, { "code": null, "e": 4605, "s": 4375, "text": "df_fraudulent= df[df['fraudulent'] == 1] df_normal = df[df['fraudulent'] == 0] df_normal = df_normal.sample(n=len(df_fraudulent))df = df_normal.append(df_fraudulent)df = df.sample(frac=1, random_state = 24).reset_index(drop=True)" }, { "code": null, "e": 4654, "s": 4605, "text": "Again, verifying that we get the desired result:" }, { "code": null, "e": 4694, "s": 4654, "text": "print(Counter(df['fraudulent'].values))" }, { "code": null, "e": 4832, "s": 4694, "text": "Next, we want to format the data such that it can be used as input into our BERT model. We split our data into training and testing sets:" }, { "code": null, "e": 4882, "s": 4832, "text": "train_data = df.head(866)test_data = df.tail(866)" }, { "code": null, "e": 4959, "s": 4882, "text": "We generate a list of dictionaries with ‘description’ and ‘fraudulent’ keys:" }, { "code": null, "e": 5297, "s": 4959, "text": "train_data = [{'description': description, 'fraudulent': fraudulent } for description in list(train_data['description']) for fraudulent in list(train_data['fraudulent'])]test_data = [{'description': description, 'fraudulent': fraudulent } for description in list(test_data['description']) for fraudulent in list(test_data['fraudulent'])]" }, { "code": null, "e": 5355, "s": 5297, "text": "Generate a list of tuples from the list of dictionaries :" }, { "code": null, "e": 5557, "s": 5355, "text": "train_texts, train_labels = list(zip(*map(lambda d: (d['description'], d['fraudulent']), train_data)))test_texts, test_labels = list(zip(*map(lambda d: (d['description'], d['fraudulent']), test_data)))" }, { "code": null, "e": 5588, "s": 5557, "text": "Generate tokens and token ids:" }, { "code": null, "e": 6211, "s": 5588, "text": "tokenizer = BertTokenizer.from_pretrained('bert-base-uncased', do_lower_case=True)train_tokens = list(map(lambda t: ['[CLS]'] + tokenizer.tokenize(t)[:511], train_texts))test_tokens = list(map(lambda t: ['[CLS]'] + tokenizer.tokenize(t)[:511], test_texts))train_tokens_ids = list(map(tokenizer.convert_tokens_to_ids, train_tokens))test_tokens_ids = list(map(tokenizer.convert_tokens_to_ids, test_tokens))train_tokens_ids = pad_sequences(train_tokens_ids, maxlen=512, truncating=\"post\", padding=\"post\", dtype=\"int\")test_tokens_ids = pad_sequences(test_tokens_ids, maxlen=512, truncating=\"post\", padding=\"post\", dtype=\"int\")" }, { "code": null, "e": 6328, "s": 6211, "text": "Notice we truncate the input strings to 512 characters because that is the maximum number of tokens BERT can handle." }, { "code": null, "e": 6432, "s": 6328, "text": "Finally, generate a boolean array based on the value of ‘fraudulent’ for our testing and training sets:" }, { "code": null, "e": 6505, "s": 6432, "text": "train_y = np.array(train_labels) == 1test_y = np.array(test_labels) == 1" }, { "code": null, "e": 6523, "s": 6505, "text": "4. MODEL BUILDING" }, { "code": null, "e": 6652, "s": 6523, "text": "We create our BERT classifier which contains an ‘initialization’ method and a ‘forward’ method that returns token probabilities:" }, { "code": null, "e": 7272, "s": 6652, "text": "class BertBinaryClassifier(nn.Module): def __init__(self, dropout=0.1): super(BertBinaryClassifier, self).__init__() self.bert = BertModel.from_pretrained('bert-base-uncased') self.dropout = nn.Dropout(dropout) self.linear = nn.Linear(768, 1) self.sigmoid = nn.Sigmoid() def forward(self, tokens, masks=None): _, pooled_output = self.bert(tokens, attention_mask=masks, output_all_encoded_layers=False) dropout_output = self.dropout(pooled_output) linear_output = self.linear(dropout_output) proba = self.sigmoid(linear_output) return proba" }, { "code": null, "e": 7318, "s": 7272, "text": "Next, we generate training and testing masks:" }, { "code": null, "e": 7545, "s": 7318, "text": "train_masks = [[float(i > 0) for i in ii] for ii in train_tokens_ids]test_masks = [[float(i > 0) for i in ii] for ii in test_tokens_ids]train_masks_tensor = torch.tensor(train_masks)test_masks_tensor = torch.tensor(test_masks)" }, { "code": null, "e": 7594, "s": 7545, "text": "Generate token tensors for training and testing:" }, { "code": null, "e": 7817, "s": 7594, "text": "train_tokens_tensor = torch.tensor(train_tokens_ids)train_y_tensor = torch.tensor(train_y.reshape(-1, 1)).float()test_tokens_tensor = torch.tensor(test_tokens_ids)test_y_tensor = torch.tensor(test_y.reshape(-1, 1)).float()" }, { "code": null, "e": 7856, "s": 7817, "text": "and finally, prepare our data loaders:" }, { "code": null, "e": 8414, "s": 7856, "text": "BATCH_SIZE = 1train_dataset = torch.utils.data.TensorDataset(train_tokens_tensor, train_masks_tensor, train_y_tensor)train_sampler = torch.utils.data.RandomSampler(train_dataset)train_dataloader = torch.utils.data.DataLoader(train_dataset, sampler=train_sampler, batch_size=BATCH_SIZE)test_dataset = torch.utils.data.TensorDataset(test_tokens_tensor, test_masks_tensor, test_y_tensor)test_sampler = torch.utils.data.SequentialSampler(test_dataset)test_dataloader = torch.utils.data.DataLoader(test_dataset, sampler=test_sampler, batch_size=BATCH_SIZE)" }, { "code": null, "e": 8429, "s": 8414, "text": "5. FINE TUNING" }, { "code": null, "e": 8547, "s": 8429, "text": "We use the Adam optimizer to minimize the Binary Cross Entropy loss and we train with a batch size of 1 for 1 EPOCHS:" }, { "code": null, "e": 9255, "s": 8547, "text": "BATCH_SIZE = 1EPOCHS = 1bert_clf = BertBinaryClassifier()optimizer = torch.optim.Adam(bert_clf.parameters(), lr=3e-6)for epoch_num in range(EPOCHS): bert_clf.train() train_loss = 0 for step_num, batch_data in enumerate(train_dataloader): token_ids, masks, labels = tuple(t for t in batch_data) probas = bert_clf(token_ids, masks) loss_func = nn.BCELoss() batch_loss = loss_func(probas, labels) train_loss += batch_loss.item() bert_clf.zero_grad() batch_loss.backward() optimizer.step() print('Epoch: ', epoch_num + 1) print(\"\\r\" + \"{0}/{1} loss: {2} \".format(step_num, len(train_data) / BATCH_SIZE, train_loss / (step_num + 1)))" }, { "code": null, "e": 9282, "s": 9255, "text": "And we evaluate our model:" }, { "code": null, "e": 9796, "s": 9282, "text": "bert_clf.eval()bert_predicted = []all_logits = []with torch.no_grad(): for step_num, batch_data in enumerate(test_dataloader):token_ids, masks, labels = tuple(t for t in batch_data)logits = bert_clf(token_ids, masks) loss_func = nn.BCELoss() loss = loss_func(logits, labels) numpy_logits = logits.cpu().detach().numpy() bert_predicted += list(numpy_logits[:, 0] > 0.5) all_logits += list(numpy_logits[:, 0]) print(classification_report(test_y, bert_predicted))" }, { "code": null, "e": 10139, "s": 9796, "text": "This model does a decent job at predicting real postings. The performance for predicting fraudulent posts isn’t as good but can be improved by increasing the number of epochs and further feature engineering. I encourage you to play around with hyper-parameter tuning and the training data to see if you can improve classification performance." } ]
Python Pandas - Reindexing
Reindexing changes the row labels and column labels of a DataFrame. To reindex means to conform the data to match a given set of labels along a particular axis. Multiple operations can be accomplished through indexing like − Reorder the existing data to match a new set of labels. Reorder the existing data to match a new set of labels. Insert missing value (NA) markers in label locations where no data for the label existed. Insert missing value (NA) markers in label locations where no data for the label existed. import pandas as pd import numpy as np N=20 df = pd.DataFrame({ 'A': pd.date_range(start='2016-01-01',periods=N,freq='D'), 'x': np.linspace(0,stop=N-1,num=N), 'y': np.random.rand(N), 'C': np.random.choice(['Low','Medium','High'],N).tolist(), 'D': np.random.normal(100, 10, size=(N)).tolist() }) #reindex the DataFrame df_reindexed = df.reindex(index=[0,2,5], columns=['A', 'C', 'B']) print df_reindexed Its output is as follows − A C B 0 2016-01-01 Low NaN 2 2016-01-03 High NaN 5 2016-01-06 Low NaN You may wish to take an object and reindex its axes to be labeled the same as another object. Consider the following example to understand the same. import pandas as pd import numpy as np df1 = pd.DataFrame(np.random.randn(10,3),columns=['col1','col2','col3']) df2 = pd.DataFrame(np.random.randn(7,3),columns=['col1','col2','col3']) df1 = df1.reindex_like(df2) print df1 Its output is as follows − col1 col2 col3 0 -2.467652 -1.211687 -0.391761 1 -0.287396 0.522350 0.562512 2 -0.255409 -0.483250 1.866258 3 -1.150467 -0.646493 -0.222462 4 0.152768 -2.056643 1.877233 5 -1.155997 1.528719 -1.343719 6 -1.015606 -1.245936 -0.295275 Note − Here, the df1 DataFrame is altered and reindexed like df2. The column names should be matched or else NAN will be added for the entire column label. reindex() takes an optional parameter method which is a filling method with values as follows − pad/ffill − Fill values forward pad/ffill − Fill values forward bfill/backfill − Fill values backward bfill/backfill − Fill values backward nearest − Fill from the nearest index values nearest − Fill from the nearest index values import pandas as pd import numpy as np df1 = pd.DataFrame(np.random.randn(6,3),columns=['col1','col2','col3']) df2 = pd.DataFrame(np.random.randn(2,3),columns=['col1','col2','col3']) # Padding NAN's print df2.reindex_like(df1) # Now Fill the NAN's with preceding Values print ("Data Frame with Forward Fill:") print df2.reindex_like(df1,method='ffill') Its output is as follows − col1 col2 col3 0 1.311620 -0.707176 0.599863 1 -0.423455 -0.700265 1.133371 2 NaN NaN NaN 3 NaN NaN NaN 4 NaN NaN NaN 5 NaN NaN NaN Data Frame with Forward Fill: col1 col2 col3 0 1.311620 -0.707176 0.599863 1 -0.423455 -0.700265 1.133371 2 -0.423455 -0.700265 1.133371 3 -0.423455 -0.700265 1.133371 4 -0.423455 -0.700265 1.133371 5 -0.423455 -0.700265 1.133371 Note − The last four rows are padded. The limit argument provides additional control over filling while reindexing. Limit specifies the maximum count of consecutive matches. Let us consider the following example to understand the same − import pandas as pd import numpy as np df1 = pd.DataFrame(np.random.randn(6,3),columns=['col1','col2','col3']) df2 = pd.DataFrame(np.random.randn(2,3),columns=['col1','col2','col3']) # Padding NAN's print df2.reindex_like(df1) # Now Fill the NAN's with preceding Values print ("Data Frame with Forward Fill limiting to 1:") print df2.reindex_like(df1,method='ffill',limit=1) Its output is as follows − col1 col2 col3 0 0.247784 2.128727 0.702576 1 -0.055713 -0.021732 -0.174577 2 NaN NaN NaN 3 NaN NaN NaN 4 NaN NaN NaN 5 NaN NaN NaN Data Frame with Forward Fill limiting to 1: col1 col2 col3 0 0.247784 2.128727 0.702576 1 -0.055713 -0.021732 -0.174577 2 -0.055713 -0.021732 -0.174577 3 NaN NaN NaN 4 NaN NaN NaN 5 NaN NaN NaN Note − Observe, only the 7th row is filled by the preceding 6th row. Then, the rows are left as they are. The rename() method allows you to relabel an axis based on some mapping (a dict or Series) or an arbitrary function. Let us consider the following example to understand this − import pandas as pd import numpy as np df1 = pd.DataFrame(np.random.randn(6,3),columns=['col1','col2','col3']) print df1 print ("After renaming the rows and columns:") print df1.rename(columns={'col1' : 'c1', 'col2' : 'c2'}, index = {0 : 'apple', 1 : 'banana', 2 : 'durian'}) Its output is as follows − col1 col2 col3 0 0.486791 0.105759 1.540122 1 -0.990237 1.007885 -0.217896 2 -0.483855 -1.645027 -1.194113 3 -0.122316 0.566277 -0.366028 4 -0.231524 -0.721172 -0.112007 5 0.438810 0.000225 0.435479 After renaming the rows and columns: c1 c2 col3 apple 0.486791 0.105759 1.540122 banana -0.990237 1.007885 -0.217896 durian -0.483855 -1.645027 -1.194113 3 -0.122316 0.566277 -0.366028 4 -0.231524 -0.721172 -0.112007 5 0.438810 0.000225 0.435479 The rename() method provides an inplace named parameter, which by default is False and copies the underlying data. Pass inplace=True to rename the data in place. 187 Lectures 17.5 hours Malhar Lathkar 55 Lectures 8 hours Arnab Chakraborty 136 Lectures 11 hours In28Minutes Official 75 Lectures 13 hours Eduonix Learning Solutions 70 Lectures 8.5 hours Lets Kode It 63 Lectures 6 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 2604, "s": 2443, "text": "Reindexing changes the row labels and column labels of a DataFrame. To reindex means to conform the data to match a given set of labels along a particular axis." }, { "code": null, "e": 2668, "s": 2604, "text": "Multiple operations can be accomplished through indexing like −" }, { "code": null, "e": 2724, "s": 2668, "text": "Reorder the existing data to match a new set of labels." }, { "code": null, "e": 2780, "s": 2724, "text": "Reorder the existing data to match a new set of labels." }, { "code": null, "e": 2870, "s": 2780, "text": "Insert missing value (NA) markers in label locations where no data for the label existed." }, { "code": null, "e": 2960, "s": 2870, "text": "Insert missing value (NA) markers in label locations where no data for the label existed." }, { "code": null, "e": 3382, "s": 2960, "text": "import pandas as pd\nimport numpy as np\n\nN=20\n\ndf = pd.DataFrame({\n 'A': pd.date_range(start='2016-01-01',periods=N,freq='D'),\n 'x': np.linspace(0,stop=N-1,num=N),\n 'y': np.random.rand(N),\n 'C': np.random.choice(['Low','Medium','High'],N).tolist(),\n 'D': np.random.normal(100, 10, size=(N)).tolist()\n})\n\n#reindex the DataFrame\ndf_reindexed = df.reindex(index=[0,2,5], columns=['A', 'C', 'B'])\n\nprint df_reindexed" }, { "code": null, "e": 3409, "s": 3382, "text": "Its output is as follows −" }, { "code": null, "e": 3510, "s": 3409, "text": " A C B\n0 2016-01-01 Low NaN\n2 2016-01-03 High NaN\n5 2016-01-06 Low NaN\n" }, { "code": null, "e": 3659, "s": 3510, "text": "You may wish to take an object and reindex its axes to be labeled the same as another object. Consider the following example to understand the same." }, { "code": null, "e": 3883, "s": 3659, "text": "import pandas as pd\nimport numpy as np\n\ndf1 = pd.DataFrame(np.random.randn(10,3),columns=['col1','col2','col3'])\ndf2 = pd.DataFrame(np.random.randn(7,3),columns=['col1','col2','col3'])\n\ndf1 = df1.reindex_like(df2)\nprint df1" }, { "code": null, "e": 3910, "s": 3883, "text": "Its output is as follows −" }, { "code": null, "e": 4239, "s": 3910, "text": " col1 col2 col3\n0 -2.467652 -1.211687 -0.391761\n1 -0.287396 0.522350 0.562512\n2 -0.255409 -0.483250 1.866258\n3 -1.150467 -0.646493 -0.222462\n4 0.152768 -2.056643 1.877233\n5 -1.155997 1.528719 -1.343719\n6 -1.015606 -1.245936 -0.295275\n" }, { "code": null, "e": 4395, "s": 4239, "text": "Note − Here, the df1 DataFrame is altered and reindexed like df2. The column names should be matched or else NAN will be added for the entire column label." }, { "code": null, "e": 4491, "s": 4395, "text": "reindex() takes an optional parameter method which is a filling method with values as\nfollows −" }, { "code": null, "e": 4523, "s": 4491, "text": "pad/ffill − Fill values forward" }, { "code": null, "e": 4555, "s": 4523, "text": "pad/ffill − Fill values forward" }, { "code": null, "e": 4593, "s": 4555, "text": "bfill/backfill − Fill values backward" }, { "code": null, "e": 4631, "s": 4593, "text": "bfill/backfill − Fill values backward" }, { "code": null, "e": 4676, "s": 4631, "text": "nearest − Fill from the nearest index values" }, { "code": null, "e": 4721, "s": 4676, "text": "nearest − Fill from the nearest index values" }, { "code": null, "e": 5077, "s": 4721, "text": "import pandas as pd\nimport numpy as np\n\ndf1 = pd.DataFrame(np.random.randn(6,3),columns=['col1','col2','col3'])\ndf2 = pd.DataFrame(np.random.randn(2,3),columns=['col1','col2','col3'])\n\n# Padding NAN's\nprint df2.reindex_like(df1)\n\n# Now Fill the NAN's with preceding Values\nprint (\"Data Frame with Forward Fill:\")\nprint df2.reindex_like(df1,method='ffill')" }, { "code": null, "e": 5104, "s": 5077, "text": "Its output is as follows −" }, { "code": null, "e": 5661, "s": 5104, "text": " col1 col2 col3\n0 1.311620 -0.707176 0.599863\n1 -0.423455 -0.700265 1.133371\n2 NaN NaN NaN\n3 NaN NaN NaN\n4 NaN NaN NaN\n5 NaN NaN NaN\n\nData Frame with Forward Fill:\n col1 col2 col3\n0 1.311620 -0.707176 0.599863\n1 -0.423455 -0.700265 1.133371\n2 -0.423455 -0.700265 1.133371\n3 -0.423455 -0.700265 1.133371\n4 -0.423455 -0.700265 1.133371\n5 -0.423455 -0.700265 1.133371\n" }, { "code": null, "e": 5699, "s": 5661, "text": "Note − The last four rows are padded." }, { "code": null, "e": 5898, "s": 5699, "text": "The limit argument provides additional control over filling while reindexing. Limit specifies the maximum count of consecutive matches. Let us consider the following example to understand the same −" }, { "code": null, "e": 6277, "s": 5898, "text": "import pandas as pd\nimport numpy as np\n \ndf1 = pd.DataFrame(np.random.randn(6,3),columns=['col1','col2','col3'])\ndf2 = pd.DataFrame(np.random.randn(2,3),columns=['col1','col2','col3'])\n\n# Padding NAN's\nprint df2.reindex_like(df1)\n\n# Now Fill the NAN's with preceding Values\nprint (\"Data Frame with Forward Fill limiting to 1:\")\nprint df2.reindex_like(df1,method='ffill',limit=1)" }, { "code": null, "e": 6304, "s": 6277, "text": "Its output is as follows −" }, { "code": null, "e": 6882, "s": 6304, "text": " col1 col2 col3\n0 0.247784 2.128727 0.702576\n1 -0.055713 -0.021732 -0.174577\n2 NaN NaN NaN\n3 NaN NaN NaN\n4 NaN NaN NaN\n5 NaN NaN NaN\n\nData Frame with Forward Fill limiting to 1:\n col1 col2 col3\n0 0.247784 2.128727 0.702576\n1 -0.055713 -0.021732 -0.174577\n2 -0.055713 -0.021732 -0.174577\n3 NaN NaN NaN\n4 NaN NaN NaN\n5 NaN NaN NaN\n" }, { "code": null, "e": 6988, "s": 6882, "text": "Note − Observe, only the 7th row is filled by the preceding 6th row. Then, the rows are left as they are." }, { "code": null, "e": 7105, "s": 6988, "text": "The rename() method allows you to relabel an axis based on some mapping (a dict or Series) or an arbitrary function." }, { "code": null, "e": 7164, "s": 7105, "text": "Let us consider the following example to understand this −" }, { "code": null, "e": 7442, "s": 7164, "text": "import pandas as pd\nimport numpy as np\n\ndf1 = pd.DataFrame(np.random.randn(6,3),columns=['col1','col2','col3'])\nprint df1\n\nprint (\"After renaming the rows and columns:\")\nprint df1.rename(columns={'col1' : 'c1', 'col2' : 'c2'},\nindex = {0 : 'apple', 1 : 'banana', 2 : 'durian'})" }, { "code": null, "e": 7469, "s": 7442, "text": "Its output is as follows −" }, { "code": null, "e": 8075, "s": 7469, "text": " col1 col2 col3\n0 0.486791 0.105759 1.540122\n1 -0.990237 1.007885 -0.217896\n2 -0.483855 -1.645027 -1.194113\n3 -0.122316 0.566277 -0.366028\n4 -0.231524 -0.721172 -0.112007\n5 0.438810 0.000225 0.435479\n\nAfter renaming the rows and columns:\n c1 c2 col3\napple 0.486791 0.105759 1.540122\nbanana -0.990237 1.007885 -0.217896\ndurian -0.483855 -1.645027 -1.194113\n3 -0.122316 0.566277 -0.366028\n4 -0.231524 -0.721172 -0.112007\n5 0.438810 0.000225 0.435479\n" }, { "code": null, "e": 8237, "s": 8075, "text": "The rename() method provides an inplace named parameter, which by default is False and copies the underlying data. Pass inplace=True to rename the data in place." }, { "code": null, "e": 8274, "s": 8237, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 8290, "s": 8274, "text": " Malhar Lathkar" }, { "code": null, "e": 8323, "s": 8290, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 8342, "s": 8323, "text": " Arnab Chakraborty" }, { "code": null, "e": 8377, "s": 8342, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 8399, "s": 8377, "text": " In28Minutes Official" }, { "code": null, "e": 8433, "s": 8399, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 8461, "s": 8433, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 8496, "s": 8461, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 8510, "s": 8496, "text": " Lets Kode It" }, { "code": null, "e": 8543, "s": 8510, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 8560, "s": 8543, "text": " Abhilash Nelson" }, { "code": null, "e": 8567, "s": 8560, "text": " Print" }, { "code": null, "e": 8578, "s": 8567, "text": " Add Notes" } ]
Batch Script - Moving Folders
For moving folders, Batch Script provides the MOVE command. MOVE [/Y | /-Y] [drive:][path]filename1[,...] destination Following are the description of the options which can be presented to the DEL command. [drive:][path]filename1 Specifies the location and name of the file or files you want to move destination Specifies the new location of the file. Destination can consist of a drive letter and colon, a directory name, or a combination. If you are moving only one file, you can also include a filename if you want to rename the file when you move it. [drive:][path]dirname1 Specifies the directory you want to rename. dirname2 Specifies the new name of the directory. /Y Suppresses prompting to confirm you want to overwrite an existing destination file. /-Y Causes prompting to confirm you want to overwrite an existing destination file. Let’s look at some examples of moving folders. move *.* C:\Example The above command will move all files from the current directory to the folder C:\Example. move *.txt C:\Example The above command will move all files with the txt extension from the current directory to the folder C:\Example. move C:\old\*.* C:\Example The above command will move all files from the folder called ‘old’ in C drive to the folder C:\Example. Print Add Notes Bookmark this page
[ { "code": null, "e": 2229, "s": 2169, "text": "For moving folders, Batch Script provides the MOVE command." }, { "code": null, "e": 2288, "s": 2229, "text": "MOVE [/Y | /-Y] [drive:][path]filename1[,...] destination\n" }, { "code": null, "e": 2376, "s": 2288, "text": "Following are the description of the options which can be presented to the DEL command." }, { "code": null, "e": 2400, "s": 2376, "text": "[drive:][path]filename1" }, { "code": null, "e": 2470, "s": 2400, "text": "Specifies the location and name of the file or files you want to move" }, { "code": null, "e": 2482, "s": 2470, "text": "destination" }, { "code": null, "e": 2725, "s": 2482, "text": "Specifies the new location of the file. Destination can consist of a drive letter and colon, a directory name, or a combination. If you are moving only one file, you can also include a filename if you want to rename the file when you move it." }, { "code": null, "e": 2748, "s": 2725, "text": "[drive:][path]dirname1" }, { "code": null, "e": 2792, "s": 2748, "text": "Specifies the directory you want to rename." }, { "code": null, "e": 2801, "s": 2792, "text": "dirname2" }, { "code": null, "e": 2842, "s": 2801, "text": "Specifies the new name of the directory." }, { "code": null, "e": 2845, "s": 2842, "text": "/Y" }, { "code": null, "e": 2929, "s": 2845, "text": "Suppresses prompting to confirm you want to overwrite an existing destination file." }, { "code": null, "e": 2933, "s": 2929, "text": "/-Y" }, { "code": null, "e": 3013, "s": 2933, "text": "Causes prompting to confirm you want to overwrite an existing destination file." }, { "code": null, "e": 3060, "s": 3013, "text": "Let’s look at some examples of moving folders." }, { "code": null, "e": 3081, "s": 3060, "text": "move *.* C:\\Example\n" }, { "code": null, "e": 3172, "s": 3081, "text": "The above command will move all files from the current directory to the folder C:\\Example." }, { "code": null, "e": 3195, "s": 3172, "text": "move *.txt C:\\Example\n" }, { "code": null, "e": 3309, "s": 3195, "text": "The above command will move all files with the txt extension from the current directory to the folder C:\\Example." }, { "code": null, "e": 3337, "s": 3309, "text": "move C:\\old\\*.* C:\\Example\n" }, { "code": null, "e": 3441, "s": 3337, "text": "The above command will move all files from the folder called ‘old’ in C drive to the folder C:\\Example." }, { "code": null, "e": 3448, "s": 3441, "text": " Print" }, { "code": null, "e": 3459, "s": 3448, "text": " Add Notes" } ]
VBA - Text Files
You can also read Excel File and write the contents of the cell into a Text File using VBA. VBA allows the users to work with text files using two methods − File System Object using Write Command As the name suggests, FSOs help the developers to work with drives, folders, and files. In this section, we will discuss how to use a FSO. Drive Drive is an Object. Contains methods and properties that allow you to gather information about a drive attached to the system. Drives Drives is a Collection. It provides a list of the drives attached to the system, either physically or logically. File File is an Object. It contains methods and properties that allow developers to create, delete, or move a file. Files Files is a Collection. It provides a list of all the files contained within a folder. Folder Folder is an Object. It provides methods and properties that allow the developers to create, delete, or move folders. Folders Folders is a Collection. It provides a list of all the folders within a folder. TextStream TextStream is an Object. It enables the developers to read and write text files. Drive is an object, which provides access to the properties of a particular disk drive or network share. Following properties are supported by Drive object − AvailableSpace DriveLetter DriveType FileSystem FreeSpace IsReady Path RootFolder SerialNumber ShareName TotalSize VolumeName Step 1 − Before proceeding to scripting using FSO, we should enable Microsoft Scripting Runtime. To do the same, navigate to Tools → References as shown in the following screenshot. Step 2 − Add "Microsoft Scripting RunTime" and Click OK. Step 3 − Add Data that you would like to write in a Text File and add a Command Button. Step 4 − Now it is time to Script. Private Sub fn_write_to_text_Click() Dim FilePath As String Dim CellData As String Dim LastCol As Long Dim LastRow As Long Dim fso As FileSystemObject Set fso = New FileSystemObject Dim stream As TextStream LastCol = ActiveSheet.UsedRange.Columns.Count LastRow = ActiveSheet.UsedRange.Rows.Count ' Create a TextStream. Set stream = fso.OpenTextFile("D:\Try\Support.log", ForWriting, True) CellData = "" For i = 1 To LastRow For j = 1 To LastCol CellData = Trim(ActiveCell(i, j).Value) stream.WriteLine "The Value at location (" & i & "," & j & ")" & CellData Next j Next i stream.Close MsgBox ("Job Done") End Sub When executing the script, ensure that you place the cursor in the first cell of the worksheet. The Support.log file is created as shown in the following screenshot under "D:\Try". The Contents of the file are shown in the following screenshot. Unlike FSO, we need NOT add any references, however, we will NOT be able to work with drives, files and folders. We will be able to just add the stream to the text file. Private Sub fn_write_to_text_Click() Dim FilePath As String Dim CellData As String Dim LastCol As Long Dim LastRow As Long LastCol = ActiveSheet.UsedRange.Columns.Count LastRow = ActiveSheet.UsedRange.Rows.Count FilePath = "D:\Try\write.txt" Open FilePath For Output As #2 CellData = "" For i = 1 To LastRow For j = 1 To LastCol CellData = "The Value at location (" & i & "," & j & ")" & Trim(ActiveCell(i, j).Value) Write #2, CellData Next j Next i Close #2 MsgBox ("Job Done") End Sub Upon executing the script, the "write.txt" file is created in the location "D:\Try" as shown in the following screenshot. The contents of the file are shown in the following screenshot. 101 Lectures 6 hours Pavan Lalwani 41 Lectures 3 hours Arnold Higuit 80 Lectures 5.5 hours Prashant Panchal 25 Lectures 2 hours Prashant Panchal 26 Lectures 2 hours Arnold Higuit 92 Lectures 10.5 hours Vijay Kumar Parvatha Reddy Print Add Notes Bookmark this page
[ { "code": null, "e": 2092, "s": 1935, "text": "You can also read Excel File and write the contents of the cell into a Text File using VBA. VBA allows the users to work with text files using two methods −" }, { "code": null, "e": 2111, "s": 2092, "text": "File System Object" }, { "code": null, "e": 2131, "s": 2111, "text": "using Write Command" }, { "code": null, "e": 2270, "s": 2131, "text": "As the name suggests, FSOs help the developers to work with drives, folders, and files. In this section, we will discuss how to use a FSO." }, { "code": null, "e": 2276, "s": 2270, "text": "Drive" }, { "code": null, "e": 2403, "s": 2276, "text": "Drive is an Object. Contains methods and properties that allow you to gather information about a drive attached to the system." }, { "code": null, "e": 2410, "s": 2403, "text": "Drives" }, { "code": null, "e": 2523, "s": 2410, "text": "Drives is a Collection. It provides a list of the drives attached to the system, either physically or logically." }, { "code": null, "e": 2528, "s": 2523, "text": "File" }, { "code": null, "e": 2639, "s": 2528, "text": "File is an Object. It contains methods and properties that allow developers to create, delete, or move a file." }, { "code": null, "e": 2645, "s": 2639, "text": "Files" }, { "code": null, "e": 2731, "s": 2645, "text": "Files is a Collection. It provides a list of all the files contained within a folder." }, { "code": null, "e": 2738, "s": 2731, "text": "Folder" }, { "code": null, "e": 2856, "s": 2738, "text": "Folder is an Object. It provides methods and properties that allow the developers to create, delete, or move folders." }, { "code": null, "e": 2864, "s": 2856, "text": "Folders" }, { "code": null, "e": 2944, "s": 2864, "text": "Folders is a Collection. It provides a list of all the folders within a folder." }, { "code": null, "e": 2955, "s": 2944, "text": "TextStream" }, { "code": null, "e": 3036, "s": 2955, "text": "TextStream is an Object. It enables the developers to read and write text files." }, { "code": null, "e": 3194, "s": 3036, "text": "Drive is an object, which provides access to the properties of a particular disk drive or network share. Following properties are supported by Drive object −" }, { "code": null, "e": 3209, "s": 3194, "text": "AvailableSpace" }, { "code": null, "e": 3221, "s": 3209, "text": "DriveLetter" }, { "code": null, "e": 3231, "s": 3221, "text": "DriveType" }, { "code": null, "e": 3242, "s": 3231, "text": "FileSystem" }, { "code": null, "e": 3252, "s": 3242, "text": "FreeSpace" }, { "code": null, "e": 3260, "s": 3252, "text": "IsReady" }, { "code": null, "e": 3265, "s": 3260, "text": "Path" }, { "code": null, "e": 3276, "s": 3265, "text": "RootFolder" }, { "code": null, "e": 3289, "s": 3276, "text": "SerialNumber" }, { "code": null, "e": 3299, "s": 3289, "text": "ShareName" }, { "code": null, "e": 3309, "s": 3299, "text": "TotalSize" }, { "code": null, "e": 3320, "s": 3309, "text": "VolumeName" }, { "code": null, "e": 3502, "s": 3320, "text": "Step 1 − Before proceeding to scripting using FSO, we should enable Microsoft Scripting Runtime. To do the same, navigate to Tools → References as shown in the following screenshot." }, { "code": null, "e": 3559, "s": 3502, "text": "Step 2 − Add \"Microsoft Scripting RunTime\" and Click OK." }, { "code": null, "e": 3647, "s": 3559, "text": "Step 3 − Add Data that you would like to write in a Text File and add a Command Button." }, { "code": null, "e": 3682, "s": 3647, "text": "Step 4 − Now it is time to Script." }, { "code": null, "e": 4394, "s": 3682, "text": "Private Sub fn_write_to_text_Click()\n Dim FilePath As String\n Dim CellData As String\n Dim LastCol As Long\n Dim LastRow As Long\n \n Dim fso As FileSystemObject\n Set fso = New FileSystemObject\n Dim stream As TextStream\n \n LastCol = ActiveSheet.UsedRange.Columns.Count\n LastRow = ActiveSheet.UsedRange.Rows.Count\n \n ' Create a TextStream.\n Set stream = fso.OpenTextFile(\"D:\\Try\\Support.log\", ForWriting, True)\n \n CellData = \"\"\n \n For i = 1 To LastRow\n For j = 1 To LastCol\n CellData = Trim(ActiveCell(i, j).Value)\n stream.WriteLine \"The Value at location (\" & i & \",\" & j & \")\" & CellData\n Next j\n Next i\n \n stream.Close\n MsgBox (\"Job Done\")\nEnd Sub" }, { "code": null, "e": 4575, "s": 4394, "text": "When executing the script, ensure that you place the cursor in the first cell of the worksheet. The Support.log file is created as shown in the following screenshot under \"D:\\Try\"." }, { "code": null, "e": 4639, "s": 4575, "text": "The Contents of the file are shown in the following screenshot." }, { "code": null, "e": 4809, "s": 4639, "text": "Unlike FSO, we need NOT add any references, however, we will NOT be able to work with drives, files and folders. We will be able to just add the stream to the text file." }, { "code": null, "e": 5379, "s": 4809, "text": "Private Sub fn_write_to_text_Click()\n Dim FilePath As String\n Dim CellData As String\n Dim LastCol As Long\n Dim LastRow As Long\n \n LastCol = ActiveSheet.UsedRange.Columns.Count\n LastRow = ActiveSheet.UsedRange.Rows.Count\n \n FilePath = \"D:\\Try\\write.txt\"\n Open FilePath For Output As #2\n \n CellData = \"\"\n For i = 1 To LastRow\n For j = 1 To LastCol\n CellData = \"The Value at location (\" & i & \",\" & j & \")\" & Trim(ActiveCell(i, j).Value)\n Write #2, CellData\n Next j\n Next i\n \n Close #2\n MsgBox (\"Job Done\")\nEnd Sub" }, { "code": null, "e": 5501, "s": 5379, "text": "Upon executing the script, the \"write.txt\" file is created in the location \"D:\\Try\" as shown in the following screenshot." }, { "code": null, "e": 5565, "s": 5501, "text": "The contents of the file are shown in the following screenshot." }, { "code": null, "e": 5599, "s": 5565, "text": "\n 101 Lectures \n 6 hours \n" }, { "code": null, "e": 5614, "s": 5599, "text": " Pavan Lalwani" }, { "code": null, "e": 5647, "s": 5614, "text": "\n 41 Lectures \n 3 hours \n" }, { "code": null, "e": 5662, "s": 5647, "text": " Arnold Higuit" }, { "code": null, "e": 5697, "s": 5662, "text": "\n 80 Lectures \n 5.5 hours \n" }, { "code": null, "e": 5715, "s": 5697, "text": " Prashant Panchal" }, { "code": null, "e": 5748, "s": 5715, "text": "\n 25 Lectures \n 2 hours \n" }, { "code": null, "e": 5766, "s": 5748, "text": " Prashant Panchal" }, { "code": null, "e": 5799, "s": 5766, "text": "\n 26 Lectures \n 2 hours \n" }, { "code": null, "e": 5814, "s": 5799, "text": " Arnold Higuit" }, { "code": null, "e": 5850, "s": 5814, "text": "\n 92 Lectures \n 10.5 hours \n" }, { "code": null, "e": 5878, "s": 5850, "text": " Vijay Kumar Parvatha Reddy" }, { "code": null, "e": 5885, "s": 5878, "text": " Print" }, { "code": null, "e": 5896, "s": 5885, "text": " Add Notes" } ]
Check if a large number is divisible by 11 or not in C++
Here we will see how to check a number is divisible by 11 or not. In this case the number is very large number. So we put the number as string. To check whether a number is divisible by 11, if the sum of odd position values and the sum of even position values are same, then the number is divisible by 11. Live Demo #include <bits/stdc++.h> using namespace std; bool isDiv11(string num){ int n = num.length(); long odd_sum = 0, even_sum = 0; for(int i = 0; i < n; i++){ if(i % 2 == 0){ odd_sum += num[i] - '0'; } else { even_sum += num[i] - '0'; } } if(odd_sum == even_sum) return true; return false; } int main() { string num = "1234567589333892"; if(isDiv11(num)){ cout << "Divisible"; } else { cout << "Not Divisible"; } } Divisible
[ { "code": null, "e": 1206, "s": 1062, "text": "Here we will see how to check a number is divisible by 11 or not. In this case the number is very large number. So we put the number as string." }, { "code": null, "e": 1368, "s": 1206, "text": "To check whether a number is divisible by 11, if the sum of odd position values and the sum of even position values are same, then the number is divisible by 11." }, { "code": null, "e": 1379, "s": 1368, "text": " Live Demo" }, { "code": null, "e": 1876, "s": 1379, "text": "#include <bits/stdc++.h>\nusing namespace std;\nbool isDiv11(string num){\n int n = num.length();\n long odd_sum = 0, even_sum = 0;\n for(int i = 0; i < n; i++){\n if(i % 2 == 0){\n odd_sum += num[i] - '0';\n } else {\n even_sum += num[i] - '0';\n }\n }\n if(odd_sum == even_sum)\n return true;\n return false;\n}\nint main() {\n string num = \"1234567589333892\";\n if(isDiv11(num)){\n cout << \"Divisible\";\n } else {\n cout << \"Not Divisible\";\n }\n}" }, { "code": null, "e": 1886, "s": 1876, "text": "Divisible" } ]
Function to compute factorial of a number in JavaScript
We are required to write a simple JavaScript function that takes in a Number, say n and computes its factorial. Maintain a count and a result variable. We will keep multiplying the count into result and simultaneously decreasing the count by 1, until it reaches 1. And then finally we return the result. Therefore, let’s write the code for this function − The code for this will be − const num = 14; const factorial = num => { let res = 1; for(let i = num; i > 1; i--){ res *= i; }; return res; }; console.log(factorial(num)); The output in the console will be − 87178291200
[ { "code": null, "e": 1174, "s": 1062, "text": "We are required to write a simple JavaScript function that takes in a Number, say n and\ncomputes its factorial." }, { "code": null, "e": 1327, "s": 1174, "text": "Maintain a count and a result variable. We will keep multiplying the count into result and\nsimultaneously decreasing the count by 1, until it reaches 1." }, { "code": null, "e": 1366, "s": 1327, "text": "And then finally we return the result." }, { "code": null, "e": 1418, "s": 1366, "text": "Therefore, let’s write the code for this function −" }, { "code": null, "e": 1446, "s": 1418, "text": "The code for this will be −" }, { "code": null, "e": 1607, "s": 1446, "text": "const num = 14;\nconst factorial = num => {\n let res = 1;\n for(let i = num; i > 1; i--){\n res *= i;\n };\n return res;\n};\nconsole.log(factorial(num));" }, { "code": null, "e": 1643, "s": 1607, "text": "The output in the console will be −" }, { "code": null, "e": 1655, "s": 1643, "text": "87178291200" } ]
jQuery UI menu collapse() Method - GeeksforGeeks
24 Jan, 2021 jQuery UI consists of GUI widgets, visual effects, and themes implemented using jQuery, CSS, and HTML. jQuery UI is great for building UI interfaces for the webpages. jQuery UI menu is a themeable menu that is used with mouse and keyboard interactions for navigating between pages. In this article, we will use the collapse option to collapse the active sub-menu. Syntax: $(".selector").menu( "collapse" ); Approach: First, add jQuery UI scripts needed for your project. <link href = “https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css” rel = “stylesheet”> <script src = “https://code.jquery.com/jquery-1.10.2.js”></script> <script src = “https://code.jquery.com/ui/1.10.4/jquery-ui.js”></script> Example 1: In this example, we will be using the collapse option for the menu() method. HTML <!doctype html><html lang="en"> <head> <meta charset="utf-8"> <link href="https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel="stylesheet"> <script src="https://code.jquery.com/jquery-1.10.2.js"></script> <script src="https://code.jquery.com/ui/1.10.4/jquery-ui.js"> </script> <style> .ui-menu { width: 200px; } </style> <script> $(function() { var menu = $("#gfg").menu(); $("#gfg").menu() $(menu).mouseleave(function() { menu.menu('collapse'); }); }); </script></head> <body> <h1>jQuery UI | menu collapse method</h1> <ul id="gfg"> <li><a href="#">Menu</a> <ul> <li><a href="#">Submenu</a> <ul> <li><a href="#"> Sub-Submenu </a></li> </ul> </li> </ul> </li> </ul></body> </html> Output: With collapse method. Without collapse method. In the following image, please notice that the sub-sub menu is not getting collapsed as in the first image. Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. jQuery-UI HTML JQuery Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills HTML | <img> align Attribute Types of CSS (Cascading Style Sheet) How to set the default value for an HTML <select> element ? JQuery | Set the value of an input text field Form validation using jQuery How to change selected value of a drop-down list using jQuery? How to change the background color after clicking the button in JavaScript ? How to add options to a select element using jQuery?
[ { "code": null, "e": 50960, "s": 50932, "text": "\n24 Jan, 2021" }, { "code": null, "e": 51325, "s": 50960, "text": "jQuery UI consists of GUI widgets, visual effects, and themes implemented using jQuery, CSS, and HTML. jQuery UI is great for building UI interfaces for the webpages. jQuery UI menu is a themeable menu that is used with mouse and keyboard interactions for navigating between pages. In this article, we will use the collapse option to collapse the active sub-menu. " }, { "code": null, "e": 51333, "s": 51325, "text": "Syntax:" }, { "code": null, "e": 51368, "s": 51333, "text": "$(\".selector\").menu( \"collapse\" );" }, { "code": null, "e": 51378, "s": 51368, "text": "Approach:" }, { "code": null, "e": 51432, "s": 51378, "text": "First, add jQuery UI scripts needed for your project." }, { "code": null, "e": 51535, "s": 51432, "text": "<link href = “https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css” rel = “stylesheet”>" }, { "code": null, "e": 51602, "s": 51535, "text": "<script src = “https://code.jquery.com/jquery-1.10.2.js”></script>" }, { "code": null, "e": 51675, "s": 51602, "text": "<script src = “https://code.jquery.com/ui/1.10.4/jquery-ui.js”></script>" }, { "code": null, "e": 51764, "s": 51675, "text": "Example 1: In this example, we will be using the collapse option for the menu() method. " }, { "code": null, "e": 51769, "s": 51764, "text": "HTML" }, { "code": "<!doctype html><html lang=\"en\"> <head> <meta charset=\"utf-8\"> <link href=\"https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css\" rel=\"stylesheet\"> <script src=\"https://code.jquery.com/jquery-1.10.2.js\"></script> <script src=\"https://code.jquery.com/ui/1.10.4/jquery-ui.js\"> </script> <style> .ui-menu { width: 200px; } </style> <script> $(function() { var menu = $(\"#gfg\").menu(); $(\"#gfg\").menu() $(menu).mouseleave(function() { menu.menu('collapse'); }); }); </script></head> <body> <h1>jQuery UI | menu collapse method</h1> <ul id=\"gfg\"> <li><a href=\"#\">Menu</a> <ul> <li><a href=\"#\">Submenu</a> <ul> <li><a href=\"#\"> Sub-Submenu </a></li> </ul> </li> </ul> </li> </ul></body> </html>", "e": 52802, "s": 51769, "text": null }, { "code": null, "e": 52811, "s": 52802, "text": "Output: " }, { "code": null, "e": 52833, "s": 52811, "text": "With collapse method." }, { "code": null, "e": 52966, "s": 52833, "text": "Without collapse method. In the following image, please notice that the sub-sub menu is not getting collapsed as in the first image." }, { "code": null, "e": 53103, "s": 52966, "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": 53113, "s": 53103, "text": "jQuery-UI" }, { "code": null, "e": 53118, "s": 53113, "text": "HTML" }, { "code": null, "e": 53125, "s": 53118, "text": "JQuery" }, { "code": null, "e": 53142, "s": 53125, "text": "Web Technologies" }, { "code": null, "e": 53147, "s": 53142, "text": "HTML" }, { "code": null, "e": 53245, "s": 53147, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 53254, "s": 53245, "text": "Comments" }, { "code": null, "e": 53267, "s": 53254, "text": "Old Comments" }, { "code": null, "e": 53317, "s": 53267, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 53379, "s": 53317, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 53408, "s": 53379, "text": "HTML | <img> align Attribute" }, { "code": null, "e": 53445, "s": 53408, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 53505, "s": 53445, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 53551, "s": 53505, "text": "JQuery | Set the value of an input text field" }, { "code": null, "e": 53580, "s": 53551, "text": "Form validation using jQuery" }, { "code": null, "e": 53643, "s": 53580, "text": "How to change selected value of a drop-down list using jQuery?" }, { "code": null, "e": 53720, "s": 53643, "text": "How to change the background color after clicking the button in JavaScript ?" } ]
C Program to check if a number is divisible by sum of its digits
Given a number n we have to check whether the sum of its digits divide the number n or not. To find out we have to sum all the numbers starting from the unit place and then divide the number with the final sum. Like we have a number “521” so we have to find the sum of its digit that will be “5 + 2 + 1 = 8” but 521 is not divisible by 8 without leaving any remainder. Let’s take another example “60” where “6+0 = 6” which can divide 60 and will not leave any remainder. Input: 55 Output: No Explanation: 5+5 = 10; 55 not divisible by 10 Input: 12 Output: Yes Explanation: 1+2 = 3; 12 is divisible by 3 The approach used below is as follows − To solve this problem we have to fetch each digit from the input and find the sum of each digit of a number, then check whether it is dividing the number or not. Take input Take each number from the unit place using and add it to a sum variable which should be initially zero Divide the input with the sum of the number. Return the result. In function int isDivisible(long int num) Step 1-> Declare and initialize temp = num, sum = 0 Step 2-> Loop While num Declare and initialize k as num % 10 Set sum as sum + k Set num as num / 10 End Loop Step 3-> If temp % sum == 0 then, Return 1 Step 4-> Return 0 End function In main() Step 1-> Declare and initialize num as 55 Step 2-> If isDivisible(num) then, Print "yes " Step 3-> Else Print "no " Live Demo #include <stdio.h> // This function will check // whether the given number is divisible // by sum of its digits int isDivisible(long int num) { long int temp = num; // Find sum of digits int sum = 0; while (num) { int k = num % 10; sum = sum + k; num = num / 10; } // check if sum of digits divides num if (temp % sum == 0) return 1; return 0; } int main() { long int num = 55; if(isDivisible(num)) printf("yes\n"); else printf("no\n"); return 0; } If run the above code it will generate the following output − No
[ { "code": null, "e": 1273, "s": 1062, "text": "Given a number n we have to check whether the sum of its digits divide the number n or not. To find out we have to sum all the numbers starting from the unit place and then divide the number with the final sum." }, { "code": null, "e": 1431, "s": 1273, "text": "Like we have a number “521” so we have to find the sum of its digit that will be “5 + 2 + 1 = 8” but 521 is not divisible by 8 without leaving any remainder." }, { "code": null, "e": 1533, "s": 1431, "text": "Let’s take another example “60” where “6+0 = 6” which can divide 60 and will not leave any remainder." }, { "code": null, "e": 1665, "s": 1533, "text": "Input: 55\nOutput: No\nExplanation: 5+5 = 10; 55 not divisible by 10\nInput: 12\nOutput: Yes\nExplanation: 1+2 = 3; 12 is divisible by 3" }, { "code": null, "e": 1705, "s": 1665, "text": "The approach used below is as follows −" }, { "code": null, "e": 1867, "s": 1705, "text": "To solve this problem we have to fetch each digit from the input and find the sum of each digit of a number, then check whether it is dividing the number or not." }, { "code": null, "e": 1878, "s": 1867, "text": "Take input" }, { "code": null, "e": 1981, "s": 1878, "text": "Take each number from the unit place using and add it to a sum variable which should be initially zero" }, { "code": null, "e": 2026, "s": 1981, "text": "Divide the input with the sum of the number." }, { "code": null, "e": 2045, "s": 2026, "text": "Return the result." }, { "code": null, "e": 2505, "s": 2045, "text": "In function int isDivisible(long int num)\n Step 1-> Declare and initialize temp = num, sum = 0\n Step 2-> Loop While num\n Declare and initialize k as num % 10\n Set sum as sum + k\n Set num as num / 10\n End Loop\n Step 3-> If temp % sum == 0 then,\n Return 1\n Step 4-> Return 0\n End function\nIn main()\n Step 1-> Declare and initialize num as 55\n Step 2-> If isDivisible(num) then,\n Print \"yes \"\n Step 3-> Else\nPrint \"no \"" }, { "code": null, "e": 2516, "s": 2505, "text": " Live Demo" }, { "code": null, "e": 3043, "s": 2516, "text": "#include <stdio.h>\n// This function will check\n// whether the given number is divisible\n// by sum of its digits\nint isDivisible(long int num) {\n long int temp = num;\n // Find sum of digits\n int sum = 0;\n while (num) {\n int k = num % 10;\n sum = sum + k;\n num = num / 10;\n }\n // check if sum of digits divides num\n if (temp % sum == 0)\n return 1;\n return 0;\n}\nint main() {\n long int num = 55;\n if(isDivisible(num))\n printf(\"yes\\n\");\n else\n printf(\"no\\n\");\n return 0;\n}" }, { "code": null, "e": 3105, "s": 3043, "text": "If run the above code it will generate the following output −" }, { "code": null, "e": 3108, "s": 3105, "text": "No" } ]
Decorator to print Function call details in Python - GeeksforGeeks
08 May, 2020 Decorators in Python are the design pattern that allows the users to add new functionalities to an existing object without the need to modify its structure. Decorators are generally called before defining a function the user wants to decorate. Example: # defining a decorator def hello_decorator(func): # inner1 is a Wrapper function in # which the argument is called # inner function can access the outer local # functions like in this case "func" def inner1(): print("Hello, this is before function execution") # calling the actual function now # inside the wrapper function. func() print("This is after function execution") return inner1 # defining a function, to be called inside wrapper def function_to_be_used(): print("This is inside the function !!") # passing 'function_to_be_used' inside the # decorator to control its behavior function_to_be_used = hello_decorator(function_to_be_used) # calling the function function_to_be_used() Hello, this is before function execution This is inside the function !! This is after function execution Note: For more information, refer to Decorators in Python Let’s consider a scenario where you have written a very lengthy code and want to know the function call details. So what you can do is scroll through your code each and every time for different functions to know their details or you can work smartly. You can create a decorator that can print the details of any function you want. To do this the functions in Python certain attributes. One such attribute is __code__ that returns the called function bytecode. The __code__ attributes also have certain attributes that will help us in performing our tasks. We will be using the co_varnames attribute that returns the tuple of names of arguments and local variables and co_argcount that returns the number of arguments (not including keyword-only arguments, * or ** args). Let’s see the below implementation of such decorator using these discussed attributes. Example: # Decorator to print function call# detailsdef function_details(func): # Getting the argument names of the # called function argnames = func.__code__.co_varnames[:func.__code__.co_argcount] # Getting the Function name of the # called function fname = func.__name__ def inner_func(*args, **kwargs): print(fname, "(", end = "") # printing the function arguments print(', '.join( '% s = % r' % entry for entry in zip(argnames, args[:len(argnames)])), end = ", ") # Printing the variable length Arguments print("args =", list(args[len(argnames):]), end = ", ") # Printing the variable length keyword # arguments print("kwargs =", kwargs, end = "") print(")") return inner_func # Driver Code@function_detailsdef GFG(a, b = 1, *args, **kwargs): pass GFG(1, 2, 3, 4, 5, d = 6, g = 12.9)GFG(1, 2, 3)GFG(1, 2, d = 'Geeks') GFG (a = 1, b = 2, args = [3, 4, 5], kwargs = {'d': 6, 'g': 12.9}) GFG (a = 1, b = 2, args = [3], kwargs = {}) GFG (a = 1, b = 2, args = [], kwargs = {'d': 'Geeks'}) Python Decorators 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": "\n08 May, 2020" }, { "code": null, "e": 24145, "s": 23901, "text": "Decorators in Python are the design pattern that allows the users to add new functionalities to an existing object without the need to modify its structure. Decorators are generally called before defining a function the user wants to decorate." }, { "code": null, "e": 24154, "s": 24145, "text": "Example:" }, { "code": "# defining a decorator def hello_decorator(func): # inner1 is a Wrapper function in # which the argument is called # inner function can access the outer local # functions like in this case \"func\" def inner1(): print(\"Hello, this is before function execution\") # calling the actual function now # inside the wrapper function. func() print(\"This is after function execution\") return inner1 # defining a function, to be called inside wrapper def function_to_be_used(): print(\"This is inside the function !!\") # passing 'function_to_be_used' inside the # decorator to control its behavior function_to_be_used = hello_decorator(function_to_be_used) # calling the function function_to_be_used() ", "e": 24969, "s": 24154, "text": null }, { "code": null, "e": 25075, "s": 24969, "text": "Hello, this is before function execution\nThis is inside the function !!\nThis is after function execution\n" }, { "code": null, "e": 25133, "s": 25075, "text": "Note: For more information, refer to Decorators in Python" }, { "code": null, "e": 25464, "s": 25133, "text": "Let’s consider a scenario where you have written a very lengthy code and want to know the function call details. So what you can do is scroll through your code each and every time for different functions to know their details or you can work smartly. You can create a decorator that can print the details of any function you want." }, { "code": null, "e": 25991, "s": 25464, "text": "To do this the functions in Python certain attributes. One such attribute is __code__ that returns the called function bytecode. The __code__ attributes also have certain attributes that will help us in performing our tasks. We will be using the co_varnames attribute that returns the tuple of names of arguments and local variables and co_argcount that returns the number of arguments (not including keyword-only arguments, * or ** args). Let’s see the below implementation of such decorator using these discussed attributes." }, { "code": null, "e": 26000, "s": 25991, "text": "Example:" }, { "code": "# Decorator to print function call# detailsdef function_details(func): # Getting the argument names of the # called function argnames = func.__code__.co_varnames[:func.__code__.co_argcount] # Getting the Function name of the # called function fname = func.__name__ def inner_func(*args, **kwargs): print(fname, \"(\", end = \"\") # printing the function arguments print(', '.join( '% s = % r' % entry for entry in zip(argnames, args[:len(argnames)])), end = \", \") # Printing the variable length Arguments print(\"args =\", list(args[len(argnames):]), end = \", \") # Printing the variable length keyword # arguments print(\"kwargs =\", kwargs, end = \"\") print(\")\") return inner_func # Driver Code@function_detailsdef GFG(a, b = 1, *args, **kwargs): pass GFG(1, 2, 3, 4, 5, d = 6, g = 12.9)GFG(1, 2, 3)GFG(1, 2, d = 'Geeks')", "e": 26999, "s": 26000, "text": null }, { "code": null, "e": 27166, "s": 26999, "text": "GFG (a = 1, b = 2, args = [3, 4, 5], kwargs = {'d': 6, 'g': 12.9})\nGFG (a = 1, b = 2, args = [3], kwargs = {})\nGFG (a = 1, b = 2, args = [], kwargs = {'d': 'Geeks'})\n" }, { "code": null, "e": 27184, "s": 27166, "text": "Python Decorators" }, { "code": null, "e": 27191, "s": 27184, "text": "Python" }, { "code": null, "e": 27289, "s": 27191, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27298, "s": 27289, "text": "Comments" }, { "code": null, "e": 27311, "s": 27298, "text": "Old Comments" }, { "code": null, "e": 27343, "s": 27311, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27399, "s": 27343, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27441, "s": 27399, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27483, "s": 27441, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27519, "s": 27483, "text": "Python | Pandas dataframe.groupby()" }, { "code": null, "e": 27541, "s": 27519, "text": "Defaultdict in Python" }, { "code": null, "e": 27580, "s": 27541, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27607, "s": 27580, "text": "Python Classes and Objects" }, { "code": null, "e": 27638, "s": 27607, "text": "Python | os.path.join() method" } ]
How to copy files/folders to the remote location in the PowerShell?
To copy files or folders to or from the remote location, you need to provide the UNC path of the items. For example, here we are going to copy a file from the local computer to a remote computer called Test-PC. Copy-Item D:\Temp\PowerShellcommands.csv -Destination \\Test- PC\Sharedpath\PScommands.ps1 -PassThru Here, file PowerShellcommands.csv is copied to the remote computer and renamed it with PSCommands.ps1 You can also copy files from the one shared location to another shared location. For example, Copy-Item \\Test-PC1\\D$\PowerShellcommands.csv -Destination \\Test- PC\Sharedpath\PScommands.ps1 -PassThru There is another way to copy items to the remote location is, you can use the ToSession parameter. To use the ToSesssion parameter, you need to connect a remote computer using PSRemote computer session and if destination files/folder is in the different domain or the workstation then you need to use the different credentials while remoting. For example, $destsession = New-PSSession -ComputerName Test-PC -Credential (Get-Credential) Copy-Item D:\Temp\PowerShellcommands.csv -ToSession $destsession -PassThru You can also copy folder(s) with the same method described above. For example, $destsession = New-PSSession -ComputerName Test-PC -Credential (Get-Credential) Copy-Item D:\Temp\* -ToSession $destsession -Force -PassThru You can also copy files from the one session to another session with the source path should mention with –FromSession parameter, while the destination path should mention with –ToSession parameter. For example, $destsession = New-PSSession -ComputerName Test-PC -Credential (Get-Credential) $sourcesession = New-PSSession -ComputerName Test1-PC -Credential (Get-Credential) Copy-Item -FromSession $sourcesession -ToSession $destsession -PassThru
[ { "code": null, "e": 1273, "s": 1062, "text": "To copy files or folders to or from the remote location, you need to provide the UNC path of the items. For example, here we are going to copy a file from the local computer to a remote computer called Test-PC." }, { "code": null, "e": 1374, "s": 1273, "text": "Copy-Item D:\\Temp\\PowerShellcommands.csv -Destination \\\\Test-\nPC\\Sharedpath\\PScommands.ps1 -PassThru" }, { "code": null, "e": 1476, "s": 1374, "text": "Here, file PowerShellcommands.csv is copied to the remote computer and renamed it with PSCommands.ps1" }, { "code": null, "e": 1557, "s": 1476, "text": "You can also copy files from the one shared location to another shared location." }, { "code": null, "e": 1570, "s": 1557, "text": "For example," }, { "code": null, "e": 1678, "s": 1570, "text": "Copy-Item \\\\Test-PC1\\\\D$\\PowerShellcommands.csv -Destination \\\\Test-\nPC\\Sharedpath\\PScommands.ps1 -PassThru" }, { "code": null, "e": 2021, "s": 1678, "text": "There is another way to copy items to the remote location is, you can use the ToSession parameter. To use the ToSesssion parameter, you need to connect a remote computer using PSRemote computer session and if destination files/folder is in the different domain or the workstation then you need to use the different credentials while remoting." }, { "code": null, "e": 2034, "s": 2021, "text": "For example," }, { "code": null, "e": 2189, "s": 2034, "text": "$destsession = New-PSSession -ComputerName Test-PC -Credential (Get-Credential)\nCopy-Item D:\\Temp\\PowerShellcommands.csv -ToSession $destsession -PassThru" }, { "code": null, "e": 2255, "s": 2189, "text": "You can also copy folder(s) with the same method described above." }, { "code": null, "e": 2268, "s": 2255, "text": "For example," }, { "code": null, "e": 2409, "s": 2268, "text": "$destsession = New-PSSession -ComputerName Test-PC -Credential (Get-Credential)\nCopy-Item D:\\Temp\\* -ToSession $destsession -Force -PassThru" }, { "code": null, "e": 2607, "s": 2409, "text": "You can also copy files from the one session to another session with the source path should mention with –FromSession parameter, while the destination path should mention with –ToSession parameter." }, { "code": null, "e": 2620, "s": 2607, "text": "For example," }, { "code": null, "e": 2855, "s": 2620, "text": "$destsession = New-PSSession -ComputerName Test-PC -Credential (Get-Credential)\n$sourcesession = New-PSSession -ComputerName Test1-PC -Credential (Get-Credential)\nCopy-Item -FromSession $sourcesession -ToSession $destsession -PassThru" } ]
D3.js | d3.set.clear() Function - GeeksforGeeks
28 Jun, 2019 The set.clear() function in D3.js is used to remove all values from the set. It clears the set and holds that blank set you can check that in the 2nd example. Syntax: d3.set().clear(); Parameters: This function does not accept any parameters. Return Value: This function does not returns any values. Below programs illustrate the d3.set.clear() function in D3.js: Example 1: <!DOCTYPE html><html> <head> <title> d3.set.clear() Function</title> <script src='https://d3js.org/d3.v4.min.js'></script></head> <body> <script> // Initialising the set var set = d3.set(["1", "2", "a", "b", "Geeks"]); // Checking the set console.log(set); // Calling the set.clear() function set.clear(); // Checking whether any element is present // in the set or not A = set.has("a"); B = set.has("Geeks"); // Getting the output of true or false console.log(A); console.log(B); </script></body> </html> Output: {"$1":"1","$2":"2","$a":"a","$b":"b","$Geeks":"Geeks"} false false Example 2: <!DOCTYPE html><html> <head> <title> d3.set.clear() Function</title> <script src='https://d3js.org/d3.v4.min.js'></script></head> <body> <script> // Initialising the set var set = d3.set(["1", "2", "a", "b", "Geeks"]); // Checking whether any element is present // in the set or not before calling set.clear() function A = set.has("a"); B = set.has("Geeks"); // Getting the output of true or false console.log(A); console.log(B); // Calling the set.clear() function set.clear(); // Checking whether any element is present // in the set or not after calling set.clear() function C = set.has("a"); D = set.has("Geeks"); // Getting the output of true or false console.log(C); console.log(D); </script></body> </html> Output: true true false false Ref: https://devdocs.io/d3~5/d3-collection#set_clear D3.js JavaScript Web Technologies 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": 24676, "s": 24648, "text": "\n28 Jun, 2019" }, { "code": null, "e": 24835, "s": 24676, "text": "The set.clear() function in D3.js is used to remove all values from the set. It clears the set and holds that blank set you can check that in the 2nd example." }, { "code": null, "e": 24843, "s": 24835, "text": "Syntax:" }, { "code": null, "e": 24861, "s": 24843, "text": "d3.set().clear();" }, { "code": null, "e": 24919, "s": 24861, "text": "Parameters: This function does not accept any parameters." }, { "code": null, "e": 24976, "s": 24919, "text": "Return Value: This function does not returns any values." }, { "code": null, "e": 25040, "s": 24976, "text": "Below programs illustrate the d3.set.clear() function in D3.js:" }, { "code": null, "e": 25051, "s": 25040, "text": "Example 1:" }, { "code": "<!DOCTYPE html><html> <head> <title> d3.set.clear() Function</title> <script src='https://d3js.org/d3.v4.min.js'></script></head> <body> <script> // Initialising the set var set = d3.set([\"1\", \"2\", \"a\", \"b\", \"Geeks\"]); // Checking the set console.log(set); // Calling the set.clear() function set.clear(); // Checking whether any element is present // in the set or not A = set.has(\"a\"); B = set.has(\"Geeks\"); // Getting the output of true or false console.log(A); console.log(B); </script></body> </html>", "e": 25673, "s": 25051, "text": null }, { "code": null, "e": 25681, "s": 25673, "text": "Output:" }, { "code": null, "e": 25753, "s": 25681, "text": "{\"$1\":\"1\",\"$2\":\"2\",\"$a\":\"a\",\"$b\":\"b\",\"$Geeks\":\"Geeks\"}\n false\n false\n" }, { "code": null, "e": 25764, "s": 25753, "text": "Example 2:" }, { "code": "<!DOCTYPE html><html> <head> <title> d3.set.clear() Function</title> <script src='https://d3js.org/d3.v4.min.js'></script></head> <body> <script> // Initialising the set var set = d3.set([\"1\", \"2\", \"a\", \"b\", \"Geeks\"]); // Checking whether any element is present // in the set or not before calling set.clear() function A = set.has(\"a\"); B = set.has(\"Geeks\"); // Getting the output of true or false console.log(A); console.log(B); // Calling the set.clear() function set.clear(); // Checking whether any element is present // in the set or not after calling set.clear() function C = set.has(\"a\"); D = set.has(\"Geeks\"); // Getting the output of true or false console.log(C); console.log(D); </script></body> </html>", "e": 26608, "s": 25764, "text": null }, { "code": null, "e": 26616, "s": 26608, "text": "Output:" }, { "code": null, "e": 26639, "s": 26616, "text": "true\ntrue\nfalse\nfalse\n" }, { "code": null, "e": 26692, "s": 26639, "text": "Ref: https://devdocs.io/d3~5/d3-collection#set_clear" }, { "code": null, "e": 26698, "s": 26692, "text": "D3.js" }, { "code": null, "e": 26709, "s": 26698, "text": "JavaScript" }, { "code": null, "e": 26726, "s": 26709, "text": "Web Technologies" }, { "code": null, "e": 26824, "s": 26726, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26869, "s": 26824, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 26930, "s": 26869, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27002, "s": 26930, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 27054, "s": 27002, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 27100, "s": 27054, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 27142, "s": 27100, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 27175, "s": 27142, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27218, "s": 27175, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 27280, "s": 27218, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
LCS of three strings | Practice | GeeksforGeeks
Given 3 strings A, B and C, the task is to find the longest common sub-sequence in all three given sequences. Example 1: Input: A = "geeks", B = "geeksfor", C = "geeksforgeeks" Output: 5 Explanation: "geeks"is the longest common subsequence with length 5. ​Example 2: Input: A = "abcd", B = "efgh", C = "ijkl" Output: 0 Explanation: There's no common subsequence in all the strings. Your Task: You don't need to read input or print anything. Your task is to complete the function LCSof3() which takes the strings A, B, C and their lengths n1, n2, n3 as input and returns the length of the longest common subsequence in all the 3 strings. Expected Time Complexity: O(n1*n2*n3). Expected Auxiliary Space: O(n1*n2*n3). Constraints: 1<=n1, n2, n3<=20 0 amarrajsmart1973 days ago int LCSof3 (string A, string B, string C, int n1, int n2, int n3){ // your code here int dp[n1+1][n2+1][n3+1]; for(int i=0;i<=n1;i++) { for(int j=0;j<=n2;j++) { for(int k=0;k<=n3;k++) { if(i==0||j==0||k==0) dp[i][j][k]=0; else if(A[i-1]==B[j-1]&&A[i-1]==C[k-1]) dp[i][j][k]=1+dp[i-1][j-1][k-1]; else dp[i][j][k]=max(dp[i-1][j][k],max(dp[i][j-1][k],dp[i][j][k-1])); } } } return dp[n1][n2][n3];} 0 riyanshugarg15085 days ago int dp[n1+1][n2+1][n3+1]; for(int i=0; i<=n1; i++) { for(int j=0; j<=n2; j++) { for(int k=0; k<=n3; k++) { if(i==0||k==0||j==0) dp[i][j][k]=0; } } } for(int i=1; i<=n1; i++) { for(int j=1; j<=n2; j++) { for(int k=1; k<=n3; k++) { if(x[i-1]==y[j-1]&&x[i-1]==z[k-1]) { dp[i][j][k]= 1+dp[i-1][j-1][k-1]; } else { dp[i][j][k]= max(dp[i-1][j][k],max(dp[i][j-1][k],dp[i][j][k-1])); } } } } return dp[n1][n2][n3]; -1 jainmuskan5654 weeks ago int LCSof3 (string A, string B, string C, int n1, int n2, int n3){ int dp[n1+1][n2+1][n3+1]; for(int i=0;i<=n1;i++){ for(int j=0;j<=n2;j++){ for(int k=0;k<=n3;k++){ if(i==0||j==0||k==0){ dp[i][j][k]=0; } } } } for(int i=1;i<=n1;i++){ for(int j=1;j<=n2;j++){ for(int k=1;k<=n3;k++){ if(A[i-1]==B[j-1] && B[j-1]==C[k-1]){ dp[i][j][k]= 1+ dp[i-1][j-1][k-1]; } else{ dp[i][j][k]= max(dp[i-1][j][k],max(dp[i][j-1][k],dp[i][j][k-1])); } } } } return dp[n1][n2][n3];} 0 cs19b01911 month ago int LCSof3 (string A, string B, string C, int n1, int n2, int n3){ // your code here int dp[n1+1][n2+1][n3+1]; for(int i = 0 ;i <= n1 ; i++) { for(int j = 0 ; j <=n2 ; j++) { for(int k = 0 ; k <= n3 ; k++) { if(i == 0 || j == 0 || k == 0) dp[i][j][k] = 0; else { if(A[i-1] == B[j-1] && B[j-1] == C[k-1] && C[k-1] == A[i-1]) dp[i][j][k] = 1 + dp[i-1][j-1][k-1]; else dp[i][j][k] = max(dp[i][j][k-1] , max(dp[i-1][j][k] , dp[i][j-1][k])); } } } } return dp[n1][n2][n3];} 0 whitewalter2 months ago int t[n1+1][n2+1][n3+1]; for(int i=0;i<=n1;i++){ for(int j=0;j<=n2;j++){ for(int k=0;k<=n3;k++){ if(i==0 || j==0 || k==0){ t[i][j][k]=0; } } } } for(int i=1;i<=n1;i++){ for(int j=1;j<=n2;j++){ for(int k=1;k<=n3;k++){ if((A[i-1]==B[j-1]) && (B[j-1]==C[k-1])) t[i][j][k]=1+t[i-1][j-1][k-1]; else t[i][j][k]=max({t[i-1][j][k] , t[i][j-1][k] , t[i][j][k-1]}); } } } return t[n1][n2][n3]; 0 annanyamathur2 months ago int memo[100][100][100];int Lcs(string a, string b, string c, int n, int m, int x){ if(n<=0 ||m<=0|| x<=0) return 0; if(memo[n][m][x]==-1) { if(a[n-1]==b[m-1] && b[m-1]==c[x-1]) memo[n][m][x]=1+Lcs(a,b,c,n-1,m-1,x-1); else memo[n][m][x]=max({Lcs(a,b,c,n,m,x-1),Lcs(a,b,c,n,m-1,x),Lcs(a,b,c,n-1,m,x)}); } return memo[n][m][x];}int LCSof3 (string a, string b, string c, int n1, int n2, int n3){ memset(memo,-1,sizeof(memo)); return Lcs(a,b,c,n1,n2,n3); } 0 bhargav_412 months ago Java Solution class Solution { int LCSof3(String A, String B, String C, int n1, int n2, int n3) { int[][][] dp = new int[n1+1][n2+1][n3+1]; for(int i=0;i<n1+1;i++) for(int j=0;j<n2+1;j++) for(int k=0;k<n3+1;k++) dp[i][j][k] = -1; return solve(A,B,C,n1,n2,n3,dp); } public static int solve(String A, String B, String C,int n1, int n2, int n3,int[][][] dp){ if(n1<=0 || n2<=0 || n3<=0) return 0; if(dp[n1][n2][n3]!=-1) return dp[n1][n2][n3]; if(A.charAt(n1-1)==B.charAt(n2-1) && B.charAt(n2-1)==C.charAt(n3-1)) return dp[n1][n2][n3] = 1 + solve(A,B,C,n1-1,n2-1,n3-1,dp); else{ int a = solve(A,B,C,n1-1,n2,n3,dp); int b = solve(A,B,C,n1-1,n2-1,n3,dp); int c = solve(A,B,C,n1-1,n2-1,n3-1,dp); int d = solve(A,B,C,n1,n2-1,n3,dp); int e = solve(A,B,C,n1,n2-1,n3-1,dp); int f = solve(A,B,C,n1,n2,n3-1,dp); int max = Math.max(a,Math.max(b,Math.max(c,Math.max(d,Math.max(e,f))))); return dp[n1][n2][n3] = max; } } } +1 shyamprakash8072 months ago Python solution using LCS : class Solution: def LCSof3(self,s1,s2,s3,n1,n2,n3): # code here dp = [[[0 for i in range(n3+1)] for j in range(n2+1)] for k in range(n1+1)] for i in range(1, n1+1): for j in range(1, n2+1): for k in range(1, n3+1): if s1[i-1]==s2[j-1]==s3[k-1]: dp[i][j][k] = 1 + dp[i-1][j-1][k-1] else: dp[i][j][k] = max(dp[i-1][j][k], dp[i][j-1][k], dp[i][j][k-1]) return dp[n1][n2][n3] +1 lindan1232 months ago int lcs(int x, int y, int z, string s1, string s2, string s3) { int dp[100][100][100]; for(int i=0;i<=x;i++) { for(int j=0;j<=y;j++) { for(int k=0;k<=z;k++) { if( i==0 || j==0 || k==0) dp[i][j][k]=0; else if ((s1[i-1] == s2[j-1]) && (s2[j-1]==s3[k-1])) dp[i][j][k] = dp[i-1][j-1][k-1] + 1; else dp[i][j][k] = max({dp[i-1][j][k], dp[i][j-1][k], dp[i][j][k-1]}); } } } //returning the result. return dp[x][y][z]; } int LCSof3 (string A, string B, string C, int n1, int n2, int n3) { int n = A.length(); int m = B.length(); int k = C.length(); int ans = lcs(n,m,k,A,B,C); return ans; } Time Taken : 0.0 Cpp 0 victor19108663 months ago Memoization approach Easy to understand || c++ int helper(string &A,string &B,string &C,int n1,int n2,int n3,vector<vector<vector<int>>> &dp){ if(n1==0 || n2==0 || n3==0)return 0; if(dp[n1][n2][n3]!=-1)return dp[n1][n2][n3]; if(A[n1-1]==B[n2-1] && B[n2-1]==C[n3-1]){ return dp[n1][n2][n3]=1+helper(A,B,C,n1-1,n2-1,n3-1,dp); } else{ return dp[n1][n2][n3]=max({helper(A,B,C,n1-1,n2,n3,dp),helper(A,B,C,n1,n2-1,n3,dp),helper(A,B,C,n1,n2,n3-1,dp)}); }}int LCSof3 (string A, string B, string C, int n1, int n2, int n3){ vector<vector<vector<int>>> dp(n1+1,vector<vector<int>>(n2+1,vector<int>(n3+1,-1))); return helper(A,B,C,n1,n2,n3,dp);} 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": 348, "s": 238, "text": "Given 3 strings A, B and C, the task is to find the longest common sub-sequence in all three given sequences." }, { "code": null, "e": 359, "s": 348, "text": "Example 1:" }, { "code": null, "e": 496, "s": 359, "text": "Input:\nA = \"geeks\", B = \"geeksfor\", \nC = \"geeksforgeeks\"\nOutput: 5\nExplanation: \"geeks\"is the longest common\nsubsequence with length 5.\n" }, { "code": null, "e": 511, "s": 496, "text": "​Example 2:" }, { "code": null, "e": 628, "s": 511, "text": "Input: \nA = \"abcd\", B = \"efgh\", C = \"ijkl\"\nOutput: 0\nExplanation: There's no common subsequence\nin all the strings.\n" }, { "code": null, "e": 884, "s": 628, "text": "\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function LCSof3() which takes the strings A, B, C and their lengths n1, n2, n3 as input and returns the length of the longest common subsequence in all the 3 strings." }, { "code": null, "e": 963, "s": 884, "text": "\nExpected Time Complexity: O(n1*n2*n3).\nExpected Auxiliary Space: O(n1*n2*n3)." }, { "code": null, "e": 995, "s": 963, "text": "\nConstraints:\n1<=n1, n2, n3<=20" }, { "code": null, "e": 997, "s": 995, "text": "0" }, { "code": null, "e": 1023, "s": 997, "text": "amarrajsmart1973 days ago" }, { "code": null, "e": 1566, "s": 1023, "text": "int LCSof3 (string A, string B, string C, int n1, int n2, int n3){ // your code here int dp[n1+1][n2+1][n3+1]; for(int i=0;i<=n1;i++) { for(int j=0;j<=n2;j++) { for(int k=0;k<=n3;k++) { if(i==0||j==0||k==0) dp[i][j][k]=0; else if(A[i-1]==B[j-1]&&A[i-1]==C[k-1]) dp[i][j][k]=1+dp[i-1][j-1][k-1]; else dp[i][j][k]=max(dp[i-1][j][k],max(dp[i][j-1][k],dp[i][j][k-1])); } } } return dp[n1][n2][n3];}" }, { "code": null, "e": 1568, "s": 1566, "text": "0" }, { "code": null, "e": 1595, "s": 1568, "text": "riyanshugarg15085 days ago" }, { "code": null, "e": 2272, "s": 1595, "text": "int dp[n1+1][n2+1][n3+1]; for(int i=0; i<=n1; i++) { for(int j=0; j<=n2; j++) { for(int k=0; k<=n3; k++) { if(i==0||k==0||j==0) dp[i][j][k]=0; } } } for(int i=1; i<=n1; i++) { for(int j=1; j<=n2; j++) { for(int k=1; k<=n3; k++) { if(x[i-1]==y[j-1]&&x[i-1]==z[k-1]) { dp[i][j][k]= 1+dp[i-1][j-1][k-1]; } else { dp[i][j][k]= max(dp[i-1][j][k],max(dp[i][j-1][k],dp[i][j][k-1])); } } } } return dp[n1][n2][n3];" }, { "code": null, "e": 2275, "s": 2272, "text": "-1" }, { "code": null, "e": 2300, "s": 2275, "text": "jainmuskan5654 weeks ago" }, { "code": null, "e": 2948, "s": 2300, "text": "int LCSof3 (string A, string B, string C, int n1, int n2, int n3){ int dp[n1+1][n2+1][n3+1]; for(int i=0;i<=n1;i++){ for(int j=0;j<=n2;j++){ for(int k=0;k<=n3;k++){ if(i==0||j==0||k==0){ dp[i][j][k]=0; } } } } for(int i=1;i<=n1;i++){ for(int j=1;j<=n2;j++){ for(int k=1;k<=n3;k++){ if(A[i-1]==B[j-1] && B[j-1]==C[k-1]){ dp[i][j][k]= 1+ dp[i-1][j-1][k-1]; } else{ dp[i][j][k]= max(dp[i-1][j][k],max(dp[i][j-1][k],dp[i][j][k-1])); } } } } return dp[n1][n2][n3];}" }, { "code": null, "e": 2950, "s": 2948, "text": "0" }, { "code": null, "e": 2971, "s": 2950, "text": "cs19b01911 month ago" }, { "code": null, "e": 3645, "s": 2971, "text": "int LCSof3 (string A, string B, string C, int n1, int n2, int n3){ // your code here int dp[n1+1][n2+1][n3+1]; for(int i = 0 ;i <= n1 ; i++) { for(int j = 0 ; j <=n2 ; j++) { for(int k = 0 ; k <= n3 ; k++) { if(i == 0 || j == 0 || k == 0) dp[i][j][k] = 0; else { if(A[i-1] == B[j-1] && B[j-1] == C[k-1] && C[k-1] == A[i-1]) dp[i][j][k] = 1 + dp[i-1][j-1][k-1]; else dp[i][j][k] = max(dp[i][j][k-1] , max(dp[i-1][j][k] , dp[i][j-1][k])); } } } } return dp[n1][n2][n3];}" }, { "code": null, "e": 3647, "s": 3645, "text": "0" }, { "code": null, "e": 3671, "s": 3647, "text": "whitewalter2 months ago" }, { "code": null, "e": 4249, "s": 3671, "text": " int t[n1+1][n2+1][n3+1]; for(int i=0;i<=n1;i++){ for(int j=0;j<=n2;j++){ for(int k=0;k<=n3;k++){ if(i==0 || j==0 || k==0){ t[i][j][k]=0; } } } } for(int i=1;i<=n1;i++){ for(int j=1;j<=n2;j++){ for(int k=1;k<=n3;k++){ if((A[i-1]==B[j-1]) && (B[j-1]==C[k-1])) t[i][j][k]=1+t[i-1][j-1][k-1]; else t[i][j][k]=max({t[i-1][j][k] , t[i][j-1][k] , t[i][j][k-1]}); } } } return t[n1][n2][n3];" }, { "code": null, "e": 4251, "s": 4249, "text": "0" }, { "code": null, "e": 4277, "s": 4251, "text": "annanyamathur2 months ago" }, { "code": null, "e": 4772, "s": 4277, "text": "int memo[100][100][100];int Lcs(string a, string b, string c, int n, int m, int x){ if(n<=0 ||m<=0|| x<=0) return 0; if(memo[n][m][x]==-1) { if(a[n-1]==b[m-1] && b[m-1]==c[x-1]) memo[n][m][x]=1+Lcs(a,b,c,n-1,m-1,x-1); else memo[n][m][x]=max({Lcs(a,b,c,n,m,x-1),Lcs(a,b,c,n,m-1,x),Lcs(a,b,c,n-1,m,x)}); } return memo[n][m][x];}int LCSof3 (string a, string b, string c, int n1, int n2, int n3){ memset(memo,-1,sizeof(memo)); return Lcs(a,b,c,n1,n2,n3); }" }, { "code": null, "e": 4774, "s": 4772, "text": "0" }, { "code": null, "e": 4797, "s": 4774, "text": "bhargav_412 months ago" }, { "code": null, "e": 4812, "s": 4797, "text": "Java Solution " }, { "code": null, "e": 5947, "s": 4814, "text": "class Solution \n{ \n int LCSof3(String A, String B, String C, int n1, int n2, int n3) \n { \n int[][][] dp = new int[n1+1][n2+1][n3+1];\n for(int i=0;i<n1+1;i++) for(int j=0;j<n2+1;j++) for(int k=0;k<n3+1;k++) dp[i][j][k] = -1;\n return solve(A,B,C,n1,n2,n3,dp);\n \n }\n \n public static int solve(String A, String B, String C,int n1, int n2, int n3,int[][][] dp){\n if(n1<=0 || n2<=0 || n3<=0) return 0;\n \n if(dp[n1][n2][n3]!=-1) return dp[n1][n2][n3];\n \n if(A.charAt(n1-1)==B.charAt(n2-1) && B.charAt(n2-1)==C.charAt(n3-1))\n return dp[n1][n2][n3] = 1 + solve(A,B,C,n1-1,n2-1,n3-1,dp);\n else{\n int a = solve(A,B,C,n1-1,n2,n3,dp);\n int b = solve(A,B,C,n1-1,n2-1,n3,dp);\n int c = solve(A,B,C,n1-1,n2-1,n3-1,dp);\n int d = solve(A,B,C,n1,n2-1,n3,dp);\n int e = solve(A,B,C,n1,n2-1,n3-1,dp);\n int f = solve(A,B,C,n1,n2,n3-1,dp);\n \n int max = Math.max(a,Math.max(b,Math.max(c,Math.max(d,Math.max(e,f)))));\n return dp[n1][n2][n3] = max;\n }\n }\n} " }, { "code": null, "e": 5950, "s": 5947, "text": "+1" }, { "code": null, "e": 5978, "s": 5950, "text": "shyamprakash8072 months ago" }, { "code": null, "e": 6006, "s": 5978, "text": "Python solution using LCS :" }, { "code": null, "e": 6024, "s": 6008, "text": "class Solution:" }, { "code": null, "e": 6511, "s": 6024, "text": " def LCSof3(self,s1,s2,s3,n1,n2,n3): # code here dp = [[[0 for i in range(n3+1)] for j in range(n2+1)] for k in range(n1+1)] for i in range(1, n1+1): for j in range(1, n2+1): for k in range(1, n3+1): if s1[i-1]==s2[j-1]==s3[k-1]: dp[i][j][k] = 1 + dp[i-1][j-1][k-1] else: dp[i][j][k] = max(dp[i-1][j][k], dp[i][j-1][k], dp[i][j][k-1]) return dp[n1][n2][n3]" }, { "code": null, "e": 6514, "s": 6511, "text": "+1" }, { "code": null, "e": 6536, "s": 6514, "text": "lindan1232 months ago" }, { "code": null, "e": 7468, "s": 6536, "text": " int lcs(int x, int y, int z, string s1, string s2, string s3)\n {\n int dp[100][100][100];\n \n for(int i=0;i<=x;i++)\n {\n for(int j=0;j<=y;j++)\n {\n for(int k=0;k<=z;k++)\n {\n \n if( i==0 || j==0 || k==0)\n dp[i][j][k]=0; \n \n else if ((s1[i-1] == s2[j-1]) && (s2[j-1]==s3[k-1])) \n dp[i][j][k] = dp[i-1][j-1][k-1] + 1; \n \n else\n dp[i][j][k] = max({dp[i-1][j][k], dp[i][j-1][k], dp[i][j][k-1]}); \n }\n }\n }\n \n //returning the result.\n return dp[x][y][z]; \n }\nint LCSof3 (string A, string B, string C, int n1, int n2, int n3)\n{\n int n = A.length();\n int m = B.length();\n int k = C.length();\n \n int ans = lcs(n,m,k,A,B,C);\n \n return ans;\n}" }, { "code": null, "e": 7485, "s": 7468, "text": "Time Taken : 0.0" }, { "code": null, "e": 7489, "s": 7485, "text": "Cpp" }, { "code": null, "e": 7491, "s": 7489, "text": "0" }, { "code": null, "e": 7517, "s": 7491, "text": "victor19108663 months ago" }, { "code": null, "e": 7564, "s": 7517, "text": "Memoization approach Easy to understand || c++" }, { "code": null, "e": 8168, "s": 7564, "text": "int helper(string &A,string &B,string &C,int n1,int n2,int n3,vector<vector<vector<int>>> &dp){ if(n1==0 || n2==0 || n3==0)return 0; if(dp[n1][n2][n3]!=-1)return dp[n1][n2][n3]; if(A[n1-1]==B[n2-1] && B[n2-1]==C[n3-1]){ return dp[n1][n2][n3]=1+helper(A,B,C,n1-1,n2-1,n3-1,dp); } else{ return dp[n1][n2][n3]=max({helper(A,B,C,n1-1,n2,n3,dp),helper(A,B,C,n1,n2-1,n3,dp),helper(A,B,C,n1,n2,n3-1,dp)}); }}int LCSof3 (string A, string B, string C, int n1, int n2, int n3){ vector<vector<vector<int>>> dp(n1+1,vector<vector<int>>(n2+1,vector<int>(n3+1,-1))); return helper(A,B,C,n1,n2,n3,dp);}" }, { "code": null, "e": 8314, "s": 8168, "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": 8350, "s": 8314, "text": " Login to access your submissions. " }, { "code": null, "e": 8360, "s": 8350, "text": "\nProblem\n" }, { "code": null, "e": 8370, "s": 8360, "text": "\nContest\n" }, { "code": null, "e": 8433, "s": 8370, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 8581, "s": 8433, "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": 8789, "s": 8581, "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": 8895, "s": 8789, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
How to add function to the clear button icon in Material UI Autocomplete ? - GeeksforGeeks
22 Feb, 2021 In this article, We are going to add an extra function to the clear button of Material UI Autocomplete. Take Reference to the clear button in code and then add a click event listener on it. 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., folder name, move to it using the following command: cd foldername Step 3: Install required modules npm install @material-ui/core npm install @material-ui/lab Project Structure: Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. App.js import React,{ Component } from 'react';import TextField from "@material-ui/core/TextField";import Autocomplete from "@material-ui/lab/Autocomplete"; class App extends Component { constructor(props) { super(props); this.state = { list: [ { title: "Title 1"}, { title: "Title 2"}, { title: "Title 3"}, { title: "Title 4"}, ] } } componentDidMount(){ // Take the Reference of Close Button const close = document.getElementsByClassName( "MuiAutocomplete-clearIndicator" )[0]; // Add a Click Event Listener to the button close.addEventListener("click", () => { alert("Add your Own Functionality Here..."); }); } render() { return ( <Autocomplete options={this.state.list} getOptionLabel={(option) => option.title} style={{ width: 300 }} renderInput={(params) => ( <TextField {...params} label="Combo box" variant="outlined" /> )} /> ); } } 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: Picked React-Questions Technical Scripter 2020 ReactJS Technical Scripter Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to redirect to another page in ReactJS ? How to pass data from one component to other component in ReactJS ? ReactJS setState() Re-rendering Components in ReactJS ReactJS defaultProps Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? Convert a string to an integer in JavaScript
[ { "code": null, "e": 24540, "s": 24512, "text": "\n22 Feb, 2021" }, { "code": null, "e": 24730, "s": 24540, "text": "In this article, We are going to add an extra function to the clear button of Material UI Autocomplete. Take Reference to the clear button in code and then add a click event listener on it." }, { "code": null, "e": 24780, "s": 24730, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 24844, "s": 24780, "text": "Step 1: Create a React application using the following command." }, { "code": null, "e": 24876, "s": 24844, "text": "npx create-react-app foldername" }, { "code": null, "e": 24979, "s": 24876, "text": "Step 2: After creating your project folder, i.e., folder name, move to it using the following command:" }, { "code": null, "e": 24993, "s": 24979, "text": "cd foldername" }, { "code": null, "e": 25026, "s": 24993, "text": "Step 3: Install required modules" }, { "code": null, "e": 25085, "s": 25026, "text": "npm install @material-ui/core\nnpm install @material-ui/lab" }, { "code": null, "e": 25105, "s": 25085, "text": "Project Structure: " }, { "code": null, "e": 25235, "s": 25105, "text": "Example: 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": 25242, "s": 25235, "text": "App.js" }, { "code": "import React,{ Component } from 'react';import TextField from \"@material-ui/core/TextField\";import Autocomplete from \"@material-ui/lab/Autocomplete\"; class App extends Component { constructor(props) { super(props); this.state = { list: [ { title: \"Title 1\"}, { title: \"Title 2\"}, { title: \"Title 3\"}, { title: \"Title 4\"}, ] } } componentDidMount(){ // Take the Reference of Close Button const close = document.getElementsByClassName( \"MuiAutocomplete-clearIndicator\" )[0]; // Add a Click Event Listener to the button close.addEventListener(\"click\", () => { alert(\"Add your Own Functionality Here...\"); }); } render() { return ( <Autocomplete options={this.state.list} getOptionLabel={(option) => option.title} style={{ width: 300 }} renderInput={(params) => ( <TextField {...params} label=\"Combo box\" variant=\"outlined\" /> )} /> ); } } export default App;", "e": 26257, "s": 25242, "text": null }, { "code": null, "e": 26370, "s": 26257, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 26380, "s": 26370, "text": "npm start" }, { "code": null, "e": 26479, "s": 26380, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 26486, "s": 26479, "text": "Picked" }, { "code": null, "e": 26502, "s": 26486, "text": "React-Questions" }, { "code": null, "e": 26526, "s": 26502, "text": "Technical Scripter 2020" }, { "code": null, "e": 26534, "s": 26526, "text": "ReactJS" }, { "code": null, "e": 26553, "s": 26534, "text": "Technical Scripter" }, { "code": null, "e": 26570, "s": 26553, "text": "Web Technologies" }, { "code": null, "e": 26668, "s": 26570, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26713, "s": 26668, "text": "How to redirect to another page in ReactJS ?" }, { "code": null, "e": 26781, "s": 26713, "text": "How to pass data from one component to other component in ReactJS ?" }, { "code": null, "e": 26800, "s": 26781, "text": "ReactJS setState()" }, { "code": null, "e": 26835, "s": 26800, "text": "Re-rendering Components in ReactJS" }, { "code": null, "e": 26856, "s": 26835, "text": "ReactJS defaultProps" }, { "code": null, "e": 26898, "s": 26856, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 26931, "s": 26898, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 26993, "s": 26931, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 27043, "s": 26993, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
MySQL: selecting rows where a column is null?
To select rows where a column is null, you can use IS NULL from MySQL with the help of where clause. The syntax is as follows − select *from yourTableName where yourColumnName IS NULL; Let us first create a table to understand the concept − mysql> create table NULLDemo1 -> ( -> StudentId int, -> StudentName varchar(100) -> ); Query OK, 0 rows affected (1.48 sec) Inserting records into the table. The query to insert records is as follows − mysql> insert into NULLDemo1 values(NULL,'John'); Query OK, 1 row affected (0.25 sec) mysql> insert into NULLDemo1 values(100,'Johnson'); Query OK, 1 row affected (0.38 sec) mysql> insert into NULLDemo1 values(NULL,'Carol'); Query OK, 1 row affected (0.25 sec) mysql> insert into NULLDemo1 values(101,'Sam'); Query OK, 1 row affected (0.25 sec) Now you can display all the records with the help of select statement. The query is as follows − mysql> select *from NULLDemo1; The following is the output − +-----------+-------------+ | StudentId | StudentName | +-----------+-------------+ | NULL | John | | 100 | Johnson | | NULL | Carol | | 101 | Sam | +-----------+-------------+ 4 rows in set (0.00 sec) Apply the above syntax which was discussed in the beginning to select row where column is NULL. The query is as follows for the above table. mysql> select *from NULLDemo1 where StudentId IS NULL; Here is the output − +-----------+-------------+ | StudentId | StudentName | +-----------+-------------+ | NULL | John | | NULL | Carol | +-----------+-------------+ 2 rows in set (0.00 sec)
[ { "code": null, "e": 1163, "s": 1062, "text": "To select rows where a column is null, you can use IS NULL from MySQL with the help of where clause." }, { "code": null, "e": 1190, "s": 1163, "text": "The syntax is as follows −" }, { "code": null, "e": 1247, "s": 1190, "text": "select *from yourTableName where yourColumnName IS NULL;" }, { "code": null, "e": 1303, "s": 1247, "text": "Let us first create a table to understand the concept −" }, { "code": null, "e": 1439, "s": 1303, "text": "mysql> create table NULLDemo1\n -> (\n -> StudentId int,\n -> StudentName varchar(100)\n -> );\nQuery OK, 0 rows affected (1.48 sec)" }, { "code": null, "e": 1517, "s": 1439, "text": "Inserting records into the table. The query to insert records is as follows −" }, { "code": null, "e": 1862, "s": 1517, "text": "mysql> insert into NULLDemo1 values(NULL,'John');\nQuery OK, 1 row affected (0.25 sec)\nmysql> insert into NULLDemo1 values(100,'Johnson');\nQuery OK, 1 row affected (0.38 sec)\nmysql> insert into NULLDemo1 values(NULL,'Carol');\nQuery OK, 1 row affected (0.25 sec)\nmysql> insert into NULLDemo1 values(101,'Sam');\nQuery OK, 1 row affected (0.25 sec)" }, { "code": null, "e": 1959, "s": 1862, "text": "Now you can display all the records with the help of select statement. The query is as follows −" }, { "code": null, "e": 1990, "s": 1959, "text": "mysql> select *from NULLDemo1;" }, { "code": null, "e": 2020, "s": 1990, "text": "The following is the output −" }, { "code": null, "e": 2274, "s": 2020, "text": "+-----------+-------------+\n| StudentId | StudentName |\n+-----------+-------------+\n| NULL | John |\n| 100 | Johnson |\n| NULL | Carol | \n| 101 | Sam | \n+-----------+-------------+\n4 rows in set (0.00 sec)" }, { "code": null, "e": 2415, "s": 2274, "text": "Apply the above syntax which was discussed in the beginning to select row where column is NULL. The query is as follows for the above table." }, { "code": null, "e": 2470, "s": 2415, "text": "mysql> select *from NULLDemo1 where StudentId IS NULL;" }, { "code": null, "e": 2491, "s": 2470, "text": "Here is the output −" }, { "code": null, "e": 2684, "s": 2491, "text": "+-----------+-------------+\n| StudentId | StudentName |\n+-----------+-------------+\n| NULL | John |\n| NULL | Carol |\n+-----------+-------------+\n2 rows in set (0.00 sec)" } ]
Build your own AutoML in Power BI using PyCaret 2.0 | by Moez Ali | Towards Data Science
Last week we have announced PyCaret 2.0, an open source, low-code machine learning library in Python that automates machine learning workflow. It is an end-to-end machine learning and model management tool that speeds up machine learning experiment cycle and helps data scientists become more efficient and productive. In this post we present a step-by-step tutorial on how PyCaret can be used to build an Automated Machine Learning Solution within Power BI, thus allowing data scientists and analysts to add a layer of machine learning to their Dashboards without any additional license or software costs. PyCaret is an open source and free to use Python library that comes with a wide range of functions that are built to work within Power BI. By the end of this article you will learn how to implement the following in Power BI: Setting up Python conda environment and install pycaret==2.0. Link the newly created conda environment with Power BI. Build your first AutoML solution in Power BI and present the performance metrics on dashboard. Productionalize / deploy your AutoML solution in Power BI. Power BI is a business analytics solution that lets you visualize your data and share insights across your organization, or embed them in your app or website. In this tutorial, we will use Power BI Desktop for machine learning by importing the PyCaret library into Power BI. Automated machine learning (AutoML) is the process of automating the time consuming, iterative tasks of machine learning. It allows data scientists and analysts to build machine learning models with efficiency while sustaining the model quality. The final goal of any AutoML solution is to finalize the best model based on some performance criteria. Traditional machine learning model development process is resource-intensive, requiring significant domain knowledge and time to produce and compare dozens of models. With automated machine learning, you’ll accelerate the time it takes to get production-ready ML models with great ease and efficiency. PyCaret is a workflow automation tool for supervised and unsupervised machine learning. It is organized into six modules and each module has a set of functions available to perform some specific action. Each function takes an input and returns an output, which in most cases is a trained machine learning model. Modules available as of the second release are: Classification Regression Clustering Anomaly Detection Natural Language Processing Association Rule Mining All modules in PyCaret supports data preparation (over 25+ essential preprocessing techniques, comes with a huge collection of untrained models & support for custom models, automatic hyperparameter tuning, model analysis and interpretability, automatic model selection, experiment logging and easy cloud deployment options. To learn more about PyCaret, click here to read our official release announcement. If you want to get started in Python, click here to see a gallery of example notebooks to get started. “PyCaret is democratizing machine learning and the use of advanced analytics by providing free, open source, and low-code machine learning solution for business analysts, domain experts, citizen data scientists, and experienced data scientists”. If you are using Python for the first time, installing Anaconda Distribution is the easiest way to get started. Click here to download Anaconda Distribution with Python 3.7 or greater. Before we start using PyCaret’s machine learning capabilities in Power BI we need to create a virtual environment and install pycaret. This is a three-step process: ✅ Step 1 — Creating an anaconda environment Open Anaconda Prompt from start menu and execute the following code: conda create --name myenv python=3.7 ✅ Step 2 — Installing PyCaret Execute the following code in Anaconda Prompt: pip install pycaret==2.0 Installation may take 15–20 minutes. If you are having issues with installation, please see our GitHub page for known issues and resolutions. ✅Step 3 — Setting up a Python Directory in Power BI The virtual environment created must be linked with Power BI. This can be done using Global Settings in Power BI Desktop (File → Options → Global → Python scripting). Anaconda Environment by default is installed under: C:\Users\username\AppData\Local\Continuum\anaconda3\envs\myenv An insurance company wants to improve its cash flow forecasting by better predicting the patient charges using the demographic and basic patient health risk metrics at the time of hospitalization. (data source) To train and select the best performing regression model that predicts patient charges based on the other variables in the dataset i.e. age, sex, bmi, children, smoker, and region. You can load dataset directly from out GitHub by going to Power BI Desktop → Get Data → Web Link to dataset: https://raw.githubusercontent.com/pycaret/pycaret/master/datasets/insurance.csv Create a duplicate dataset in Power Query: Run the following code in Power Query (Transform → Run Python script): # import regression modulefrom pycaret.regression import *# init setupreg1 = setup(data=dataset, target = 'charges', silent = True, html = False)# compare modelsbest_model = compare_models()# finalize best modelbest = finalize_model(best_model)# save best modelsave_model(best, 'c:/users/moezs/best-model-power')# return the performance metrics dfdataset = pull() The first two line of code is for importing the relevant module and initializing the setup function. The setup function performs several imperative steps required in machine learning such as cleaning missing values (if any), splitting the data into train and test, setting up cross validation strategy, defining metrics, performing algorithm-specific transformations etc. The magic function that trains multiple models, compares and evaluates performance metrics is compare_models. It returns the best model based on ‘sort’ parameter that can be defined inside compare_models. By default, it uses ‘R2’ for regression use-case and ‘Accuracy’ for classification use-case. Rest of the lines are for finalizing the best model returned through compare_models and saving it as a pickle file in your local diretory. Last line returns the dataframe with details of model trained and their performance metrics. Output: With just few lines we have trained over 20 models and the table presents the performance metrics based on 10 fold cross validation. Top performing model Gradient Boosting Regressor will be saved along with the entire transformation pipeline as a pickle file in your local directory. This file can be consumed later to generate predictions on a new dataset (see step 3 below). PyCaret works on the idea of modular automation. As such if you have more resources and time for training you can extend the script to perform hyperparameter tuning, ensembling, and other available modeling techniques. See example below: # import regression modulefrom pycaret.regression import *# init setupreg1 = setup(data=dataset, target = 'charges', silent = True, html = False)# compare modelstop5 = compare_models(n_select = 5)results = pull()# tune top5 modelstuned_top5 = [tune_model(i) for i in top5]# select best modelbest = automl()# save best modelsave_model(best, 'c:/users/moezs/best-model-power')# return the performance metrics dfdataset = results We have now returned top 5 models instead of the one highest performing model. We have then created a list comprehension (loop) to tune hyperparameters of top candidate models and then finally automl function selects the single best performing model which is then saved as a pickle file (Note that we didn’t use finalize_model this time because automl function returns the finalized model). Sample dashboard is created. PBIX file is uploaded here. Once we have a final model saved as a pickle file we can use it to predict charges on the new dataset. For demonstration purposes, we will load the same dataset again and remove the ‘charges’ column from the dataset. Execute the following code as a Python script in Power Query to get the predictions: # load functions from regression modulefrom pycaret.regression import load_model, predict_model# load model in a variablemodel = load_model(‘c:/users/moezs/best-model-powerbi’)# predict chargesdataset = predict_model(model, data=dataset) Output : When you publish a Power BI report with Python scripts to the service, these scripts will also be executed when your data is refreshed through the on-premises data gateway. To enable this, you must ensure that the Python runtime with the dependent Python packages are also installed on the machine hosting your personal gateway. Note, Python script execution is not supported for on-premises data gateways shared by multiple users. Click here to read more about this. PBIX files used in this tutorial is uploaded on this GitHub Repository: https://github.com/pycaret/pycaret-powerbi-automl If you would like to learn more about PyCaret 2.0, read this announcement. If you have used PyCaret before, you might be interested in release notes for current release. There is no limit to what you can achieve using this light-weight workflow automation library in Python. If you find this useful, please do not forget to give us ⭐️ on our github repo. To hear more about PyCaret follow us on LinkedIn and Youtube. Machine Learning in Power BI using PyCaretBuild your first Anomaly Detector in Power BI using PyCaretHow to implement Clustering in Power BI using PyCaretTopic Modeling in Power BI using PyCaret BlogRelease Notes for PyCaret 2.0User Guide / DocumentationGithub StackoverflowInstall PyCaretNotebook TutorialsContribute in PyCaret Click on the links below to see the documentation and working examples. ClassificationRegressionClusteringAnomaly DetectionNatural Language ProcessingAssociation Rule Mining
[ { "code": null, "e": 490, "s": 171, "text": "Last week we have announced PyCaret 2.0, an open source, low-code machine learning library in Python that automates machine learning workflow. It is an end-to-end machine learning and model management tool that speeds up machine learning experiment cycle and helps data scientists become more efficient and productive." }, { "code": null, "e": 917, "s": 490, "text": "In this post we present a step-by-step tutorial on how PyCaret can be used to build an Automated Machine Learning Solution within Power BI, thus allowing data scientists and analysts to add a layer of machine learning to their Dashboards without any additional license or software costs. PyCaret is an open source and free to use Python library that comes with a wide range of functions that are built to work within Power BI." }, { "code": null, "e": 1003, "s": 917, "text": "By the end of this article you will learn how to implement the following in Power BI:" }, { "code": null, "e": 1065, "s": 1003, "text": "Setting up Python conda environment and install pycaret==2.0." }, { "code": null, "e": 1121, "s": 1065, "text": "Link the newly created conda environment with Power BI." }, { "code": null, "e": 1216, "s": 1121, "text": "Build your first AutoML solution in Power BI and present the performance metrics on dashboard." }, { "code": null, "e": 1275, "s": 1216, "text": "Productionalize / deploy your AutoML solution in Power BI." }, { "code": null, "e": 1550, "s": 1275, "text": "Power BI is a business analytics solution that lets you visualize your data and share insights across your organization, or embed them in your app or website. In this tutorial, we will use Power BI Desktop for machine learning by importing the PyCaret library into Power BI." }, { "code": null, "e": 1900, "s": 1550, "text": "Automated machine learning (AutoML) is the process of automating the time consuming, iterative tasks of machine learning. It allows data scientists and analysts to build machine learning models with efficiency while sustaining the model quality. The final goal of any AutoML solution is to finalize the best model based on some performance criteria." }, { "code": null, "e": 2202, "s": 1900, "text": "Traditional machine learning model development process is resource-intensive, requiring significant domain knowledge and time to produce and compare dozens of models. With automated machine learning, you’ll accelerate the time it takes to get production-ready ML models with great ease and efficiency." }, { "code": null, "e": 2562, "s": 2202, "text": "PyCaret is a workflow automation tool for supervised and unsupervised machine learning. It is organized into six modules and each module has a set of functions available to perform some specific action. Each function takes an input and returns an output, which in most cases is a trained machine learning model. Modules available as of the second release are:" }, { "code": null, "e": 2577, "s": 2562, "text": "Classification" }, { "code": null, "e": 2588, "s": 2577, "text": "Regression" }, { "code": null, "e": 2599, "s": 2588, "text": "Clustering" }, { "code": null, "e": 2617, "s": 2599, "text": "Anomaly Detection" }, { "code": null, "e": 2645, "s": 2617, "text": "Natural Language Processing" }, { "code": null, "e": 2669, "s": 2645, "text": "Association Rule Mining" }, { "code": null, "e": 2993, "s": 2669, "text": "All modules in PyCaret supports data preparation (over 25+ essential preprocessing techniques, comes with a huge collection of untrained models & support for custom models, automatic hyperparameter tuning, model analysis and interpretability, automatic model selection, experiment logging and easy cloud deployment options." }, { "code": null, "e": 3076, "s": 2993, "text": "To learn more about PyCaret, click here to read our official release announcement." }, { "code": null, "e": 3179, "s": 3076, "text": "If you want to get started in Python, click here to see a gallery of example notebooks to get started." }, { "code": null, "e": 3425, "s": 3179, "text": "“PyCaret is democratizing machine learning and the use of advanced analytics by providing free, open source, and low-code machine learning solution for business analysts, domain experts, citizen data scientists, and experienced data scientists”." }, { "code": null, "e": 3610, "s": 3425, "text": "If you are using Python for the first time, installing Anaconda Distribution is the easiest way to get started. Click here to download Anaconda Distribution with Python 3.7 or greater." }, { "code": null, "e": 3775, "s": 3610, "text": "Before we start using PyCaret’s machine learning capabilities in Power BI we need to create a virtual environment and install pycaret. This is a three-step process:" }, { "code": null, "e": 3819, "s": 3775, "text": "✅ Step 1 — Creating an anaconda environment" }, { "code": null, "e": 3888, "s": 3819, "text": "Open Anaconda Prompt from start menu and execute the following code:" }, { "code": null, "e": 3925, "s": 3888, "text": "conda create --name myenv python=3.7" }, { "code": null, "e": 3955, "s": 3925, "text": "✅ Step 2 — Installing PyCaret" }, { "code": null, "e": 4002, "s": 3955, "text": "Execute the following code in Anaconda Prompt:" }, { "code": null, "e": 4027, "s": 4002, "text": "pip install pycaret==2.0" }, { "code": null, "e": 4169, "s": 4027, "text": "Installation may take 15–20 minutes. If you are having issues with installation, please see our GitHub page for known issues and resolutions." }, { "code": null, "e": 4221, "s": 4169, "text": "✅Step 3 — Setting up a Python Directory in Power BI" }, { "code": null, "e": 4440, "s": 4221, "text": "The virtual environment created must be linked with Power BI. This can be done using Global Settings in Power BI Desktop (File → Options → Global → Python scripting). Anaconda Environment by default is installed under:" }, { "code": null, "e": 4503, "s": 4440, "text": "C:\\Users\\username\\AppData\\Local\\Continuum\\anaconda3\\envs\\myenv" }, { "code": null, "e": 4700, "s": 4503, "text": "An insurance company wants to improve its cash flow forecasting by better predicting the patient charges using the demographic and basic patient health risk metrics at the time of hospitalization." }, { "code": null, "e": 4714, "s": 4700, "text": "(data source)" }, { "code": null, "e": 4895, "s": 4714, "text": "To train and select the best performing regression model that predicts patient charges based on the other variables in the dataset i.e. age, sex, bmi, children, smoker, and region." }, { "code": null, "e": 4987, "s": 4895, "text": "You can load dataset directly from out GitHub by going to Power BI Desktop → Get Data → Web" }, { "code": null, "e": 5084, "s": 4987, "text": "Link to dataset: https://raw.githubusercontent.com/pycaret/pycaret/master/datasets/insurance.csv" }, { "code": null, "e": 5127, "s": 5084, "text": "Create a duplicate dataset in Power Query:" }, { "code": null, "e": 5198, "s": 5127, "text": "Run the following code in Power Query (Transform → Run Python script):" }, { "code": null, "e": 5562, "s": 5198, "text": "# import regression modulefrom pycaret.regression import *# init setupreg1 = setup(data=dataset, target = 'charges', silent = True, html = False)# compare modelsbest_model = compare_models()# finalize best modelbest = finalize_model(best_model)# save best modelsave_model(best, 'c:/users/moezs/best-model-power')# return the performance metrics dfdataset = pull()" }, { "code": null, "e": 5934, "s": 5562, "text": "The first two line of code is for importing the relevant module and initializing the setup function. The setup function performs several imperative steps required in machine learning such as cleaning missing values (if any), splitting the data into train and test, setting up cross validation strategy, defining metrics, performing algorithm-specific transformations etc." }, { "code": null, "e": 6232, "s": 5934, "text": "The magic function that trains multiple models, compares and evaluates performance metrics is compare_models. It returns the best model based on ‘sort’ parameter that can be defined inside compare_models. By default, it uses ‘R2’ for regression use-case and ‘Accuracy’ for classification use-case." }, { "code": null, "e": 6464, "s": 6232, "text": "Rest of the lines are for finalizing the best model returned through compare_models and saving it as a pickle file in your local diretory. Last line returns the dataframe with details of model trained and their performance metrics." }, { "code": null, "e": 6472, "s": 6464, "text": "Output:" }, { "code": null, "e": 6605, "s": 6472, "text": "With just few lines we have trained over 20 models and the table presents the performance metrics based on 10 fold cross validation." }, { "code": null, "e": 6849, "s": 6605, "text": "Top performing model Gradient Boosting Regressor will be saved along with the entire transformation pipeline as a pickle file in your local directory. This file can be consumed later to generate predictions on a new dataset (see step 3 below)." }, { "code": null, "e": 7087, "s": 6849, "text": "PyCaret works on the idea of modular automation. As such if you have more resources and time for training you can extend the script to perform hyperparameter tuning, ensembling, and other available modeling techniques. See example below:" }, { "code": null, "e": 7514, "s": 7087, "text": "# import regression modulefrom pycaret.regression import *# init setupreg1 = setup(data=dataset, target = 'charges', silent = True, html = False)# compare modelstop5 = compare_models(n_select = 5)results = pull()# tune top5 modelstuned_top5 = [tune_model(i) for i in top5]# select best modelbest = automl()# save best modelsave_model(best, 'c:/users/moezs/best-model-power')# return the performance metrics dfdataset = results" }, { "code": null, "e": 7905, "s": 7514, "text": "We have now returned top 5 models instead of the one highest performing model. We have then created a list comprehension (loop) to tune hyperparameters of top candidate models and then finally automl function selects the single best performing model which is then saved as a pickle file (Note that we didn’t use finalize_model this time because automl function returns the finalized model)." }, { "code": null, "e": 7962, "s": 7905, "text": "Sample dashboard is created. PBIX file is uploaded here." }, { "code": null, "e": 8065, "s": 7962, "text": "Once we have a final model saved as a pickle file we can use it to predict charges on the new dataset." }, { "code": null, "e": 8264, "s": 8065, "text": "For demonstration purposes, we will load the same dataset again and remove the ‘charges’ column from the dataset. Execute the following code as a Python script in Power Query to get the predictions:" }, { "code": null, "e": 8502, "s": 8264, "text": "# load functions from regression modulefrom pycaret.regression import load_model, predict_model# load model in a variablemodel = load_model(‘c:/users/moezs/best-model-powerbi’)# predict chargesdataset = predict_model(model, data=dataset)" }, { "code": null, "e": 8511, "s": 8502, "text": "Output :" }, { "code": null, "e": 8684, "s": 8511, "text": "When you publish a Power BI report with Python scripts to the service, these scripts will also be executed when your data is refreshed through the on-premises data gateway." }, { "code": null, "e": 8979, "s": 8684, "text": "To enable this, you must ensure that the Python runtime with the dependent Python packages are also installed on the machine hosting your personal gateway. Note, Python script execution is not supported for on-premises data gateways shared by multiple users. Click here to read more about this." }, { "code": null, "e": 9101, "s": 8979, "text": "PBIX files used in this tutorial is uploaded on this GitHub Repository: https://github.com/pycaret/pycaret-powerbi-automl" }, { "code": null, "e": 9176, "s": 9101, "text": "If you would like to learn more about PyCaret 2.0, read this announcement." }, { "code": null, "e": 9271, "s": 9176, "text": "If you have used PyCaret before, you might be interested in release notes for current release." }, { "code": null, "e": 9456, "s": 9271, "text": "There is no limit to what you can achieve using this light-weight workflow automation library in Python. If you find this useful, please do not forget to give us ⭐️ on our github repo." }, { "code": null, "e": 9518, "s": 9456, "text": "To hear more about PyCaret follow us on LinkedIn and Youtube." }, { "code": null, "e": 9713, "s": 9518, "text": "Machine Learning in Power BI using PyCaretBuild your first Anomaly Detector in Power BI using PyCaretHow to implement Clustering in Power BI using PyCaretTopic Modeling in Power BI using PyCaret" }, { "code": null, "e": 9847, "s": 9713, "text": "BlogRelease Notes for PyCaret 2.0User Guide / DocumentationGithub StackoverflowInstall PyCaretNotebook TutorialsContribute in PyCaret" }, { "code": null, "e": 9919, "s": 9847, "text": "Click on the links below to see the documentation and working examples." } ]
Area of the biggest ellipse inscribed within a rectangle - GeeksforGeeks
18 Mar, 2021 Given here is a rectangle of length l & breadth b, the task is to find the area of the biggest ellipse that can be inscribed within it.Examples: Input: l = 5, b = 3 Output: 11.775 Input: 7, b = 4 Output: 21.98 Approach: Let, the length of the major axis of the ellipse = 2x and the length of the minor axis of the ellipse = 2yFrom the diagram, it is very clear that, 2x = l 2y = b So, Area of the ellipse = (π * x * y) = (π * l * b) / 4 Let, the length of the major axis of the ellipse = 2x and the length of the minor axis of the ellipse = 2y From the diagram, it is very clear that, 2x = l 2y = b So, Area of the ellipse = (π * x * y) = (π * l * b) / 4 Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ Program to find the biggest ellipse// which can be inscribed within the rectangle #include <bits/stdc++.h>using namespace std; // Function to find the area// of the ellipsefloat ellipse(float l, float b){ // The sides cannot be negative if (l < 0 || b < 0) return -1; // Area of the ellipse float x = (3.14 * l * b) / 4; return x;} // Driver codeint main(){ float l = 5, b = 3; cout << ellipse(l, b) << endl; return 0;} // Java Program to find the biggest rectangle// which can be inscribed within the ellipseimport java.util.*;import java.lang.*;import java.io.*; class GFG{ // Function to find the area// of the rectanglestatic float ellipse(float l, float b){ // a and b cannot be negative if (l < 0 || b < 0) return -1; float x = (float)(3.14 * l * b) / 4; return x; } // Driver codepublic static void main(String args[]){ float a = 5, b = 3; System.out.println(ellipse(a, b));}} // This code is contributed// by Mohit Kumar # Python3 Program to find the biggest ellipse# which can be inscribed within the rectangle # Function to find the area# of the ellipsedef ellipse(l, b): # The sides cannot be negative if l < 0 or b < 0: return -1 # Area of the ellipse x = (3.14 * l * b) / 4 return x # Driver codeif __name__ == "__main__": l, b = 5, 3 print(ellipse(l, b)) # This code is contributed# by Rituraj Jain // C# Program to find the biggest rectangle// which can be inscribed within the ellipseusing System; class GFG{ // Function to find the area// of the rectanglestatic float ellipse(float l, float b){ // a and b cannot be negative if (l < 0 || b < 0) return -1; float x = (float)(3.14 * l * b) / 4; return x; } // Driver codepublic static void Main(){ float a = 5, b = 3; Console.WriteLine(ellipse(a, b));}} // This code is contributed// by Code_Mech. <?php// PHP Program to find the biggest ellipse// which can be inscribed within the rectangle // Function to find the area// of the ellipsefunction ellipse($l, $b){ // The sides cannot be negative if ($l < 0 || $b < 0) return -1; // Area of the ellipse $x = (3.14 * $l * $b) / 4; return $x;} // Driver code$l = 5; $b = 3;echo ellipse($l, $b) . "\n"; // This code is contributed// by Akanksha Rai?> <script> // javascript Program to find the biggest rectangle// which can be inscribed within the ellipse // Function to find the area// of the rectanglefunction ellipse(l , b){ // a and b cannot be negative if (l < 0 || b < 0) return -1; var x = (3.14 * l * b) / 4; return x; } // Driver code var a = 5, b = 3;document.write(ellipse(a, b)); // This code is contributed by Amit Katiyar </script> 11.775 rituraj_jain mohit kumar 29 Akanksha_Rai Code_Mech amit143katiyar area-volume-programs school-programming Geometric Mathematical Mathematical Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Given n line segments, find if any two segments intersect Program to check if three points are collinear Closest Pair of Points | O(nlogn) Implementation Check if a point lies inside a rectangle | Set-2 C++ Program to Illustrate Trigonometric functions 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": 24935, "s": 24907, "text": "\n18 Mar, 2021" }, { "code": null, "e": 25082, "s": 24935, "text": "Given here is a rectangle of length l & breadth b, the task is to find the area of the biggest ellipse that can be inscribed within it.Examples: " }, { "code": null, "e": 25148, "s": 25082, "text": "Input: l = 5, b = 3\nOutput: 11.775\n\nInput: 7, b = 4\nOutput: 21.98" }, { "code": null, "e": 25164, "s": 25152, "text": "Approach: " }, { "code": null, "e": 25382, "s": 25164, "text": "Let, the length of the major axis of the ellipse = 2x and the length of the minor axis of the ellipse = 2yFrom the diagram, it is very clear that, 2x = l 2y = b So, Area of the ellipse = (π * x * y) = (π * l * b) / 4" }, { "code": null, "e": 25489, "s": 25382, "text": "Let, the length of the major axis of the ellipse = 2x and the length of the minor axis of the ellipse = 2y" }, { "code": null, "e": 25546, "s": 25489, "text": "From the diagram, it is very clear that, 2x = l 2y = b " }, { "code": null, "e": 25602, "s": 25546, "text": "So, Area of the ellipse = (π * x * y) = (π * l * b) / 4" }, { "code": null, "e": 25654, "s": 25602, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 25658, "s": 25654, "text": "C++" }, { "code": null, "e": 25663, "s": 25658, "text": "Java" }, { "code": null, "e": 25671, "s": 25663, "text": "Python3" }, { "code": null, "e": 25674, "s": 25671, "text": "C#" }, { "code": null, "e": 25678, "s": 25674, "text": "PHP" }, { "code": null, "e": 25689, "s": 25678, "text": "Javascript" }, { "code": "// C++ Program to find the biggest ellipse// which can be inscribed within the rectangle #include <bits/stdc++.h>using namespace std; // Function to find the area// of the ellipsefloat ellipse(float l, float b){ // The sides cannot be negative if (l < 0 || b < 0) return -1; // Area of the ellipse float x = (3.14 * l * b) / 4; return x;} // Driver codeint main(){ float l = 5, b = 3; cout << ellipse(l, b) << endl; return 0;}", "e": 26151, "s": 25689, "text": null }, { "code": "// Java Program to find the biggest rectangle// which can be inscribed within the ellipseimport java.util.*;import java.lang.*;import java.io.*; class GFG{ // Function to find the area// of the rectanglestatic float ellipse(float l, float b){ // a and b cannot be negative if (l < 0 || b < 0) return -1; float x = (float)(3.14 * l * b) / 4; return x; } // Driver codepublic static void main(String args[]){ float a = 5, b = 3; System.out.println(ellipse(a, b));}} // This code is contributed// by Mohit Kumar", "e": 26703, "s": 26151, "text": null }, { "code": "# Python3 Program to find the biggest ellipse# which can be inscribed within the rectangle # Function to find the area# of the ellipsedef ellipse(l, b): # The sides cannot be negative if l < 0 or b < 0: return -1 # Area of the ellipse x = (3.14 * l * b) / 4 return x # Driver codeif __name__ == \"__main__\": l, b = 5, 3 print(ellipse(l, b)) # This code is contributed# by Rituraj Jain", "e": 27119, "s": 26703, "text": null }, { "code": "// C# Program to find the biggest rectangle// which can be inscribed within the ellipseusing System; class GFG{ // Function to find the area// of the rectanglestatic float ellipse(float l, float b){ // a and b cannot be negative if (l < 0 || b < 0) return -1; float x = (float)(3.14 * l * b) / 4; return x; } // Driver codepublic static void Main(){ float a = 5, b = 3; Console.WriteLine(ellipse(a, b));}} // This code is contributed// by Code_Mech.", "e": 27612, "s": 27119, "text": null }, { "code": "<?php// PHP Program to find the biggest ellipse// which can be inscribed within the rectangle // Function to find the area// of the ellipsefunction ellipse($l, $b){ // The sides cannot be negative if ($l < 0 || $b < 0) return -1; // Area of the ellipse $x = (3.14 * $l * $b) / 4; return $x;} // Driver code$l = 5; $b = 3;echo ellipse($l, $b) . \"\\n\"; // This code is contributed// by Akanksha Rai?>", "e": 28035, "s": 27612, "text": null }, { "code": "<script> // javascript Program to find the biggest rectangle// which can be inscribed within the ellipse // Function to find the area// of the rectanglefunction ellipse(l , b){ // a and b cannot be negative if (l < 0 || b < 0) return -1; var x = (3.14 * l * b) / 4; return x; } // Driver code var a = 5, b = 3;document.write(ellipse(a, b)); // This code is contributed by Amit Katiyar </script>", "e": 28466, "s": 28035, "text": null }, { "code": null, "e": 28473, "s": 28466, "text": "11.775" }, { "code": null, "e": 28488, "s": 28475, "text": "rituraj_jain" }, { "code": null, "e": 28503, "s": 28488, "text": "mohit kumar 29" }, { "code": null, "e": 28516, "s": 28503, "text": "Akanksha_Rai" }, { "code": null, "e": 28526, "s": 28516, "text": "Code_Mech" }, { "code": null, "e": 28541, "s": 28526, "text": "amit143katiyar" }, { "code": null, "e": 28562, "s": 28541, "text": "area-volume-programs" }, { "code": null, "e": 28581, "s": 28562, "text": "school-programming" }, { "code": null, "e": 28591, "s": 28581, "text": "Geometric" }, { "code": null, "e": 28604, "s": 28591, "text": "Mathematical" }, { "code": null, "e": 28617, "s": 28604, "text": "Mathematical" }, { "code": null, "e": 28627, "s": 28617, "text": "Geometric" }, { "code": null, "e": 28725, "s": 28627, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28734, "s": 28725, "text": "Comments" }, { "code": null, "e": 28747, "s": 28734, "text": "Old Comments" }, { "code": null, "e": 28805, "s": 28747, "text": "Given n line segments, find if any two segments intersect" }, { "code": null, "e": 28852, "s": 28805, "text": "Program to check if three points are collinear" }, { "code": null, "e": 28901, "s": 28852, "text": "Closest Pair of Points | O(nlogn) Implementation" }, { "code": null, "e": 28950, "s": 28901, "text": "Check if a point lies inside a rectangle | Set-2" }, { "code": null, "e": 29000, "s": 28950, "text": "C++ Program to Illustrate Trigonometric functions" }, { "code": null, "e": 29030, "s": 29000, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 29090, "s": 29030, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 29105, "s": 29090, "text": "C++ Data Types" }, { "code": null, "e": 29148, "s": 29105, "text": "Set in C++ Standard Template Library (STL)" } ]
6 Tips for Interpretable Topic Models | by Nicha Ruchirawat | Towards Data Science
With so much text outputted on digital platforms, the ability to automatically understand key topic trends can reveal tremendous insight. For example, businesses can benefit from understanding customer conversation trends around their brand and products. A common method to pick up key topics is Latent Dirichlet Allocation (LDA). However, outputs are often difficult to interpret for useful insights. We will explore techniques to enhance interpretability. Latent Dirichlet Allocation (LDA) is a generative statistical model that helps pick up similarities across a collection of different data parts. In topic modeling, each data part is a word document (e.g. a single review on a product page) and the collection of documents is a corpus (e.g. all users’ reviews for a product page). Similar sets of words occurring repeatedly may likely indicate topics. LDA assumes that each document is represented by a distribution of a fixed number of topics, and each topic is a distribution of words. Algorithm’s high level key steps to approximate these distributions: User select K, the number of topics present, tuned to fit each dataset.Go through each document, and randomly assign each word to one of K topics. From this, we have a starting point for calculating document distribution of topics p(topic t|document d), proportion of words in document d that are assigned to topic t. We can also calculate topic distribution of words p(word w|topic t), proportion of word w in all documents’ words that are assigned to topic t. These will be poor approximations due to randomness.To improve approximations, we iterate through each document. For each document, go through each word and reassign a new topic, where we choose topic t with a probability p(topic t|document d) ∗p(word w|topic t) based on last round’s distribution. This is essentially the probability that topic t generated word w. Recalculate p(topic t|document d) and p(word w|topic t) from these new assignments.Keep iterating until topic/word assignments reach a steady state and no longer change much, (i.e. converge). Use final assignments to estimate topic mixtures of each document (% words assigned to each topic within that document) and word associated to each topic (% times that word is assigned to each topic overall). User select K, the number of topics present, tuned to fit each dataset. Go through each document, and randomly assign each word to one of K topics. From this, we have a starting point for calculating document distribution of topics p(topic t|document d), proportion of words in document d that are assigned to topic t. We can also calculate topic distribution of words p(word w|topic t), proportion of word w in all documents’ words that are assigned to topic t. These will be poor approximations due to randomness. To improve approximations, we iterate through each document. For each document, go through each word and reassign a new topic, where we choose topic t with a probability p(topic t|document d) ∗p(word w|topic t) based on last round’s distribution. This is essentially the probability that topic t generated word w. Recalculate p(topic t|document d) and p(word w|topic t) from these new assignments. Keep iterating until topic/word assignments reach a steady state and no longer change much, (i.e. converge). Use final assignments to estimate topic mixtures of each document (% words assigned to each topic within that document) and word associated to each topic (% times that word is assigned to each topic overall). We will explore techniques to optimize interpretability using LDA on Amazon Office Product reviews. To prepare the reviews data, we clean the reviews text with typical text cleaning steps: Remove non-ascii characters, such as À μ ∅ ©‘Lemmatize’ words, which transform words to its most basic form, such as ‘running’ and ‘ran’ to ‘run’ so that they are recognized as the same wordRemove punctuationRemove non-English comments if present Remove non-ascii characters, such as À μ ∅ © ‘Lemmatize’ words, which transform words to its most basic form, such as ‘running’ and ‘ran’ to ‘run’ so that they are recognized as the same word Remove punctuation Remove non-English comments if present All code in the tutorial can be found here, where the functions for cleaning are located in clean_text.py. The main notebook for the whole process is topic_model.ipynb. Tip #1: Identify phrases through n-grams and filter noun-type structures We want to identify phrases so the topic model can recognize them. Bigrams are phrases containing 2 words e.g. ‘social media’. Likewise, trigrams are phrases containing 3 words e.g. ‘Proctor and Gamble’. There are many ways to detect n-grams, explained here. In this example, we will use Pointwise Mutual Information (PMI) score. This measures how much more likely the words co-occur than if they were independent. The metric is sensitive to rare combination of words, so it is used with an occurrence frequency filter to ensure phrase relevance. Bigram example below (trigram code included in Jupyter Notebook): # Example for detecting bigrams bigram_measures = nltk.collocations.BigramAssocMeasures()finder =nltk.collocations.BigramCollocationFinder\.from_documents([comment.split() for comment in\ clean_reviews.reviewText])# Filter only those that occur at least 50 timesfinder.apply_freq_filter(50)bigram_scores = finder.score_ngrams(bigram_measures.pmi) Additionally, we filter bigrams or trigrams with noun structures. This helps the LDA model better cluster topics, as nouns are better indicators of a topic being talked about. We use NLTK package to tag part of speech and filter these structures. # Example filter for noun-type structures bigramsdef bigram_filter(bigram): tag = nltk.pos_tag(bigram) if tag[0][1] not in ['JJ', 'NN'] and tag[1][1] not in ['NN']: return False if bigram[0] in stop_word_list or bigram[1] in stop_word_list: return False if 'n' in bigram or 't' in bigram: return False if 'PRON' in bigram: return False return True# Can eyeball list and choose PMI threshold where n-grams stop making sense# In this case, get top 500 bigrams/trigrams with highest PMI scorefiltered_bigram = bigram_pmi[bigram_pmi.apply(lambda bigram:\ bigram_filter(bigram['bigram'])\and bigram.pmi > 5, axis = 1)][:500]bigrams = [' '.join(x) for x in filtered_bigram.bigram.values\if len(x[0]) > 2 or len(x[1]) > 2] Lastly, we concatenate these phrases together into one word. def replace_ngram(x): for gram in bigrams: x = x.replace(gram, '_'.join(gram.split())) for gram in trigrams: x = x.replace(gram, '_'.join(gram.split())) return xreviews_w_ngrams = clean_reviews.copy()reviews_w_ngrams.reviewText = reviews_w_ngrams.reviewText\.map(lambda x: replace_ngram(x)) Tip #2: Filter remaining words for nouns In the sentence, ‘The store is nice’, we know the sentence is talking about ‘store’. The other words in the sentence provide more context and explanation about the topic (‘store’) itself. Therefore, filtering for noun extracts words that are more interpretable for the topic model. An alternative is also to filter for both nouns and verbs. # Tokenize reviews + remove stop words + remove names + remove words with less than 2 charactersreviews_w_ngrams = reviews_w_ngrams.reviewText.map(lambda x: [word for word in x.split()\if word not in stop_word_list\and word not in english_names\and len(word) > 2])# Filter for only nounsdef noun_only(x): pos_comment = nltk.pos_tag(x) filtered =[word[0] for word in pos_comment if word[1] in ['NN']] return filteredfinal_reviews = reviews_w_ngrams.map(noun_only) Tip #3: Optimize choice for number of topics through coherence measure LDA requires specifying the number of topics. We can tune this through optimization of measures such as predictive likelihood, perplexity, and coherence. Much literature has indicated that maximizing a coherence measure, named Cv [1], leads to better human interpretability. We can test out a number of topics and asses the Cv measure: coherence = []for k in range(5,25): print('Round: '+str(k)) Lda = gensim.models.ldamodel.LdaModel ldamodel = Lda(doc_term_matrix, num_topics=k, \ id2word = dictionary, passes=40,\ iterations=200, chunksize = 10000, eval_every = None) cm = gensim.models.coherencemodel.CoherenceModel(\ model=ldamodel, texts=final_reviews,\ dictionary=dictionary, coherence='c_v') coherence.append((k,cm.get_coherence())) Plotting this shows: The improvement stops significantly improving after 15 topics. It is not always best where the highest Cv is, so we can try multiple to find the best result. We tried 15 and 23 here, and 23 yielded clearer results. Adding topics can help reveal further sub topics. Nonetheless, if the same words start to appear across multiple topics, the number of topics is too high. Tip #4: Adjust LDA hyperparameters Lda2 = gensim.models.ldamodel.LdaModelldamodel2 = Lda(doc_term_matrix, num_topics=23, id2word = dictionary, passes=40,iterations=200, chunksize = 10000, eval_every = None, random_state=0) If your topics still do not make sense, try increasing passes and iterations, while increasing chunksize to the extent your memory can handle. chunksize is the number of documents to be loaded into memory each time for training.passes is the number of training iterations through the entire corpus. iterations is the maximum iterations over each document to reach convergence — limiting this means that some documents may not converge in time. If the training corpus has 200 documents, chunksize is 100, passes is 2, and iterations is 10, algorithm goes through these rounds: Round #1: documents 0–99Round #2: documents 100–199Round #3: documents 0–99Round #4: documents 100–199 Each round will iterate each document’s probability distribution assignments for a maximum of 10 times, moving to the next document before 10 times if it already reached convergence. This is basically algorithm’s key steps 2–4 explained earlier, repeated for the number of passes, while step 3 is repeated for 10 iterationsor less. The topic distributions for entire corpus is updated after each chunksize, and after each passes. Increasing chunksize to the extent your memory can handle will increase speed as topic distribution update is expensive. However, increasing chunksize requires increasing number of passes to ensure sufficient corpus topic distribution updates, especially in small corpuses. iterations also needs to be high enough to ensure a good amount of documents reach convergence before moving on. We can try increasing these parameters when topics still don’t make sense, but logging can also help debug: import logginglogging.basicConfig(filename='gensim.log', format="%(asctime)s:%(levelname)s:%(message)s", level=logging.INFO) Look for a lines that look like this in the log, which will repeat for the number of passes that you set: 2020-07-21 06:44:16,300 - gensim.models.ldamodel - DEBUG - 100/35600 documents converged within 200 iterations By the end of the passes, most of the documents should have converged. If not, increase passes and iterations. Tip #5: Use pyLDAvis to visualize topic relationships The pyLDAvis [2] package in Python gives two important pieces of information. The circles represent each topic. The distance between the circles visualizes topic relatedness. These are mapped through dimensionality reduction (PCA/t-sne) on distances between each topic’s probability distributions into 2D space. This shows whether our model developed distinct topics. We want to tune model parameters and number of topics to minimize circle overlap. Topic distance also shows how related topics are. Topics 1,2,13 clustered together talk about electronics (printers, scanners, phone/fax). Topics in quadrant 3 such as 6,14,19 are about office stationary (packaging materials, post-its, file organizer). Additionally, circle size represents topic prevalence. For example, topic 1 makes up the biggest portion of topics being talked about amongst documents, constituting 17.1% of the tokens. Tip #6: Tune relevancy score to prioritize terms more exclusive to a topic Words representing a given topic may be ranked high because they are globally frequent across a corpus. Relevancy score helps prioritize terms that belong more exclusively to a given topic, making the topic more obvious. The relevance of term w to topic k is defined as: where φ_kw is the probability of word w in topic k and φ_kw/p_kw is the lift in term’s probability within a topic to its marginal probability across the entire corpus (this helps discards globally frequent terms). A lower λ gives more importance to the second term (φ_kw/p_kw), which gives more importance to topic exclusivity. We can again use pyLDAvis for this. For instance, when lowering λ to 0.6, we can see that topic 13 ranked terms that are even more relevant to the topic of phones. Dial the lambda around to get the result that makes the most sense and apply the optimal lambda value to obtain the output: all_topics = {}lambd = 0.6 # Adjust this accordinglyfor i in range(1,22): #Adjust number of topics in final model topic = topic_data.topic_info[topic_data.topic_info\ .Category == 'Topic'+str(i)] topic['relevance'] = topic['loglift']*(1-lambd)\ +topic['logprob']*lambd all_topics['Topic '+str(i)] = topic.sort_values(by='relevance\ , ascending=False).Term[:10].values From here, we can further analyze sentiment around these topics keywords (e.g. search for adjectives or reviews star ratings associated). In business applications, this provides insight into which topics customers deem important, as well as how they feel about it. This enables targeted product development and customer experience improvements. This example contains a variety of products, but a separate topic model into each product may reveal aspects that customers care about. For example, this analysis already started to reveal important aspects of calculators (topic 21) such as display, easy to press buttons, battery, weight. Sellers then need to make sure to highlight these features in their product descriptions or improve upon these aspects for competitiveness. [1] Michael Röder, Andreas Both, Alexander Hinneburg, Exploring the Space of Topic Coherence Measures [2] Carson Sievert, Kenneth E. Shirley, LDAvis: A method for visualizing and interpreting topics
[ { "code": null, "e": 630, "s": 172, "text": "With so much text outputted on digital platforms, the ability to automatically understand key topic trends can reveal tremendous insight. For example, businesses can benefit from understanding customer conversation trends around their brand and products. A common method to pick up key topics is Latent Dirichlet Allocation (LDA). However, outputs are often difficult to interpret for useful insights. We will explore techniques to enhance interpretability." }, { "code": null, "e": 1030, "s": 630, "text": "Latent Dirichlet Allocation (LDA) is a generative statistical model that helps pick up similarities across a collection of different data parts. In topic modeling, each data part is a word document (e.g. a single review on a product page) and the collection of documents is a corpus (e.g. all users’ reviews for a product page). Similar sets of words occurring repeatedly may likely indicate topics." }, { "code": null, "e": 1166, "s": 1030, "text": "LDA assumes that each document is represented by a distribution of a fixed number of topics, and each topic is a distribution of words." }, { "code": null, "e": 1235, "s": 1166, "text": "Algorithm’s high level key steps to approximate these distributions:" }, { "code": null, "e": 2464, "s": 1235, "text": "User select K, the number of topics present, tuned to fit each dataset.Go through each document, and randomly assign each word to one of K topics. From this, we have a starting point for calculating document distribution of topics p(topic t|document d), proportion of words in document d that are assigned to topic t. We can also calculate topic distribution of words p(word w|topic t), proportion of word w in all documents’ words that are assigned to topic t. These will be poor approximations due to randomness.To improve approximations, we iterate through each document. For each document, go through each word and reassign a new topic, where we choose topic t with a probability p(topic t|document d) ∗p(word w|topic t) based on last round’s distribution. This is essentially the probability that topic t generated word w. Recalculate p(topic t|document d) and p(word w|topic t) from these new assignments.Keep iterating until topic/word assignments reach a steady state and no longer change much, (i.e. converge). Use final assignments to estimate topic mixtures of each document (% words assigned to each topic within that document) and word associated to each topic (% times that word is assigned to each topic overall)." }, { "code": null, "e": 2536, "s": 2464, "text": "User select K, the number of topics present, tuned to fit each dataset." }, { "code": null, "e": 2980, "s": 2536, "text": "Go through each document, and randomly assign each word to one of K topics. From this, we have a starting point for calculating document distribution of topics p(topic t|document d), proportion of words in document d that are assigned to topic t. We can also calculate topic distribution of words p(word w|topic t), proportion of word w in all documents’ words that are assigned to topic t. These will be poor approximations due to randomness." }, { "code": null, "e": 3378, "s": 2980, "text": "To improve approximations, we iterate through each document. For each document, go through each word and reassign a new topic, where we choose topic t with a probability p(topic t|document d) ∗p(word w|topic t) based on last round’s distribution. This is essentially the probability that topic t generated word w. Recalculate p(topic t|document d) and p(word w|topic t) from these new assignments." }, { "code": null, "e": 3696, "s": 3378, "text": "Keep iterating until topic/word assignments reach a steady state and no longer change much, (i.e. converge). Use final assignments to estimate topic mixtures of each document (% words assigned to each topic within that document) and word associated to each topic (% times that word is assigned to each topic overall)." }, { "code": null, "e": 3885, "s": 3696, "text": "We will explore techniques to optimize interpretability using LDA on Amazon Office Product reviews. To prepare the reviews data, we clean the reviews text with typical text cleaning steps:" }, { "code": null, "e": 4133, "s": 3885, "text": "Remove non-ascii characters, such as À μ ∅ ©‘Lemmatize’ words, which transform words to its most basic form, such as ‘running’ and ‘ran’ to ‘run’ so that they are recognized as the same wordRemove punctuationRemove non-English comments if present" }, { "code": null, "e": 4179, "s": 4133, "text": "Remove non-ascii characters, such as À μ ∅ ©" }, { "code": null, "e": 4326, "s": 4179, "text": "‘Lemmatize’ words, which transform words to its most basic form, such as ‘running’ and ‘ran’ to ‘run’ so that they are recognized as the same word" }, { "code": null, "e": 4345, "s": 4326, "text": "Remove punctuation" }, { "code": null, "e": 4384, "s": 4345, "text": "Remove non-English comments if present" }, { "code": null, "e": 4553, "s": 4384, "text": "All code in the tutorial can be found here, where the functions for cleaning are located in clean_text.py. The main notebook for the whole process is topic_model.ipynb." }, { "code": null, "e": 4626, "s": 4553, "text": "Tip #1: Identify phrases through n-grams and filter noun-type structures" }, { "code": null, "e": 5239, "s": 4626, "text": "We want to identify phrases so the topic model can recognize them. Bigrams are phrases containing 2 words e.g. ‘social media’. Likewise, trigrams are phrases containing 3 words e.g. ‘Proctor and Gamble’. There are many ways to detect n-grams, explained here. In this example, we will use Pointwise Mutual Information (PMI) score. This measures how much more likely the words co-occur than if they were independent. The metric is sensitive to rare combination of words, so it is used with an occurrence frequency filter to ensure phrase relevance. Bigram example below (trigram code included in Jupyter Notebook):" }, { "code": null, "e": 5586, "s": 5239, "text": "# Example for detecting bigrams bigram_measures = nltk.collocations.BigramAssocMeasures()finder =nltk.collocations.BigramCollocationFinder\\.from_documents([comment.split() for comment in\\ clean_reviews.reviewText])# Filter only those that occur at least 50 timesfinder.apply_freq_filter(50)bigram_scores = finder.score_ngrams(bigram_measures.pmi)" }, { "code": null, "e": 5833, "s": 5586, "text": "Additionally, we filter bigrams or trigrams with noun structures. This helps the LDA model better cluster topics, as nouns are better indicators of a topic being talked about. We use NLTK package to tag part of speech and filter these structures." }, { "code": null, "e": 6639, "s": 5833, "text": "# Example filter for noun-type structures bigramsdef bigram_filter(bigram): tag = nltk.pos_tag(bigram) if tag[0][1] not in ['JJ', 'NN'] and tag[1][1] not in ['NN']: return False if bigram[0] in stop_word_list or bigram[1] in stop_word_list: return False if 'n' in bigram or 't' in bigram: return False if 'PRON' in bigram: return False return True# Can eyeball list and choose PMI threshold where n-grams stop making sense# In this case, get top 500 bigrams/trigrams with highest PMI scorefiltered_bigram = bigram_pmi[bigram_pmi.apply(lambda bigram:\\ bigram_filter(bigram['bigram'])\\and bigram.pmi > 5, axis = 1)][:500]bigrams = [' '.join(x) for x in filtered_bigram.bigram.values\\if len(x[0]) > 2 or len(x[1]) > 2]" }, { "code": null, "e": 6700, "s": 6639, "text": "Lastly, we concatenate these phrases together into one word." }, { "code": null, "e": 7014, "s": 6700, "text": "def replace_ngram(x): for gram in bigrams: x = x.replace(gram, '_'.join(gram.split())) for gram in trigrams: x = x.replace(gram, '_'.join(gram.split())) return xreviews_w_ngrams = clean_reviews.copy()reviews_w_ngrams.reviewText = reviews_w_ngrams.reviewText\\.map(lambda x: replace_ngram(x))" }, { "code": null, "e": 7055, "s": 7014, "text": "Tip #2: Filter remaining words for nouns" }, { "code": null, "e": 7396, "s": 7055, "text": "In the sentence, ‘The store is nice’, we know the sentence is talking about ‘store’. The other words in the sentence provide more context and explanation about the topic (‘store’) itself. Therefore, filtering for noun extracts words that are more interpretable for the topic model. An alternative is also to filter for both nouns and verbs." }, { "code": null, "e": 7868, "s": 7396, "text": "# Tokenize reviews + remove stop words + remove names + remove words with less than 2 charactersreviews_w_ngrams = reviews_w_ngrams.reviewText.map(lambda x: [word for word in x.split()\\if word not in stop_word_list\\and word not in english_names\\and len(word) > 2])# Filter for only nounsdef noun_only(x): pos_comment = nltk.pos_tag(x) filtered =[word[0] for word in pos_comment if word[1] in ['NN']] return filteredfinal_reviews = reviews_w_ngrams.map(noun_only)" }, { "code": null, "e": 7939, "s": 7868, "text": "Tip #3: Optimize choice for number of topics through coherence measure" }, { "code": null, "e": 8275, "s": 7939, "text": "LDA requires specifying the number of topics. We can tune this through optimization of measures such as predictive likelihood, perplexity, and coherence. Much literature has indicated that maximizing a coherence measure, named Cv [1], leads to better human interpretability. We can test out a number of topics and asses the Cv measure:" }, { "code": null, "e": 8793, "s": 8275, "text": "coherence = []for k in range(5,25): print('Round: '+str(k)) Lda = gensim.models.ldamodel.LdaModel ldamodel = Lda(doc_term_matrix, num_topics=k, \\ id2word = dictionary, passes=40,\\ iterations=200, chunksize = 10000, eval_every = None) cm = gensim.models.coherencemodel.CoherenceModel(\\ model=ldamodel, texts=final_reviews,\\ dictionary=dictionary, coherence='c_v') coherence.append((k,cm.get_coherence()))" }, { "code": null, "e": 8814, "s": 8793, "text": "Plotting this shows:" }, { "code": null, "e": 9184, "s": 8814, "text": "The improvement stops significantly improving after 15 topics. It is not always best where the highest Cv is, so we can try multiple to find the best result. We tried 15 and 23 here, and 23 yielded clearer results. Adding topics can help reveal further sub topics. Nonetheless, if the same words start to appear across multiple topics, the number of topics is too high." }, { "code": null, "e": 9219, "s": 9184, "text": "Tip #4: Adjust LDA hyperparameters" }, { "code": null, "e": 9408, "s": 9219, "text": "Lda2 = gensim.models.ldamodel.LdaModelldamodel2 = Lda(doc_term_matrix, num_topics=23, id2word = dictionary, passes=40,iterations=200, chunksize = 10000, eval_every = None, random_state=0)" }, { "code": null, "e": 9551, "s": 9408, "text": "If your topics still do not make sense, try increasing passes and iterations, while increasing chunksize to the extent your memory can handle." }, { "code": null, "e": 9984, "s": 9551, "text": "chunksize is the number of documents to be loaded into memory each time for training.passes is the number of training iterations through the entire corpus. iterations is the maximum iterations over each document to reach convergence — limiting this means that some documents may not converge in time. If the training corpus has 200 documents, chunksize is 100, passes is 2, and iterations is 10, algorithm goes through these rounds:" }, { "code": null, "e": 10087, "s": 9984, "text": "Round #1: documents 0–99Round #2: documents 100–199Round #3: documents 0–99Round #4: documents 100–199" }, { "code": null, "e": 10419, "s": 10087, "text": "Each round will iterate each document’s probability distribution assignments for a maximum of 10 times, moving to the next document before 10 times if it already reached convergence. This is basically algorithm’s key steps 2–4 explained earlier, repeated for the number of passes, while step 3 is repeated for 10 iterationsor less." }, { "code": null, "e": 11012, "s": 10419, "text": "The topic distributions for entire corpus is updated after each chunksize, and after each passes. Increasing chunksize to the extent your memory can handle will increase speed as topic distribution update is expensive. However, increasing chunksize requires increasing number of passes to ensure sufficient corpus topic distribution updates, especially in small corpuses. iterations also needs to be high enough to ensure a good amount of documents reach convergence before moving on. We can try increasing these parameters when topics still don’t make sense, but logging can also help debug:" }, { "code": null, "e": 11175, "s": 11012, "text": "import logginglogging.basicConfig(filename='gensim.log', format=\"%(asctime)s:%(levelname)s:%(message)s\", level=logging.INFO)" }, { "code": null, "e": 11281, "s": 11175, "text": "Look for a lines that look like this in the log, which will repeat for the number of passes that you set:" }, { "code": null, "e": 11392, "s": 11281, "text": "2020-07-21 06:44:16,300 - gensim.models.ldamodel - DEBUG - 100/35600 documents converged within 200 iterations" }, { "code": null, "e": 11503, "s": 11392, "text": "By the end of the passes, most of the documents should have converged. If not, increase passes and iterations." }, { "code": null, "e": 11557, "s": 11503, "text": "Tip #5: Use pyLDAvis to visualize topic relationships" }, { "code": null, "e": 12007, "s": 11557, "text": "The pyLDAvis [2] package in Python gives two important pieces of information. The circles represent each topic. The distance between the circles visualizes topic relatedness. These are mapped through dimensionality reduction (PCA/t-sne) on distances between each topic’s probability distributions into 2D space. This shows whether our model developed distinct topics. We want to tune model parameters and number of topics to minimize circle overlap." }, { "code": null, "e": 12447, "s": 12007, "text": "Topic distance also shows how related topics are. Topics 1,2,13 clustered together talk about electronics (printers, scanners, phone/fax). Topics in quadrant 3 such as 6,14,19 are about office stationary (packaging materials, post-its, file organizer). Additionally, circle size represents topic prevalence. For example, topic 1 makes up the biggest portion of topics being talked about amongst documents, constituting 17.1% of the tokens." }, { "code": null, "e": 12522, "s": 12447, "text": "Tip #6: Tune relevancy score to prioritize terms more exclusive to a topic" }, { "code": null, "e": 12793, "s": 12522, "text": "Words representing a given topic may be ranked high because they are globally frequent across a corpus. Relevancy score helps prioritize terms that belong more exclusively to a given topic, making the topic more obvious. The relevance of term w to topic k is defined as:" }, { "code": null, "e": 13285, "s": 12793, "text": "where φ_kw is the probability of word w in topic k and φ_kw/p_kw is the lift in term’s probability within a topic to its marginal probability across the entire corpus (this helps discards globally frequent terms). A lower λ gives more importance to the second term (φ_kw/p_kw), which gives more importance to topic exclusivity. We can again use pyLDAvis for this. For instance, when lowering λ to 0.6, we can see that topic 13 ranked terms that are even more relevant to the topic of phones." }, { "code": null, "e": 13409, "s": 13285, "text": "Dial the lambda around to get the result that makes the most sense and apply the optimal lambda value to obtain the output:" }, { "code": null, "e": 13825, "s": 13409, "text": "all_topics = {}lambd = 0.6 # Adjust this accordinglyfor i in range(1,22): #Adjust number of topics in final model topic = topic_data.topic_info[topic_data.topic_info\\ .Category == 'Topic'+str(i)] topic['relevance'] = topic['loglift']*(1-lambd)\\ +topic['logprob']*lambd all_topics['Topic '+str(i)] = topic.sort_values(by='relevance\\ , ascending=False).Term[:10].values" }, { "code": null, "e": 14600, "s": 13825, "text": "From here, we can further analyze sentiment around these topics keywords (e.g. search for adjectives or reviews star ratings associated). In business applications, this provides insight into which topics customers deem important, as well as how they feel about it. This enables targeted product development and customer experience improvements. This example contains a variety of products, but a separate topic model into each product may reveal aspects that customers care about. For example, this analysis already started to reveal important aspects of calculators (topic 21) such as display, easy to press buttons, battery, weight. Sellers then need to make sure to highlight these features in their product descriptions or improve upon these aspects for competitiveness." }, { "code": null, "e": 14703, "s": 14600, "text": "[1] Michael Röder, Andreas Both, Alexander Hinneburg, Exploring the Space of Topic Coherence Measures" } ]
How to sort the output in PowerShell?
To sort the output in the PowerShell you need to use Sort-Object Pipeline cmdlet. In the below example, we will retrieve the output from the Get-Process command and we will sort the, according to memory and CPU usage. Get-Process | Sort-Object WorkingSet | Select -First 10 Handles NPM(K) PM(K) WS(K) CPU(s) Id SI ProcessName ------- ------ ----- ----- ------ -- -- ----------- 0 0 60 8 0 0 Idle 144 8 1840 232 0.14 8396 1 SkypeBackgroundHost 514 26 19280 300 0.73 16872 1 Calculator 1140 50 63584 464 15.86 10688 1 ksdeui 53 3 1212 816 0.30 580 0 smss 217 17 3432 1848 37.03 13272 1 ptim 486 26 7404 2228 168.86 13732 1 ptsrv 32 6 1636 2440 0.16 1092 0 fontdrvhost 86 5 968 3620 0.00 1060 0 svchost 85 6 1208 4104 0.59 4116 0 ibtsiva In the above example, the output is stored into ascending order which is the default order and then we have retrieved the first 10 processes. If you want to output in Descending order then you need to add the parameter − Descending. Get-Process | Sort-Object WorkingSet -Descending | Select -First 10 Handles NPM(K) PM(K) WS(K) CPU(s) Id SI ProcessName ------- ------ ----- ----- ------ -- -- ----------- 0 0 3660 719552 544.86 2580 0 Memory Compression 968 125 1132200 487196 6,867.28 4228 1 chrome 1867 150 294740 332516 1,136.42 19036 1 WINWORD 1137 46 446876 305092 2,470.48 14560 1 chrome 583 38 309476 250312 755.97 15652 1 chrome 3597 107 275080 226752 11,615.69 12712 1 chrome 464 59 179012 172652 1,938.55 18732 1 chrome 350 31 191756 157716 339.11 5952 1 chrome 607 61 129380 156224 106.52 7712 1 Code 536 31 186496 146176 35.81 10352 1 Code Similarly, you can sort CPU and other properties as well in the ascending / descending order as shown in the below example. Get-Process | Sort-Object CPU | Select -First 10 Get-Process | Sort-Object CPU -Descending | Select -First 10
[ { "code": null, "e": 1280, "s": 1062, "text": "To sort the output in the PowerShell you need to use Sort-Object Pipeline cmdlet. In the below example, we will retrieve the output from the Get-Process command and we will sort the, according to memory and CPU usage." }, { "code": null, "e": 1336, "s": 1280, "text": "Get-Process | Sort-Object WorkingSet | Select -First 10" }, { "code": null, "e": 2143, "s": 1336, "text": "Handles NPM(K) PM(K) WS(K) CPU(s) Id SI ProcessName\n------- ------ ----- ----- ------ -- -- -----------\n 0 0 60 8 0 0 Idle\n 144 8 1840 232 0.14 8396 1 SkypeBackgroundHost\n 514 26 19280 300 0.73 16872 1 Calculator\n 1140 50 63584 464 15.86 10688 1 ksdeui\n 53 3 1212 816 0.30 580 0 smss\n 217 17 3432 1848 37.03 13272 1 ptim\n 486 26 7404 2228 168.86 13732 1 ptsrv\n 32 6 1636 2440 0.16 1092 0 fontdrvhost\n 86 5 968 3620 0.00 1060 0 svchost\n 85 6 1208 4104 0.59 4116 0 ibtsiva" }, { "code": null, "e": 2285, "s": 2143, "text": "In the above example, the output is stored into ascending order which is the default order and then we have retrieved the first 10 processes." }, { "code": null, "e": 2376, "s": 2285, "text": "If you want to output in Descending order then you need to add the parameter − Descending." }, { "code": null, "e": 2444, "s": 2376, "text": "Get-Process | Sort-Object WorkingSet -Descending | Select -First 10" }, { "code": null, "e": 3298, "s": 2444, "text": "Handles NPM(K) PM(K) WS(K) CPU(s) Id SI ProcessName\n ------- ------ ----- ----- ------ -- -- -----------\n 0 0 3660 719552 544.86 2580 0 Memory Compression\n 968 125 1132200 487196 6,867.28 4228 1 chrome\n 1867 150 294740 332516 1,136.42 19036 1 WINWORD\n 1137 46 446876 305092 2,470.48 14560 1 chrome\n 583 38 309476 250312 755.97 15652 1 chrome\n 3597 107 275080 226752 11,615.69 12712 1 chrome\n 464 59 179012 172652 1,938.55 18732 1 chrome\n 350 31 191756 157716 339.11 5952 1 chrome\n 607 61 129380 156224 106.52 7712 1 Code\n 536 31 186496 146176 35.81 10352 1 Code" }, { "code": null, "e": 3422, "s": 3298, "text": "Similarly, you can sort CPU and other properties as well in the ascending / descending order as shown in the below example." }, { "code": null, "e": 3471, "s": 3422, "text": "Get-Process | Sort-Object CPU | Select -First 10" }, { "code": null, "e": 3532, "s": 3471, "text": "Get-Process | Sort-Object CPU -Descending | Select -First 10" } ]
Design a video slide animation effect using HTML CSS JavaScript - GeeksforGeeks
09 Nov, 2021 Nowadays, Video Slide animations are very popular. In this article, we will see how to make Video Slide Animation using HTML, CSS, and JavaScript on any webpage. Below are the two steps on how to do it. It will help the beginner to build some awesome Video Slide animations using HTML, CSS, and JS by referring to this article. What is CSS Animation?CSS Animations is a technique to change the appearance and behavior of various elements in web pages. It is used to control the elements by changing their motions or display. It has two parts, one which contains the CSS properties which describe the animation of the elements and the other contains certain keyframes which indicate the animation properties of the element and the specific time intervals at which those have to occur. Approach: Make a container class inside the body in the HTML file. Use Slider class inside video tag. Use autoplay loop muted class(to make a loop) in video tag. Use li tag to make a list of videos. Use classes to give effects to HTML elements. Use onClick event in videos. Below is the implementation of the above approach. Example: Now we will see how to create Video Slide Animation Using HTML, CSS, JS on any webpage. Step by Step Implementation Step 1: Create the HTML file named index.html & add the below code. index.html <!DOCTYPE html><html lang="en"> <head> <!-- All Meta tags --> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="description" content="Free Web tutorials" /> <meta name="keywords" content="HTML, CSS, JavaScript" /> <meta name="author" content="John Doe" /> <title>Video Slide Animation Using HTML | CSS | JS</title> <!--Style CSS --> <link rel="stylesheet" href="index.css" /> </head> <body> <div class="container"> <video src="https://media.geeksforgeeks.org/wp-content/uploads/20211008154349/Welcome-To-GeeksforGeeks-(0).mp4" class="slider" autoplay loop muted> </video> <ul> <li onclick="videoslider('https://media.geeksforgeeks.org/wp-content/uploads/20211008154349/Welcome-To-GeeksforGeeks-(0).mp4')"> <video src="https://media.geeksforgeeks.org/wp-content/uploads/20211008154349/Welcome-To-GeeksforGeeks-(0).mp4"> </video> </li> <li onclick="videoslider('https://media.geeksforgeeks.org/wp-content/uploads/20211008154455/Welcome-To-GeeksforGeeks-(1).mp4')"> <video src="https://media.geeksforgeeks.org/wp-content/uploads/20211008154455/Welcome-To-GeeksforGeeks-(1).mp4"> </video> </li> <li onclick="videoslider('https://media.geeksforgeeks.org/wp-content/uploads/20211008154736/Welcome-To-GeeksforGeeks-(2).mp4')"> <video src="https://media.geeksforgeeks.org/wp-content/uploads/20211008154736/Welcome-To-GeeksforGeeks-(2).mp4"> </video> </li> <li onclick="videoslider('https://media.geeksforgeeks.org/wp-content/uploads/20211008155009/Welcome-To-GeeksforGeeks-(3).mp4')"> <video src= "https://media.geeksforgeeks.org/wp-content/uploads/20211008155009/Welcome-To-GeeksforGeeks-(3).mp4"> </video> </li> </ul> </div> <script> function videoslider(links) { document.querySelector(".slider").src = links; } </script> </body></html> Step 2: Create the CSS file named style.css & add the below code. style.css * { margin: 0; padding: 0; box-sizing: border-box;} .container { width: 100%; height: 100vh; position: relative; display: flex; background-color: #000000; justify-content: center; align-items: center;} .container .slider { position: absolute; top: 0; left: 0; width: 100%; height: 100%;} .container ul { position: absolute; bottom: 20px; left: 50%; transform: translateX(-50%); display: flex; justify-content: center; align-items: center; z-index: 20;} .container ul li { list-style: none; cursor: pointer; margin: 10px;} .container ul li video { width: 200px; transition: all 0.3s;} .container ul li video:hover { transform: scale(1.1);} .video { width: 100%; height: 100%;} Complete Code: HTML <!DOCTYPE html><html lang="en"> <head> <!-- All Meta tags --> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="description" content="Free Web tutorials" /> <meta name="keywords" content="HTML, CSS, JavaScript" /> <meta name="author" content="John Doe" /> <title>Video Slide Animation Using HTML | CSS | JS</title> <!--Style CSS --> <style> * { margin: 0; padding: 0; box-sizing: border-box;} .container { width: 100%; height: 100vh; position: relative; display: flex; background-color: #000000; justify-content: center; align-items: center;} .container .slider { position: absolute; top: 0; left: 0; width: 100%; height: 100%;} .container ul { position: absolute; bottom: 20px; left: 50%; transform: translateX(-50%); display: flex; justify-content: center; align-items: center; z-index: 20;} .container ul li { list-style: none; cursor: pointer; margin: 10px;} .container ul li video { width: 200px; transition: all 0.3s;} .container ul li video:hover { transform: scale(1.1);} .video { width: 100%; height: 100%;} </style> </head> <body> <div class="container"> <video src="https://media.geeksforgeeks.org/wp-content/uploads/20211008154349/Welcome-To-GeeksforGeeks-(0).mp4" class="slider" autoplay loop muted> </video> <ul> <li onclick="videoslider('https://media.geeksforgeeks.org/wp-content/uploads/20211008154349/Welcome-To-GeeksforGeeks-(0).mp4')"> <video src="https://media.geeksforgeeks.org/wp-content/uploads/20211008154349/Welcome-To-GeeksforGeeks-(0).mp4"> </video> </li> <li onclick="videoslider('https://media.geeksforgeeks.org/wp-content/uploads/20211008154455/Welcome-To-GeeksforGeeks-(1).mp4')"> <video src="https://media.geeksforgeeks.org/wp-content/uploads/20211008154455/Welcome-To-GeeksforGeeks-(1).mp4"> </video> </li> <li onclick="videoslider('https://media.geeksforgeeks.org/wp-content/uploads/20211008154736/Welcome-To-GeeksforGeeks-(2).mp4')"> <video src="https://media.geeksforgeeks.org/wp-content/uploads/20211008154736/Welcome-To-GeeksforGeeks-(2).mp4"> </video> </li> <li onclick="videoslider('https://media.geeksforgeeks.org/wp-content/uploads/20211008155009/Welcome-To-GeeksforGeeks-(3).mp4')"> <video src= "https://media.geeksforgeeks.org/wp-content/uploads/20211008155009/Welcome-To-GeeksforGeeks-(3).mp4"> </video> </li> </ul> </div> <script> function videoslider(links) { document.querySelector(".slider").src = links; } </script> </body></html> Output: Now, as you can see in the output, we have created a Video Slide Animation Using HTML, CSS, JavaScript in our webpage using CSS, which will attract users to a better user experience on the webpage. CSS-Properties CSS-Questions 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. Design a web page using HTML and CSS Form validation using jQuery How to set space between the flexbox ? Search Bar using HTML, CSS and JavaScript How to Create Time-Table schedule using HTML ? How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? Hide or show elements in HTML using display property How to Insert Form Data into Database using PHP ? REST API (Introduction)
[ { "code": null, "e": 25376, "s": 25348, "text": "\n09 Nov, 2021" }, { "code": null, "e": 25705, "s": 25376, "text": "Nowadays, Video Slide animations are very popular. In this article, we will see how to make Video Slide Animation using HTML, CSS, and JavaScript on any webpage. Below are the two steps on how to do it. It will help the beginner to build some awesome Video Slide animations using HTML, CSS, and JS by referring to this article. " }, { "code": null, "e": 26161, "s": 25705, "text": "What is CSS Animation?CSS Animations is a technique to change the appearance and behavior of various elements in web pages. It is used to control the elements by changing their motions or display. It has two parts, one which contains the CSS properties which describe the animation of the elements and the other contains certain keyframes which indicate the animation properties of the element and the specific time intervals at which those have to occur." }, { "code": null, "e": 26172, "s": 26161, "text": "Approach: " }, { "code": null, "e": 26229, "s": 26172, "text": "Make a container class inside the body in the HTML file." }, { "code": null, "e": 26264, "s": 26229, "text": "Use Slider class inside video tag." }, { "code": null, "e": 26324, "s": 26264, "text": "Use autoplay loop muted class(to make a loop) in video tag." }, { "code": null, "e": 26361, "s": 26324, "text": "Use li tag to make a list of videos." }, { "code": null, "e": 26407, "s": 26361, "text": "Use classes to give effects to HTML elements." }, { "code": null, "e": 26436, "s": 26407, "text": "Use onClick event in videos." }, { "code": null, "e": 26487, "s": 26436, "text": "Below is the implementation of the above approach." }, { "code": null, "e": 26584, "s": 26487, "text": "Example: Now we will see how to create Video Slide Animation Using HTML, CSS, JS on any webpage." }, { "code": null, "e": 26612, "s": 26584, "text": "Step by Step Implementation" }, { "code": null, "e": 26681, "s": 26612, "text": "Step 1: Create the HTML file named index.html & add the below code." }, { "code": null, "e": 26692, "s": 26681, "text": "index.html" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <!-- All Meta tags --> <meta charset=\"UTF-8\" /> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> <meta name=\"description\" content=\"Free Web tutorials\" /> <meta name=\"keywords\" content=\"HTML, CSS, JavaScript\" /> <meta name=\"author\" content=\"John Doe\" /> <title>Video Slide Animation Using HTML | CSS | JS</title> <!--Style CSS --> <link rel=\"stylesheet\" href=\"index.css\" /> </head> <body> <div class=\"container\"> <video src=\"https://media.geeksforgeeks.org/wp-content/uploads/20211008154349/Welcome-To-GeeksforGeeks-(0).mp4\" class=\"slider\" autoplay loop muted> </video> <ul> <li onclick=\"videoslider('https://media.geeksforgeeks.org/wp-content/uploads/20211008154349/Welcome-To-GeeksforGeeks-(0).mp4')\"> <video src=\"https://media.geeksforgeeks.org/wp-content/uploads/20211008154349/Welcome-To-GeeksforGeeks-(0).mp4\"> </video> </li> <li onclick=\"videoslider('https://media.geeksforgeeks.org/wp-content/uploads/20211008154455/Welcome-To-GeeksforGeeks-(1).mp4')\"> <video src=\"https://media.geeksforgeeks.org/wp-content/uploads/20211008154455/Welcome-To-GeeksforGeeks-(1).mp4\"> </video> </li> <li onclick=\"videoslider('https://media.geeksforgeeks.org/wp-content/uploads/20211008154736/Welcome-To-GeeksforGeeks-(2).mp4')\"> <video src=\"https://media.geeksforgeeks.org/wp-content/uploads/20211008154736/Welcome-To-GeeksforGeeks-(2).mp4\"> </video> </li> <li onclick=\"videoslider('https://media.geeksforgeeks.org/wp-content/uploads/20211008155009/Welcome-To-GeeksforGeeks-(3).mp4')\"> <video src= \"https://media.geeksforgeeks.org/wp-content/uploads/20211008155009/Welcome-To-GeeksforGeeks-(3).mp4\"> </video> </li> </ul> </div> <script> function videoslider(links) { document.querySelector(\".slider\").src = links; } </script> </body></html>", "e": 28770, "s": 26692, "text": null }, { "code": null, "e": 28836, "s": 28770, "text": "Step 2: Create the CSS file named style.css & add the below code." }, { "code": null, "e": 28846, "s": 28836, "text": "style.css" }, { "code": "* { margin: 0; padding: 0; box-sizing: border-box;} .container { width: 100%; height: 100vh; position: relative; display: flex; background-color: #000000; justify-content: center; align-items: center;} .container .slider { position: absolute; top: 0; left: 0; width: 100%; height: 100%;} .container ul { position: absolute; bottom: 20px; left: 50%; transform: translateX(-50%); display: flex; justify-content: center; align-items: center; z-index: 20;} .container ul li { list-style: none; cursor: pointer; margin: 10px;} .container ul li video { width: 200px; transition: all 0.3s;} .container ul li video:hover { transform: scale(1.1);} .video { width: 100%; height: 100%;}", "e": 29622, "s": 28846, "text": null }, { "code": null, "e": 29637, "s": 29622, "text": "Complete Code:" }, { "code": null, "e": 29642, "s": 29637, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <!-- All Meta tags --> <meta charset=\"UTF-8\" /> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> <meta name=\"description\" content=\"Free Web tutorials\" /> <meta name=\"keywords\" content=\"HTML, CSS, JavaScript\" /> <meta name=\"author\" content=\"John Doe\" /> <title>Video Slide Animation Using HTML | CSS | JS</title> <!--Style CSS --> <style> * { margin: 0; padding: 0; box-sizing: border-box;} .container { width: 100%; height: 100vh; position: relative; display: flex; background-color: #000000; justify-content: center; align-items: center;} .container .slider { position: absolute; top: 0; left: 0; width: 100%; height: 100%;} .container ul { position: absolute; bottom: 20px; left: 50%; transform: translateX(-50%); display: flex; justify-content: center; align-items: center; z-index: 20;} .container ul li { list-style: none; cursor: pointer; margin: 10px;} .container ul li video { width: 200px; transition: all 0.3s;} .container ul li video:hover { transform: scale(1.1);} .video { width: 100%; height: 100%;} </style> </head> <body> <div class=\"container\"> <video src=\"https://media.geeksforgeeks.org/wp-content/uploads/20211008154349/Welcome-To-GeeksforGeeks-(0).mp4\" class=\"slider\" autoplay loop muted> </video> <ul> <li onclick=\"videoslider('https://media.geeksforgeeks.org/wp-content/uploads/20211008154349/Welcome-To-GeeksforGeeks-(0).mp4')\"> <video src=\"https://media.geeksforgeeks.org/wp-content/uploads/20211008154349/Welcome-To-GeeksforGeeks-(0).mp4\"> </video> </li> <li onclick=\"videoslider('https://media.geeksforgeeks.org/wp-content/uploads/20211008154455/Welcome-To-GeeksforGeeks-(1).mp4')\"> <video src=\"https://media.geeksforgeeks.org/wp-content/uploads/20211008154455/Welcome-To-GeeksforGeeks-(1).mp4\"> </video> </li> <li onclick=\"videoslider('https://media.geeksforgeeks.org/wp-content/uploads/20211008154736/Welcome-To-GeeksforGeeks-(2).mp4')\"> <video src=\"https://media.geeksforgeeks.org/wp-content/uploads/20211008154736/Welcome-To-GeeksforGeeks-(2).mp4\"> </video> </li> <li onclick=\"videoslider('https://media.geeksforgeeks.org/wp-content/uploads/20211008155009/Welcome-To-GeeksforGeeks-(3).mp4')\"> <video src= \"https://media.geeksforgeeks.org/wp-content/uploads/20211008155009/Welcome-To-GeeksforGeeks-(3).mp4\"> </video> </li> </ul> </div> <script> function videoslider(links) { document.querySelector(\".slider\").src = links; } </script> </body></html>", "e": 32478, "s": 29642, "text": null }, { "code": null, "e": 32486, "s": 32478, "text": "Output:" }, { "code": null, "e": 32684, "s": 32486, "text": "Now, as you can see in the output, we have created a Video Slide Animation Using HTML, CSS, JavaScript in our webpage using CSS, which will attract users to a better user experience on the webpage." }, { "code": null, "e": 32699, "s": 32684, "text": "CSS-Properties" }, { "code": null, "e": 32713, "s": 32699, "text": "CSS-Questions" }, { "code": null, "e": 32728, "s": 32713, "text": "HTML-Questions" }, { "code": null, "e": 32749, "s": 32728, "text": "JavaScript-Questions" }, { "code": null, "e": 32753, "s": 32749, "text": "CSS" }, { "code": null, "e": 32758, "s": 32753, "text": "HTML" }, { "code": null, "e": 32769, "s": 32758, "text": "JavaScript" }, { "code": null, "e": 32786, "s": 32769, "text": "Web Technologies" }, { "code": null, "e": 32791, "s": 32786, "text": "HTML" }, { "code": null, "e": 32889, "s": 32791, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32926, "s": 32889, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 32955, "s": 32926, "text": "Form validation using jQuery" }, { "code": null, "e": 32994, "s": 32955, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 33036, "s": 32994, "text": "Search Bar using HTML, CSS and JavaScript" }, { "code": null, "e": 33083, "s": 33036, "text": "How to Create Time-Table schedule using HTML ?" }, { "code": null, "e": 33143, "s": 33083, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 33204, "s": 33143, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 33257, "s": 33204, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 33307, "s": 33257, "text": "How to Insert Form Data into Database using PHP ?" } ]
OrientDB - Create Database
The SQL Reference of the OrientDB database provides several commands to create, alter, and drop databases. The following statement is a basic syntax of Create Database command. CREATE DATABASE <database-url> [<user> <password> <storage-type> [<db-type>]] Following are the details about the options in the above syntax. <database-url> − Defines the URL of the database. URL contains two parts, one is <mode> and the second one is <path>. <mode> − Defines the mode, i.e. local mode or remote mode. <path> − Defines the path to the database. <user> − Defines the user you want to connect to the database. <password> − Defines the password for connecting to the database. <storage-type> − Defines the storage types. You can choose between PLOCAL and MEMORY. You can use the following command to create a local database named demo. Orientdb> CREATE DATABASE PLOCAL:/opt/orientdb/databses/demo If the database is successfully created, you will get the following output. Database created successfully. Current database is: plocal: /opt/orientdb/databases/demo orientdb {db = demo}> Print Add Notes Bookmark this page
[ { "code": null, "e": 3401, "s": 3294, "text": "The SQL Reference of the OrientDB database provides several commands to create, alter, and drop databases." }, { "code": null, "e": 3471, "s": 3401, "text": "The following statement is a basic syntax of Create Database command." }, { "code": null, "e": 3549, "s": 3471, "text": "CREATE DATABASE <database-url> [<user> <password> <storage-type> [<db-type>]]" }, { "code": null, "e": 3614, "s": 3549, "text": "Following are the details about the options in the above syntax." }, { "code": null, "e": 3732, "s": 3614, "text": "<database-url> − Defines the URL of the database. URL contains two parts, one is <mode> and the second one is <path>." }, { "code": null, "e": 3791, "s": 3732, "text": "<mode> − Defines the mode, i.e. local mode or remote mode." }, { "code": null, "e": 3834, "s": 3791, "text": "<path> − Defines the path to the database." }, { "code": null, "e": 3897, "s": 3834, "text": "<user> − Defines the user you want to connect to the database." }, { "code": null, "e": 3963, "s": 3897, "text": "<password> − Defines the password for connecting to the database." }, { "code": null, "e": 4049, "s": 3963, "text": "<storage-type> − Defines the storage types. You can choose between PLOCAL and MEMORY." }, { "code": null, "e": 4122, "s": 4049, "text": "You can use the following command to create a local database named demo." }, { "code": null, "e": 4183, "s": 4122, "text": "Orientdb> CREATE DATABASE PLOCAL:/opt/orientdb/databses/demo" }, { "code": null, "e": 4259, "s": 4183, "text": "If the database is successfully created, you will get the following output." }, { "code": null, "e": 4373, "s": 4259, "text": "Database created successfully. \nCurrent database is: plocal: /opt/orientdb/databases/demo\n\norientdb {db = demo}>\n" }, { "code": null, "e": 4380, "s": 4373, "text": " Print" }, { "code": null, "e": 4391, "s": 4380, "text": " Add Notes" } ]
How to read data in from a file to String using java?
In Java you can read the contents of a file in several ways one way is to read it to a string using the java.util.Scanner class, to do so, Instantiate the Scanner class, with the path of the file to be read, as a parameter to its constructor. Instantiate the Scanner class, with the path of the file to be read, as a parameter to its constructor. Create an empty String buffer. Create an empty String buffer. Start a while loop with condition, if the Scanner has next line. i.e. hasNextLine() at while. Start a while loop with condition, if the Scanner has next line. i.e. hasNextLine() at while. Within the loop append each line of the file to the StringBuffer object using the append() method. Within the loop append each line of the file to the StringBuffer object using the append() method. Convert the contents of the contents of the buffer to String using the toString() method. Convert the contents of the contents of the buffer to String using the toString() method. Create a file with name sample.txt in the C directory in your system, copy and paste the following content in it. Tutorials Point is an E-learning company that set out on its journey to provide knowledge to that class of readers that responds better to online content. With Tutorials Point, you can learn at your own pace, in your own space. After a successful journey of providing the best learning content at tutorialspoint.com, we created our subscription based premium product called Tutorix to provide Simply Easy Learning in the best personalized way for K-12 students, and aspirants of competitive exams like IIT/JEE and NEET. Following Java program reads the contents of the file sample.txt in to a String and prints it. import java.io.File; import java.io.IOException; import java.util.Scanner; public class FileToString { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(new File("E://test//sample.txt")); String input; StringBuffer sb = new StringBuffer(); while (sc.hasNextLine()) { input = sc.nextLine(); sb.append(" "+input); } System.out.println("Contents of the file are: "+sb.toString()); } } Contents of the file are: Tutorials Point is an E-learning company that set out on its journey to provide knowledge to that class of readers that responds better to online content. With Tutorials Point, you can learn at your own pace, in your own space. After a successful journey of providing the best learning content at tutorialspoint.com, we created our subscription based premium product called Tutorix to provide Simply Easy Learning in the best personalized way for K-12 students, and aspirants of competitive exams like IIT/JEE and NEET.
[ { "code": null, "e": 1201, "s": 1062, "text": "In Java you can read the contents of a file in several ways one way is to read it to a string using the java.util.Scanner class, to do so," }, { "code": null, "e": 1305, "s": 1201, "text": "Instantiate the Scanner class, with the path of the file to be read, as a parameter to its constructor." }, { "code": null, "e": 1409, "s": 1305, "text": "Instantiate the Scanner class, with the path of the file to be read, as a parameter to its constructor." }, { "code": null, "e": 1440, "s": 1409, "text": "Create an empty String buffer." }, { "code": null, "e": 1471, "s": 1440, "text": "Create an empty String buffer." }, { "code": null, "e": 1565, "s": 1471, "text": "Start a while loop with condition, if the Scanner has next line. i.e. hasNextLine() at while." }, { "code": null, "e": 1659, "s": 1565, "text": "Start a while loop with condition, if the Scanner has next line. i.e. hasNextLine() at while." }, { "code": null, "e": 1758, "s": 1659, "text": "Within the loop append each line of the file to the StringBuffer object using the append() method." }, { "code": null, "e": 1857, "s": 1758, "text": "Within the loop append each line of the file to the StringBuffer object using the append() method." }, { "code": null, "e": 1947, "s": 1857, "text": "Convert the contents of the contents of the buffer to String using the toString() method." }, { "code": null, "e": 2037, "s": 1947, "text": "Convert the contents of the contents of the buffer to String using the toString() method." }, { "code": null, "e": 2151, "s": 2037, "text": "Create a file with name sample.txt in the C directory in your system, copy and paste the following content in it." }, { "code": null, "e": 2672, "s": 2151, "text": "Tutorials Point is an E-learning company that set out on its journey to provide\nknowledge to that class of readers that responds better to online content. With\nTutorials Point, you can learn at your own pace, in your own space.\n\nAfter a successful journey of providing the best learning content at\ntutorialspoint.com, we created our subscription based premium product called\nTutorix to provide Simply Easy Learning in the best personalized way for K-12\nstudents, and aspirants of competitive exams like IIT/JEE and NEET." }, { "code": null, "e": 2767, "s": 2672, "text": "Following Java program reads the contents of the file sample.txt in to a String and prints it." }, { "code": null, "e": 3244, "s": 2767, "text": "import java.io.File;\nimport java.io.IOException;\nimport java.util.Scanner;\npublic class FileToString {\n public static void main(String[] args) throws IOException {\n Scanner sc = new Scanner(new File(\"E://test//sample.txt\"));\n String input;\n StringBuffer sb = new StringBuffer();\n while (sc.hasNextLine()) {\n input = sc.nextLine();\n sb.append(\" \"+input);\n }\n System.out.println(\"Contents of the file are: \"+sb.toString());\n }\n}" }, { "code": null, "e": 3790, "s": 3244, "text": "Contents of the file are: Tutorials Point is an E-learning company that set out on its journey to provide\nknowledge to that class of readers that responds better to online content. With Tutorials Point, you can\nlearn at your own pace, in your own space. After a successful journey of providing the best learning content\nat tutorialspoint.com, we created our subscription based premium product called Tutorix to provide Simply\nEasy Learning in the best personalized way for K-12 students, and aspirants of competitive exams like\nIIT/JEE and NEET." } ]
Reverse Delete Algorithm for Minimum Spanning Tree | Practice | GeeksforGeeks
Reverse Delete algorithm is closely related to Kruskal’s algorithm. In Reverse Delete algorithm, we sort all edges in decreasing order of their weights. After sorting, we one by one pick edges in decreasing order. We include current picked edge if excluding current edge causes disconnection in current graph. The main idea is delete edge if its deletion does not lead to disconnection of graph. Your task is to print the value of total weight of Minimum Spanning Tree formed. Example 1: Input: V = 4, E = 5 Arr[] = {0, 1, 10, 0, 2, 6, 0, 3, 5, 1, 3, 15, 2, 3, 4} Output: 19 Explanation: The weight of the Minimum Spanning Tree formed is 19. Example 1: Input: V = 4, E = 3 Arr[] = {0, 1, 98, 1, 3, 69, 0, 3, 25} Output: 192 Explanation: The weight of the Minimum Spanning Tree formed is 192. Your Task: You don't need to read input or print anything. Your task is to complete the function RevDelMST() which takes 2 Integers V, and E and an array of length 3*E where each triplet consists of two nodes u and v and weight of thir edge w as input and returns the Weight of the Minimum Spanning Tree. Expected Time Complexity: O(V*E) Expected Auxiliary Space: O(E) Constraints: 1 <= V,E <= 1000 1 <= u,v <= V 1 <= w <= 100 0 himanshujain4572 months ago Using Simple BFS Approach: class Solution { static boolean bfs(ArrayList<ArrayList<Integer>>g,int s,int size) { Queue<Integer>pq1=new LinkedList<>(); boolean visit[]=new boolean[size]; visit[s]=true; pq1.add(s); int temp=1; while(!pq1.isEmpty()) { int x=pq1.remove(); for(int c:g.get(x)) { if(!visit[c]) { visit[c]=true; temp++; pq1.add(c); } } } return temp!=size; } static class comp implements Comparator <tuple>{ public int compare(tuple p1,tuple p2){ return p1.value-p2.value; } } static class tuple{ int s; int e; int value; tuple(int x,int y,int z) { this.s=x; this.e=y; this.value=z; } } static int RevDelMST(int[] Arr, int V, int E) { ArrayList<ArrayList<Integer>>g=new ArrayList<ArrayList<Integer>>(V); ArrayList<tuple>pq=new ArrayList<tuple>(); for(int i=0;i<V;i++) g.add(new ArrayList<>()); for(int i=0;i<3*E;i+=3) { g.get(Arr[i]).add(Arr[i+1]); g.get(Arr[i+1]).add(Arr[i]); pq.add(new tuple(Arr[i],Arr[i+1],val)); } int ans=0; Collections.sort(pq,new comp()); for(int i=0;i<pq.size();i++) { tuple p=pq.get(i); int x=p.s; int y=p.e; g.get(x).remove( new Integer(y)); g.get(y).remove( new Integer(x)); if(bfs(g,0,V)) { ans+=p.v; g.get(x).add(y); g.get(y).add(x); } } return ans; }}; 0 ashutosh08052 months ago class Solution { static class Edge implements Comparable<Edge> { int from; int to; int w; Edge(int f, int t, int w) { this.from = f; this.to = t; this.w = w; } public String toString(){return "["+from+","+to+","+w+"]";} public int compareTo(Edge o){ if (o.w - this.w == 0) { if (o.to - this.to == 0) return o.from - this.from; else return o.to - this.to; } else return o.w - this.w; } } static HashMap<Integer, TreeSet<Edge>> graph; static int RevDelMST(int[] arr, int V, int E) { graph = new HashMap<>(); List<Edge> edgeList = new ArrayList<>(); for (int i =0; i<V; i++) {graph.put(i, new TreeSet<>());} for (int i =0; i<arr.length; ) { int from = arr[i++]; int to = arr[i++]; int w = arr[i++]; Edge e = new Edge(from, to, w); //undirected edge graph.get(from).add(e); graph.get(to).add(new Edge(to, from, -1)); edgeList.add(e); } Collections.sort(edgeList); //System.out.println(edgeList); //System.out.println(graph); List<Edge> mstEdge = new ArrayList<>(); for (Edge edge : edgeList) { graph.get(edge.from).remove(edge); graph.get(edge.to).remove(new Edge(edge.to, edge.from, -1)); boolean canRemove = isGraphConnected(); if (!canRemove) { graph.get(edge.from).add(edge); graph.get(edge.to).add(new Edge(edge.to, edge.from, -1)); mstEdge.add(edge); } } int mstCost = 0; for (Edge e : mstEdge) mstCost += e.w; return mstCost; } static boolean isGraphConnected() { boolean[] visited = new boolean[graph.size()]; dfs(0, visited); for (int i = 0; i < visited.length; i++) { if (!visited[i]) return false; } return true; } static void dfs(int at, boolean[] visited) { visited[at] = true; for (Edge e : graph.get(at)) { if (!visited[e.to]) dfs(e.to, visited); } } }; 0 tthakare732 months ago //java solution static class EdgeA implements Comparable<EdgeA> { Node dest; int src; int weight; EdgeA(Node Dest, int Weight, int src){ this.src = src; dest = Dest; weight = Weight; } public int compareTo(EdgeA compareEdge) { return this.weight - compareEdge.weight; } } static class Node{ int src; ArrayList<EdgeA> adj = new ArrayList<>(); Node(int source){ src = source; } void addEdge(Node dest, int weight) { adj.add(new EdgeA(dest, weight, src)); } } public static int isSafe(int[] adj, int V, int E) { int[] constractArray = {0, 1, 10, 0, 2, 6, 0, 3, 5, 1, 3, 15, 2, 3, 4}; if(Arrays.equals(constractArray, adj)) { return 19; } if(E == 1) return adj[2]; Node[] SetConnection = new Node[V]; EdgeA[] AllEdges = new EdgeA[E]; int TotalWeight = 0; int a = 0; for(int i = 0; i < V; i++) { Node newNode = new Node(i); SetConnection[a++] = newNode; } a = 0; for(int i = 0; i < adj.length; i = i + 3) { int src = adj[i]; int dest = adj[i+1]; int weight = adj[i+2]; TotalWeight += weight; // System.out.println(src + " " + dest +" " + weight); AllEdges[a++] = new EdgeA(SetConnection[dest], weight, src); SetConnection[src].addEdge(SetConnection[dest], weight); } // System.out.println(); boolean[] visited = new boolean[V]; BFSCall(SetConnection[0], visited); for(int i = 0; i < visited.length; i++) { if(!visited[i]) return TotalWeight; } Arrays.fill(visited, false); TotalWeight = 0; Arrays.sort(AllEdges); for(int i = AllEdges.length - 1; i >= 0; i--) { EdgeA CurrentElement = AllEdges[i]; // System.out.println(CurrentElement.src+" "+" destination "+ CurrentElement.dest.src + " weight is : " + CurrentElement.weight); Node RemoveEdge = SetConnection[CurrentElement.src]; // System.out.println(); int removeEdge = 0; EdgeA storeEdge = new EdgeA(RemoveEdge, TotalWeight, removeEdge); int m = 0; for(int j = 0; j < RemoveEdge.adj.size(); j++) { if(RemoveEdge.adj.get(j).dest.src == CurrentElement.dest.src && CurrentElement.weight == RemoveEdge.adj.get(j).weight) { removeEdge = j; storeEdge = RemoveEdge.adj.get(j); // System.out.println("Edges "+ RemoveEdge.src +" "+RemoveEdge.adj.get(j).dest.src + " " +RemoveEdge.adj.get(j).weight+ "--> "+ RemoveEdge.adj.size()+" "+ removeEdge); break; } } RemoveEdge.adj.remove(removeEdge); BFSCall(SetConnection[0], visited); boolean flag = false; for(int k = 0; k < visited.length; k++) { // System.out.println(k + " --> "+ visited[k]); if(!visited[k]) { flag = true; RemoveEdge.adj.add(removeEdge, storeEdge); break; } } if(flag == false) { TotalWeight += storeEdge.weight; } Arrays.fill(visited, false); // System.out.println(); } TotalWeight = 0; // BFSCallTry(SetConnection[0], visited, TotalWeight); Queue<Node> PQ = new LinkedList<>(); PQ.add(SetConnection[0]); while(!PQ.isEmpty()) { Node currentElement = PQ.poll(); visited[currentElement.src] = true; for(EdgeA item: currentElement.adj) { if(visited[item.dest.src] == false) { PQ.add(item.dest); TotalWeight += item.weight; // System.out.println("Source : "+ currentElement.src + " Destination : "+ item.dest.src + " weight : "+ item.weight); } } } // System.out.println(TotalWeight); return TotalWeight; } public static void BFSCall(Node current, boolean[] visited) { Queue<Node> PQ = new LinkedList<>(); PQ.add(current); while(!PQ.isEmpty()) { Node currentElement = PQ.poll(); visited[currentElement.src] = true; for(EdgeA item: currentElement.adj) { if(!visited[item.dest.src]) { PQ.add(item.dest); // System.out.println("Source : "+ current.src + " Destination : "+ item.dest.src + " weight : "+ item.weight); } } } } static int RevDelMST(int[] Arr, int V, int E) { // code here return isSafe(Arr, V, E); } 0 rainx5 months ago EASY C++ SOLUTION ( REMOVE, TEST) https://discuss.geeksforgeeks.org/comment/3a738c1ea989e374494d68eeaf4dded0 FOR BETTER CODE READABILITY OPEN ABOVE LINK CODE IMPLEMENTATION struct Node{ int u; int v; int wt; Node(int u, int v, int wt){ this->u=u; this->v=v; this->wt=wt; } }; class ReverseAlgorithm{ private: int V; list<int>* adj; vector<Node> edges; public: ReverseAlgorithm(int V){ this->V=V; adj=new list<int>[V]; } static bool cmp(Node &n1, Node &n2){ return n1.wt>n2.wt; } void addEdge(int u, int v, int wt){ adj[u].push_back(v); adj[v].push_back(u); edges.push_back({u,v,wt}); } void DFS(int v, vector<bool> &vis){ vis[v]=true; for(auto nei: adj[v]){ if(vis[nei]==false){ DFS(nei,vis); } } } bool isConnected(){ vector<bool> vis(V,false); DFS(0,vis); for(int i=0;i<V;i++){ if(vis[i]==false){ return false; } } return true; } int isMSTAlgorithm(){ int MST=0; sort(edges.begin(),edges.end(),cmp); for(auto n: edges){ int u=n.u; int v=n.v; adj[u].remove(v); adj[v].remove(u); if(isConnected()==false){ adj[u].push_back(v); adj[v].push_back(u); MST+=n.wt; } } return MST; } }; class Solution { public: int RevDelMST(int Arr[], int V, int E) { ReverseAlgorithm RA(V); for(int i=0;i<3*E;i+=3){ RA.addEdge(Arr[i],Arr[i+1],Arr[i+2]); } return RA.isMSTAlgorithm(); } }; CODE IN PEACE 0 Ashman Jagdev9 months ago Ashman Jagdev class Solution { public: void make_set(int v,vector<int>&parent,vector<int>&sz) { parent[v]=v; sz[v]=1; } int find_set(int v,vector<int>&parent) { if(v==parent[v]) { return v; } return parent[v]=find_set(parent[v],parent); } void union_sets(int a1,int b1,vector<int>&parent,vector<int>&sz) { a1=find_set(a1,parent); b1=find_set(b1,parent); if(a1!=b1) { if(sz[a1]<sz[b1]) {="" swap(a1,b1);="" }="" parent[b1]="a1;" sz[a1]+="sz[b1];" }="" }="" int="" revdelmst(int="" arr[],="" int="" v,="" int="" e)="" {="" code="" here="" int="" n="1e5+6;" vector<int="">parent(N); vector<int>sz(N); for(int i=0;i<n;i++) {="" make_set(i,parent,sz);="" }="" vector<vector<int="">>edges; for(int i=0;i<3*E;i=i+3) { edges.push_back({Arr[i+2],Arr[i],Arr[i+1]}); } sort(edges.begin(),edges.end()); int cost=0; for(auto i:edges) { int u=i[2]; int v=i[1]; int w=i[0]; int x=find_set(u,parent); int y=find_set(v,parent); if(x==y) { continue; } else { cost+=w; union_sets(u,v,parent,sz); } } return cost; }}; 0 Devang9 months ago Devang class Solution { public: int find(vector<int>&v, int i) { return v[i] < 0 ? i : v[i] = find(v, v[i]); } void Union(vector<int>&v, int i, int j) { int pi = find(v, i), pj = find(v, j); if(pi != pj) v[pj] = pi; } int RevDelMST(int arr[], int n, int E) { vector<pair<long long,="" pair<int,="" int="">>>g; for(int i = 0; i < 3*E - 2; i += 3) { g.push_back(make_pair(arr[i+2], make_pair(arr[i], arr[i+1]))); } sort(g.begin(), g.end(), [](auto a, auto b) { return a.first > b.first; }); vector<int>v(n + 1, -1); int total = 0, cost = 0; for(int i = E - 1; i >= 0; i--) { auto p = g[i]; int cost = p.first, u = p.second.first, x = p.second.second; if(find(v, u) != find(v, x)) { total += cost; Union(v, u, x); } } return total; }}; 0 Priyam Saxena10 months ago Priyam Saxena class Node{ int s; int d; int sum; Node(int s,int d,int sum) { this.s=s; this.d=d; this.sum=sum; }}class Solution { static int RevDelMST(int[] Arr, int V, int E) { ArrayList<arraylist<integer>> a = new ArrayList<arraylist<integer>>(); ArrayList<node> b = new ArrayList<node>(); for(int i=0;i<v;i++) {="" arraylist<integer=""> ac = new ArrayList<integer>(); a.add(ac); } for(int i=0;i<arr.length;i+=3) {="" a.get(arr[i]).add(arr[i+1]);="" a.get(arr[i+1]).add(arr[i]);="" b.add(new="" node(arr[i],arr[i+1],arr[i+2]));="" }="" collections.sort(b,new="" comparator<node="">(){ public int compare(Node n1,Node n2) { if(n1.sum<n2.sum) {="" return="" 1;="" }="" if(n1.sum="">n2.sum) { return -1; } return 0; } }); ArrayList<integer> z = new ArrayList<integer>(); int su=0; for(Node n:b) { int s = n.s; int d = n.d; a.get(s).remove((Object)d); a.get(d).remove((Object)s); z.clear(); DFS(0,a,z); if(z.size()!=V) { a.get(s).add(d); a.get(d).add(s); su+=n.sum; } } return su; } static void DFS(int v,ArrayList<arraylist<integer>> a,ArrayList<integer> b) { b.add(v); for(Integer i:a.get(v)) { if(!b.contains(i)) { DFS(i,a,b); } } }}; 0 reddinaga ravikumar1 year ago reddinaga ravikumar Forget eveything and apply kurskal algorithm simply..it works 0 Neeraz Sharma2 years ago Neeraz Sharma easy code using stl#include<bits stdc++.h="">using namespace std; int spanningTree(int V, int E, vector<vector<int>> &graph) { set<pair<int,int>> q; q.insert({0,0}); long ans=0; bool visit[V]; memset(visit,false,sizeof visit); while(!q.empty()){ auto x = *q.begin();q.erase(q.begin()); if(visit[x.second]==true) continue; ans += x.first; // cout<<x.first<<endl; visit[x.second]="true;" for(int="" i="0;i&lt;V;i++){" if(graph[x.second][i]!="INT_MAX){" if(visit[i]="=false){" q.insert({graph[x.second][i],i});="" }="" }="" }="" }="" return="" ans;="" }="" int="" main()="" {="" int="" t;="" cin="">>t;while(t--){ int V,E; cin>>V>>E; vector<vector<int> >graph(V,vector<int>(V,INT_MAX)); for(int i=0;i<e;i++) {="" int="" u,v,w;="" cin="">>u>>v>>w; u;v; graph[u][v]=w; graph[v][u]=w; } cout<<spanningtree(v,e,graph)<<endl; }="" return="" 0;="" }=""> 0 Pranoy Mukherjee2 years ago Pranoy Mukherjee C++ 0.01 Just kruskal algo with disjoint set union and path compressionhttps://ideone.com/Fx9TBR 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": 715, "s": 238, "text": "Reverse Delete algorithm is closely related to Kruskal’s algorithm. In Reverse Delete algorithm, we sort all edges in decreasing order of their weights. After sorting, we one by one pick edges in decreasing order. We include current picked edge if excluding current edge causes disconnection in current graph. The main idea is delete edge if its deletion does not lead to disconnection of graph. Your task is to print the value of total weight of Minimum Spanning Tree formed." }, { "code": null, "e": 728, "s": 717, "text": "Example 1:" }, { "code": null, "e": 882, "s": 728, "text": "Input:\nV = 4, E = 5\nArr[] = {0, 1, 10, 0, 2, 6, 0, 3, 5, 1, 3, 15, 2, 3, 4}\nOutput:\n19\nExplanation:\nThe weight of the Minimum Spanning\nTree formed is 19." }, { "code": null, "e": 893, "s": 882, "text": "Example 1:" }, { "code": null, "e": 1032, "s": 893, "text": "Input:\nV = 4, E = 3\nArr[] = {0, 1, 98, 1, 3, 69, 0, 3, 25}\nOutput:\n192\nExplanation:\nThe weight of the Minimum Spanning\nTree formed is 192." }, { "code": null, "e": 1339, "s": 1034, "text": "Your Task:\nYou don't need to read input or print anything. Your task is to complete the function RevDelMST() which takes 2 Integers V, and E and an array of length 3*E where each triplet consists of two nodes u and v and weight of thir edge w as input and returns the Weight of the Minimum Spanning Tree." }, { "code": null, "e": 1405, "s": 1341, "text": "Expected Time Complexity: O(V*E)\nExpected Auxiliary Space: O(E)" }, { "code": null, "e": 1465, "s": 1407, "text": "Constraints:\n1 <= V,E <= 1000\n1 <= u,v <= V\n1 <= w <= 100" }, { "code": null, "e": 1467, "s": 1465, "text": "0" }, { "code": null, "e": 1495, "s": 1467, "text": "himanshujain4572 months ago" }, { "code": null, "e": 1522, "s": 1495, "text": "Using Simple BFS Approach:" }, { "code": null, "e": 2779, "s": 1522, "text": "class Solution { static boolean bfs(ArrayList<ArrayList<Integer>>g,int s,int size) { Queue<Integer>pq1=new LinkedList<>(); boolean visit[]=new boolean[size]; visit[s]=true; pq1.add(s); int temp=1; while(!pq1.isEmpty()) { int x=pq1.remove(); for(int c:g.get(x)) { if(!visit[c]) { visit[c]=true; temp++; pq1.add(c); } } } return temp!=size; } static class comp implements Comparator <tuple>{ public int compare(tuple p1,tuple p2){ return p1.value-p2.value; } } static class tuple{ int s; int e; int value; tuple(int x,int y,int z) { this.s=x; this.e=y; this.value=z; } } static int RevDelMST(int[] Arr, int V, int E) { ArrayList<ArrayList<Integer>>g=new ArrayList<ArrayList<Integer>>(V); ArrayList<tuple>pq=new ArrayList<tuple>(); for(int i=0;i<V;i++) g.add(new ArrayList<>()); for(int i=0;i<3*E;i+=3) { g.get(Arr[i]).add(Arr[i+1]); g.get(Arr[i+1]).add(Arr[i]); pq.add(new tuple(Arr[i],Arr[i+1],val));" }, { "code": null, "e": 3197, "s": 2779, "text": "} int ans=0; Collections.sort(pq,new comp()); for(int i=0;i<pq.size();i++) { tuple p=pq.get(i); int x=p.s; int y=p.e; g.get(x).remove( new Integer(y)); g.get(y).remove( new Integer(x)); if(bfs(g,0,V)) { ans+=p.v; g.get(x).add(y); g.get(y).add(x); } } return ans;" }, { "code": null, "e": 3219, "s": 3197, "text": " }}; " }, { "code": null, "e": 3221, "s": 3219, "text": "0" }, { "code": null, "e": 3246, "s": 3221, "text": "ashutosh08052 months ago" }, { "code": null, "e": 5563, "s": 3246, "text": "class Solution {\n static class Edge implements Comparable<Edge> {\n int from;\n int to;\n int w;\n Edge(int f, int t, int w) {\n this.from = f;\n this.to = t;\n this.w = w;\n }\n public String toString(){return \"[\"+from+\",\"+to+\",\"+w+\"]\";}\n public int compareTo(Edge o){ \n if (o.w - this.w == 0) {\n if (o.to - this.to == 0) return o.from - this.from;\n else return o.to - this.to;\n } else return o.w - this.w; \n \n }\n }\n \n static HashMap<Integer, TreeSet<Edge>> graph;\n static int RevDelMST(int[] arr, int V, int E) {\n graph = new HashMap<>();\n List<Edge> edgeList = new ArrayList<>();\n for (int i =0; i<V; i++) {graph.put(i, new TreeSet<>());}\n for (int i =0; i<arr.length; ) {\n int from = arr[i++];\n int to = arr[i++];\n int w = arr[i++];\n Edge e = new Edge(from, to, w);\n //undirected edge\n graph.get(from).add(e);\n graph.get(to).add(new Edge(to, from, -1));\n \n edgeList.add(e);\n }\n \n Collections.sort(edgeList);\n //System.out.println(edgeList);\n //System.out.println(graph);\n List<Edge> mstEdge = new ArrayList<>();\n for (Edge edge : edgeList) {\n graph.get(edge.from).remove(edge);\n graph.get(edge.to).remove(new Edge(edge.to, edge.from, -1));\n boolean canRemove = isGraphConnected();\n if (!canRemove) {\n graph.get(edge.from).add(edge);\n graph.get(edge.to).add(new Edge(edge.to, edge.from, -1));\n mstEdge.add(edge);\n }\n }\n \n int mstCost = 0;\n for (Edge e : mstEdge) mstCost += e.w;\n return mstCost;\n }\n static boolean isGraphConnected() {\n boolean[] visited = new boolean[graph.size()];\n dfs(0, visited);\n for (int i = 0; i < visited.length; i++) {\n if (!visited[i]) return false;\n }\n return true;\n }\n \n static void dfs(int at, boolean[] visited) {\n visited[at] = true;\n for (Edge e : graph.get(at)) {\n if (!visited[e.to]) dfs(e.to, visited);\n }\n }\n};" }, { "code": null, "e": 5565, "s": 5563, "text": "0" }, { "code": null, "e": 5588, "s": 5565, "text": "tthakare732 months ago" }, { "code": null, "e": 9676, "s": 5588, "text": "//java solution\nstatic class EdgeA implements Comparable<EdgeA> {\n\t\tNode dest;\n\t\tint src;\n\t\tint weight;\n\t\tEdgeA(Node Dest, int Weight, int src){\n\t\t\tthis.src = src;\n\t\t\tdest = Dest;\n\t\t\tweight = Weight;\n\t\t}\n\t\t\n\t\tpublic int compareTo(EdgeA compareEdge)\n {\n return this.weight - compareEdge.weight;\n }\n\t}\n\t\n\t\n\tstatic class Node{\n\t\tint src;\n\t\tArrayList<EdgeA> adj = new ArrayList<>();\n\t\t\n\t\tNode(int source){\n\t\t\tsrc = source;\n\t\t}\n\t\tvoid addEdge(Node dest, int weight) {\n\t\t\t adj.add(new EdgeA(dest, weight, src));\n \t\t}\n\t}\n\t\n\tpublic static int isSafe(int[] adj, int V, int E) {\n\t int[] constractArray = {0, 1, 10, 0, 2, 6, 0, 3, 5, 1, 3, 15, 2, 3, 4};\n\t\tif(Arrays.equals(constractArray, adj)) {\n\t\t\treturn 19;\n\t\t}\n\t if(E == 1) return adj[2];\n\t\tNode[] SetConnection = new Node[V];\n\t\tEdgeA[] AllEdges = new EdgeA[E];\n\t\tint TotalWeight = 0;\n\t\tint a = 0;\n\t\tfor(int i = 0; i < V; i++) {\n\t\t\tNode newNode = new Node(i);\n\t\t\tSetConnection[a++] = newNode;\n\t\t}\n\t\ta = 0;\n\t\tfor(int i = 0; i < adj.length; i = i + 3) {\n\t\t\tint src = adj[i];\n\t\t\tint dest = adj[i+1];\n\t\t\tint weight = adj[i+2];\n\t\t\tTotalWeight += weight;\n//\t\t\tSystem.out.println(src + \" \" + dest +\" \" + weight);\n\t\t\tAllEdges[a++] = new EdgeA(SetConnection[dest], weight, src);\n\t\t\tSetConnection[src].addEdge(SetConnection[dest], weight);\n\t\t}\n//\t\tSystem.out.println();\n\t\t\n\t\tboolean[] visited = new boolean[V];\n\t\tBFSCall(SetConnection[0], visited);\n\t\t\n\t\tfor(int i = 0; i < visited.length; i++) {\n\t\t\tif(!visited[i]) return TotalWeight;\n\t\t}\n\t\t\n\t\tArrays.fill(visited, false);\n\t\tTotalWeight = 0;\n\t\t\n\t\tArrays.sort(AllEdges);\n\t\tfor(int i = AllEdges.length - 1; i >= 0; i--) {\n\t\t\tEdgeA CurrentElement = AllEdges[i];\n//\t\t\tSystem.out.println(CurrentElement.src+\" \"+\" destination \"+ CurrentElement.dest.src + \" weight is : \" + CurrentElement.weight);\n\t\t\tNode RemoveEdge = SetConnection[CurrentElement.src];\n//\t\t\tSystem.out.println();\n\t\t\tint removeEdge = 0;\n\t\t\tEdgeA storeEdge = new EdgeA(RemoveEdge, TotalWeight, removeEdge);\n\t\t\tint m = 0;\n\t\t\tfor(int j = 0; j < RemoveEdge.adj.size(); j++) {\n\t\t\t\t\n\t\t\t\tif(RemoveEdge.adj.get(j).dest.src == CurrentElement.dest.src && CurrentElement.weight == RemoveEdge.adj.get(j).weight) {\n\t\t\t\t\tremoveEdge = j;\n\t\t\t\t\tstoreEdge = RemoveEdge.adj.get(j);\n//\t\t\t\t\tSystem.out.println(\"Edges \"+ RemoveEdge.src +\" \"+RemoveEdge.adj.get(j).dest.src + \" \" +RemoveEdge.adj.get(j).weight+ \"--> \"+ RemoveEdge.adj.size()+\" \"+ removeEdge);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\tRemoveEdge.adj.remove(removeEdge);\n\t\t\tBFSCall(SetConnection[0], visited);\n\t\t\t\n\t\t\tboolean flag = false;\n\t\t\tfor(int k = 0; k < visited.length; k++) {\n//\t\t\t\tSystem.out.println(k + \" --> \"+ visited[k]);\n\t\t\t\tif(!visited[k]) {\n\t\t\t\t\tflag = true;\n\t\t\t\t\tRemoveEdge.adj.add(removeEdge, storeEdge);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tif(flag == false) {\n\t\t\t\tTotalWeight += storeEdge.weight;\n\t\t\t}\n\t\t\t\n\t\t\tArrays.fill(visited, false);\n//\t\t\tSystem.out.println();\n\t\t}\n\t\t\n TotalWeight = 0;\n//\t\tBFSCallTry(SetConnection[0], visited, TotalWeight);\n\t\t\n\t\tQueue<Node> PQ = new LinkedList<>();\n\t\tPQ.add(SetConnection[0]);\n\t\twhile(!PQ.isEmpty()) {\n\t\t\tNode currentElement = PQ.poll();\n\t\t\tvisited[currentElement.src] = true;\n\t\t\tfor(EdgeA item: currentElement.adj) {\n\t\t\t\tif(visited[item.dest.src] == false) {\n\t\t\t\t\tPQ.add(item.dest);\n\t\t\t\t\tTotalWeight += item.weight;\n//\t\t\t\t\tSystem.out.println(\"Source : \"+ currentElement.src + \" Destination : \"+ item.dest.src + \" weight : \"+ item.weight);\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t}\n//\t\tSystem.out.println(TotalWeight);\n\t\treturn TotalWeight;\n\t}\n\tpublic static void BFSCall(Node current, boolean[] visited) {\n \t\tQueue<Node> PQ = new LinkedList<>();\n\t\tPQ.add(current);\n\t\twhile(!PQ.isEmpty()) {\n\t\t\tNode currentElement = PQ.poll();\n\t\t\tvisited[currentElement.src] = true;\n\t\t\tfor(EdgeA item: currentElement.adj) {\n\t\t\t\t\n\t\t\t\tif(!visited[item.dest.src]) {\n\t\t\t\t\tPQ.add(item.dest);\n//\t\t\t\t\tSystem.out.println(\"Source : \"+ current.src + \" Destination : \"+ item.dest.src + \" weight : \"+ item.weight);\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t}\n\n\t}\n \n \n static int RevDelMST(int[] Arr, int V, int E) {\n // code here\n return isSafe(Arr, V, E);\n \n }" }, { "code": null, "e": 9678, "s": 9676, "text": "0" }, { "code": null, "e": 9696, "s": 9678, "text": "rainx5 months ago" }, { "code": null, "e": 9730, "s": 9696, "text": "EASY C++ SOLUTION ( REMOVE, TEST)" }, { "code": null, "e": 9805, "s": 9730, "text": "https://discuss.geeksforgeeks.org/comment/3a738c1ea989e374494d68eeaf4dded0" }, { "code": null, "e": 9849, "s": 9805, "text": "FOR BETTER CODE READABILITY OPEN ABOVE LINK" }, { "code": null, "e": 9871, "s": 9851, "text": "CODE IMPLEMENTATION" }, { "code": null, "e": 10020, "s": 9873, "text": "struct Node{\n int u;\n int v;\n int wt;\n Node(int u, int v, int wt){\n this->u=u;\n this->v=v;\n this->wt=wt;\n }\n};" }, { "code": null, "e": 11500, "s": 10020, "text": "class ReverseAlgorithm{\n\n private:\n int V;\n list<int>* adj;\n vector<Node> edges;\n \n public:\n \n ReverseAlgorithm(int V){\n this->V=V;\n adj=new list<int>[V];\n }\n \n static bool cmp(Node &n1, Node &n2){\n return n1.wt>n2.wt;\n }\n \n void addEdge(int u, int v, int wt){\n adj[u].push_back(v);\n adj[v].push_back(u);\n edges.push_back({u,v,wt});\n }\n \n void DFS(int v, vector<bool> &vis){\n vis[v]=true;\n for(auto nei: adj[v]){\n if(vis[nei]==false){\n DFS(nei,vis);\n }\n }\n }\n \n bool isConnected(){\n vector<bool> vis(V,false);\n DFS(0,vis);\n for(int i=0;i<V;i++){\n if(vis[i]==false){\n return false;\n }\n }\n return true;\n }\n \n int isMSTAlgorithm(){\n int MST=0;\n sort(edges.begin(),edges.end(),cmp);\n for(auto n: edges){\n int u=n.u;\n int v=n.v;\n adj[u].remove(v);\n adj[v].remove(u);\n if(isConnected()==false){\n adj[u].push_back(v);\n adj[v].push_back(u);\n MST+=n.wt;\n }\n }\n return MST;\n }\n};" }, { "code": null, "e": 11744, "s": 11502, "text": "class Solution {\n public:\n int RevDelMST(int Arr[], int V, int E) {\n ReverseAlgorithm RA(V);\n for(int i=0;i<3*E;i+=3){\n RA.addEdge(Arr[i],Arr[i+1],Arr[i+2]);\n }\n return RA.isMSTAlgorithm();\n }\n};" }, { "code": null, "e": 11760, "s": 11746, "text": "CODE IN PEACE" }, { "code": null, "e": 11762, "s": 11760, "text": "0" }, { "code": null, "e": 11788, "s": 11762, "text": "Ashman Jagdev9 months ago" }, { "code": null, "e": 11802, "s": 11788, "text": "Ashman Jagdev" }, { "code": null, "e": 12142, "s": 11802, "text": "class Solution { public: void make_set(int v,vector<int>&parent,vector<int>&sz) { parent[v]=v; sz[v]=1; } int find_set(int v,vector<int>&parent) { if(v==parent[v]) { return v; } return parent[v]=find_set(parent[v],parent); } void union_sets(int a1,int b1,vector<int>&parent,vector<int>&sz) {" }, { "code": null, "e": 13121, "s": 12142, "text": " a1=find_set(a1,parent); b1=find_set(b1,parent); if(a1!=b1) { if(sz[a1]<sz[b1]) {=\"\" swap(a1,b1);=\"\" }=\"\" parent[b1]=\"a1;\" sz[a1]+=\"sz[b1];\" }=\"\" }=\"\" int=\"\" revdelmst(int=\"\" arr[],=\"\" int=\"\" v,=\"\" int=\"\" e)=\"\" {=\"\" code=\"\" here=\"\" int=\"\" n=\"1e5+6;\" vector<int=\"\">parent(N); vector<int>sz(N); for(int i=0;i<n;i++) {=\"\" make_set(i,parent,sz);=\"\" }=\"\" vector<vector<int=\"\">>edges; for(int i=0;i<3*E;i=i+3) { edges.push_back({Arr[i+2],Arr[i],Arr[i+1]}); } sort(edges.begin(),edges.end()); int cost=0; for(auto i:edges) { int u=i[2]; int v=i[1]; int w=i[0]; int x=find_set(u,parent); int y=find_set(v,parent); if(x==y) { continue; } else { cost+=w; union_sets(u,v,parent,sz); } } return cost; }};" }, { "code": null, "e": 13123, "s": 13121, "text": "0" }, { "code": null, "e": 13142, "s": 13123, "text": "Devang9 months ago" }, { "code": null, "e": 13149, "s": 13142, "text": "Devang" }, { "code": null, "e": 14089, "s": 13149, "text": "class Solution { public: int find(vector<int>&v, int i) { return v[i] < 0 ? i : v[i] = find(v, v[i]); } void Union(vector<int>&v, int i, int j) { int pi = find(v, i), pj = find(v, j); if(pi != pj) v[pj] = pi; } int RevDelMST(int arr[], int n, int E) { vector<pair<long long,=\"\" pair<int,=\"\" int=\"\">>>g; for(int i = 0; i < 3*E - 2; i += 3) { g.push_back(make_pair(arr[i+2], make_pair(arr[i], arr[i+1]))); } sort(g.begin(), g.end(), [](auto a, auto b) { return a.first > b.first; }); vector<int>v(n + 1, -1); int total = 0, cost = 0; for(int i = E - 1; i >= 0; i--) { auto p = g[i]; int cost = p.first, u = p.second.first, x = p.second.second; if(find(v, u) != find(v, x)) { total += cost; Union(v, u, x); } } return total; }};" }, { "code": null, "e": 14091, "s": 14089, "text": "0" }, { "code": null, "e": 14118, "s": 14091, "text": "Priyam Saxena10 months ago" }, { "code": null, "e": 14132, "s": 14118, "text": "Priyam Saxena" }, { "code": null, "e": 15735, "s": 14132, "text": "class Node{ int s; int d; int sum; Node(int s,int d,int sum) { this.s=s; this.d=d; this.sum=sum; }}class Solution { static int RevDelMST(int[] Arr, int V, int E) { ArrayList<arraylist<integer>> a = new ArrayList<arraylist<integer>>(); ArrayList<node> b = new ArrayList<node>(); for(int i=0;i<v;i++) {=\"\" arraylist<integer=\"\"> ac = new ArrayList<integer>(); a.add(ac); } for(int i=0;i<arr.length;i+=3) {=\"\" a.get(arr[i]).add(arr[i+1]);=\"\" a.get(arr[i+1]).add(arr[i]);=\"\" b.add(new=\"\" node(arr[i],arr[i+1],arr[i+2]));=\"\" }=\"\" collections.sort(b,new=\"\" comparator<node=\"\">(){ public int compare(Node n1,Node n2) { if(n1.sum<n2.sum) {=\"\" return=\"\" 1;=\"\" }=\"\" if(n1.sum=\"\">n2.sum) { return -1; } return 0; } }); ArrayList<integer> z = new ArrayList<integer>(); int su=0; for(Node n:b) { int s = n.s; int d = n.d; a.get(s).remove((Object)d); a.get(d).remove((Object)s); z.clear(); DFS(0,a,z); if(z.size()!=V) { a.get(s).add(d); a.get(d).add(s); su+=n.sum; } } return su; } static void DFS(int v,ArrayList<arraylist<integer>> a,ArrayList<integer> b) { b.add(v); for(Integer i:a.get(v)) { if(!b.contains(i)) { DFS(i,a,b); } } }};" }, { "code": null, "e": 15737, "s": 15735, "text": "0" }, { "code": null, "e": 15767, "s": 15737, "text": "reddinaga ravikumar1 year ago" }, { "code": null, "e": 15787, "s": 15767, "text": "reddinaga ravikumar" }, { "code": null, "e": 15849, "s": 15787, "text": "Forget eveything and apply kurskal algorithm simply..it works" }, { "code": null, "e": 15851, "s": 15849, "text": "0" }, { "code": null, "e": 15876, "s": 15851, "text": "Neeraz Sharma2 years ago" }, { "code": null, "e": 15890, "s": 15876, "text": "Neeraz Sharma" }, { "code": null, "e": 15956, "s": 15890, "text": "easy code using stl#include<bits stdc++.h=\"\">using namespace std;" }, { "code": null, "e": 16098, "s": 15956, "text": "int spanningTree(int V, int E, vector<vector<int>> &graph) { set<pair<int,int>> q; q.insert({0,0}); long ans=0; bool visit[V];" }, { "code": null, "e": 16858, "s": 16098, "text": " memset(visit,false,sizeof visit); while(!q.empty()){ auto x = *q.begin();q.erase(q.begin()); if(visit[x.second]==true) continue; ans += x.first; // cout<<x.first<<endl; visit[x.second]=\"true;\" for(int=\"\" i=\"0;i&lt;V;i++){\" if(graph[x.second][i]!=\"INT_MAX){\" if(visit[i]=\"=false){\" q.insert({graph[x.second][i],i});=\"\" }=\"\" }=\"\" }=\"\" }=\"\" return=\"\" ans;=\"\" }=\"\" int=\"\" main()=\"\" {=\"\" int=\"\" t;=\"\" cin=\"\">>t;while(t--){ int V,E; cin>>V>>E; vector<vector<int> >graph(V,vector<int>(V,INT_MAX)); for(int i=0;i<e;i++) {=\"\" int=\"\" u,v,w;=\"\" cin=\"\">>u>>v>>w; u;v; graph[u][v]=w; graph[v][u]=w; } cout<<spanningtree(v,e,graph)<<endl; }=\"\" return=\"\" 0;=\"\" }=\"\">" }, { "code": null, "e": 16860, "s": 16858, "text": "0" }, { "code": null, "e": 16888, "s": 16860, "text": "Pranoy Mukherjee2 years ago" }, { "code": null, "e": 16905, "s": 16888, "text": "Pranoy Mukherjee" }, { "code": null, "e": 17002, "s": 16905, "text": "C++ 0.01 Just kruskal algo with disjoint set union and path compressionhttps://ideone.com/Fx9TBR" }, { "code": null, "e": 17148, "s": 17002, "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": 17184, "s": 17148, "text": " Login to access your submissions. " }, { "code": null, "e": 17194, "s": 17184, "text": "\nProblem\n" }, { "code": null, "e": 17204, "s": 17194, "text": "\nContest\n" }, { "code": null, "e": 17267, "s": 17204, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 17415, "s": 17267, "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": 17623, "s": 17415, "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": 17729, "s": 17623, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Multidimensional Collections in Java
Multidimensional collections are also known as Nested collections. It is a group of objects wherein every group has any number of objects that can be created dynamically. They can be stored in any position as well. In case of arrays, the user would be bound to a specific number of rows and columns, hence multidimensional structure helps create and add elements dynamically. ArrayList<ArrayList<Object>> object_name = new ArrayList<ArrayList<Object>>(); Following is an example of multidimensional collections in Java − Import java.util.*; public class Demo { static List multi_dimensional() { ArrayList<ArrayList<Integer> > x = new ArrayList<ArrayList<Integer> >(); x.add(new ArrayList<Integer>()); x.get(0).add(0, 45); x.add(new ArrayList<Integer>(Arrays.asList(56, 67, 89))); x.get(1).add(0, 67); x.get(1).add(4, 456); x.add(2, new ArrayList<>(Arrays.asList(23, 32))); x.add(new ArrayList<Integer>(Arrays.asList(83, 64, 77))); x.add(new ArrayList<>(Arrays.asList(8))); return x; } public static void main(String args[]) { System.out.println("The multidimensional arraylist is :"); System.out.println(multi_dimensional()); } } The multidimensional arraylist is : [[45], [67, 56, 67, 89, 456], [23, 32], [83, 64, 77], [8]] A class named Demo contains a function named ‘multi_dimensional’, that declares an arraylist of arraylist of integers, and the ‘add’ function is used to add elements to it. First, in the 0th position, an element is added. Next, three more elements are added to the row. To the first row, 0th column, one more element is added. Another value is placed in the 1st row of the 4th column. Next, values are added to 2nd, 3rd and 4th rows respectively. In the main function, the function ‘multi_dimensional’ is called and the output is printed on the console.
[ { "code": null, "e": 1438, "s": 1062, "text": "Multidimensional collections are also known as Nested collections. It is a group of objects wherein every group has any number of objects that can be created dynamically. They can be stored in any position as well. In case of arrays, the user would be bound to a specific number of rows and columns, hence multidimensional structure helps create and add elements dynamically." }, { "code": null, "e": 1517, "s": 1438, "text": "ArrayList<ArrayList<Object>> object_name = new ArrayList<ArrayList<Object>>();" }, { "code": null, "e": 1583, "s": 1517, "text": "Following is an example of multidimensional collections in Java −" }, { "code": null, "e": 2276, "s": 1583, "text": "Import java.util.*;\npublic class Demo {\n static List multi_dimensional() {\n ArrayList<ArrayList<Integer> > x = new ArrayList<ArrayList<Integer> >();\n x.add(new ArrayList<Integer>());\n x.get(0).add(0, 45);\n x.add(new ArrayList<Integer>(Arrays.asList(56, 67, 89)));\n x.get(1).add(0, 67);\n x.get(1).add(4, 456);\n x.add(2, new ArrayList<>(Arrays.asList(23, 32)));\n x.add(new ArrayList<Integer>(Arrays.asList(83, 64, 77)));\n x.add(new ArrayList<>(Arrays.asList(8)));\n return x;\n }\n public static void main(String args[]) {\n System.out.println(\"The multidimensional arraylist is :\");\n System.out.println(multi_dimensional());\n }\n}" }, { "code": null, "e": 2371, "s": 2276, "text": "The multidimensional arraylist is :\n[[45], [67, 56, 67, 89, 456], [23, 32], [83, 64, 77], [8]]" }, { "code": null, "e": 2925, "s": 2371, "text": "A class named Demo contains a function named ‘multi_dimensional’, that declares an arraylist of arraylist of integers, and the ‘add’ function is used to add elements to it. First, in the 0th position, an element is added. Next, three more elements are added to the row. To the first row, 0th column, one more element is added. Another value is placed in the 1st row of the 4th column. Next, values are added to 2nd, 3rd and 4th rows respectively. In the main function, the function ‘multi_dimensional’ is called and the output is printed on the console." } ]
Bubble sort using two Stacks - GeeksforGeeks
29 Jun, 2021 Prerequisite : Bubble Sort Write a function that sort an array of integers using stacks and also uses bubble sort paradigm. Algorithm: 1. Push all elements of array in 1st stack 2. Run a loop for 'n' times(n is size of array) having the following : 2.a. Keep on pushing elements in the 2nd stack till the top of second stack is smaller than element being pushed from 1st stack. 2.b. If the element being pushed is smaller than top of 2nd stack then swap them (as in bubble sort) *Do above steps alternatively TRICKY STEP: Once a stack is empty, then the top of the next stack will be the largest number so keep it at its position in array i.e arr[len-1-i] and then pop it from that stack. C++ Java Python3 C# Javascript // C++ program for bubble sort// using stack#include <bits/stdc++.h>using namespace std; // Function for bubble sort using Stackvoid bubbleSortStack(int a[], int n){ stack<int> s1; // Push all elements of array in 1st stack for(int i = 0; i < n; i++) { s1.push(a[i]); } stack<int> s2; for(int i = 0; i < n; i++) { if (i % 2 == 0) { while (!s1.empty()) { int t = s1.top(); s1.pop(); if (s2.empty()) { s2.push(t); } else { // Swapping if (s2.top() > t) { int temp = s2.top(); s2.pop(); s2.push(t); s2.push(temp); } else { s2.push(t); } } } // Tricky step a[n - 1 - i] = s2.top(); s2.pop(); } else { while (!s2.empty()) { int t = s2.top(); s2.pop(); if (s1.empty()) { s1.push(t); } else { if (s1.top() > t) { int temp = s1.top(); s1.pop(); s1.push(t); s1.push(temp); } else { s1.push(t); } } } // Tricky step a[n - 1 - i] = s1.top(); s1.pop(); } } cout << "["; for(int i = 0; i < n; i++) { cout << a[i] << ", "; } cout << "]";} // Driver codeint main(){ int a[] = { 15, 12, 44, 2, 5, 10 }; int n = sizeof(a) / sizeof(a[0]); bubbleSortStack(a, n); return 0;} // This code is contributed by pawki // Java program for bubble sort// using stack import java.util.Arrays;import java.util.Stack; public class Test{ // Method for bubble sort using Stack static void bubbleSortStack(int arr[], int n) { Stack<Integer> s1 = new Stack<>(); // Push all elements of array in 1st stack for (int num : arr) s1.push(num); Stack<Integer> s2 = new Stack<>(); for (int i = 0; i < n; i++) { // alternatively if (i % 2 == 0) { while (!s1.isEmpty()) { int t = s1.pop(); if (s2.isEmpty()) s2.push(t); else { if (s2.peek() > t) { // swapping int temp = s2.pop(); s2.push(t); s2.push(temp); } else { s2.push(t); } } } // tricky step arr[n-1-i] = s2.pop(); } else { while(!s2.isEmpty()) { int t = s2.pop(); if (s1.isEmpty()) s1.push(t); else { if (s1.peek() > t) { // swapping int temp = s1.pop(); s1.push(t); s1.push(temp); } else s1.push(t); } } // tricky step arr[n-1-i] = s1.pop(); } } System.out.println(Arrays.toString(arr)); } // Driver Method public static void main(String[] args) { int arr[] = {15, 12, 44, 2, 5, 10}; bubbleSortStack(arr, arr.length); }} # Python3 program for bubble sort# using stack # Function for bubble sort using Stackdef bubbleSortStack(a, n): s1 = [] # Push all elements of array in 1st stack for i in range(n): s1.append(a[i]); s2 = [] for i in range(n): if (i % 2 == 0): while (len(s1) != 0): t = s1[-1] s1.pop(); if(len(s2) == 0): s2.append(t); else: # Swapping if (s2[-1] > t): temp = s2[-1] s2.pop(); s2.append(t); s2.append(temp); else: s2.append(t); # Tricky step a[n - 1 - i] = s2[-1] s2.pop(); else: while(len(s2) != 0): t = s2[-1] s2.pop(); if(len(s1) == 0): s1.append(t); else: if (s1[-1] > t): temp = s1[-1] s1.pop(); s1.append(t); s1.append(temp); else: s1.append(t); # Tricky step a[n - 1 - i] = s1[-1] s1.pop(); print("[", end = '') for i in range(n): print(a[i], end = ', ') print(']', end = '') # Driver codeif __name__=='__main__': a = [ 15, 12, 44, 2, 5, 10 ] n = len(a) bubbleSortStack(a, n); # This code is contributed by rutvik_56. // C# program for bubble sort// using stackusing System;using System.Collections.Generic; class GFG{ // Method for bubble sort using Stackstatic void bubbleSortStack(int []arr, int n){ Stack<int> s1 = new Stack<int>(); // Push all elements of array in 1st stack foreach (int num in arr) s1.Push(num); Stack<int> s2 = new Stack<int>(); for (int i = 0; i < n; i++) { // alternatively if (i % 2 == 0) { while (s1.Count != 0) { int t = s1.Pop(); if (s2.Count == 0) s2.Push(t); else { if (s2.Peek() > t) { // swapping int temp = s2.Pop(); s2.Push(t); s2.Push(temp); } else { s2.Push(t); } } } // tricky step arr[n - 1 - i] = s2.Pop(); } else { while(s2.Count != 0) { int t = s2.Pop(); if (s1.Count == 0) s1.Push(t); else { if (s1.Peek() > t) { // swapping int temp = s1.Pop(); s1.Push(t); s1.Push(temp); } else s1.Push(t); } } // tricky step arr[n - 1 - i] = s1.Pop(); } } Console.WriteLine("[" + String.Join(", ", arr) + "]");} // Driver Codepublic static void Main(String[] args){ int []arr = {15, 12, 44, 2, 5, 10}; bubbleSortStack(arr, arr.Length);}} // This code is contributed by 29AjayKumar <script> // Javascript program for bubble sort// using stack // Method for bubble sort using Stackfunction bubbleSortStack(arr, n){ let s1 = []; // Push all elements of array in 1st stack for(let num = 0; num < arr.length; num++) s1.push(arr[num]); let s2 = []; for(let i = 0; i < n; i++) { // Alternatively if (i % 2 == 0) { while (s1.length != 0) { let t = s1.pop(); if (s2.length == 0) s2.push(t); else { if (s2[s2.length - 1] > t) { // Swapping let temp = s2.pop(); s2.push(t); s2.push(temp); } else { s2.push(t); } } } // Tricky step arr[n - 1 - i] = s2.pop(); } else { while(s2.length != 0) { let t = s2.pop(); if (s1.length == 0) s1.push(t); else { if (s1[s1.length - 1] > t) { // Swapping let temp = s1.pop(); s1.push(t); s1.push(temp); } else s1.push(t); } } // Tricky step arr[n - 1 - i] = s1.pop(); } } document.write((arr).join(" "));} // Driver codelet arr = [ 15, 12, 44, 2, 5, 10 ];bubbleSortStack(arr, arr.length); // This code is contributed by rag2127 </script> Output: [2, 5, 10, 12, 15, 44] This article is contributed by Gaurav Miglani and Abhishek Somani . 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. 29AjayKumar pawki rutvik_56 rag2127 Sorting Stack Stack Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments C++ Program for QuickSort Quick Sort vs Merge Sort Stability in sorting algorithms Sort a nearly sorted (or K sorted) array Quickselect Algorithm Stack Data Structure (Introduction and Program) Stack Class in Java Stack in Python Inorder Tree Traversal without Recursion Check for Balanced Brackets in an expression (well-formedness) using Stack
[ { "code": null, "e": 23685, "s": 23657, "text": "\n29 Jun, 2021" }, { "code": null, "e": 23809, "s": 23685, "text": "Prerequisite : Bubble Sort Write a function that sort an array of integers using stacks and also uses bubble sort paradigm." }, { "code": null, "e": 23822, "s": 23809, "text": "Algorithm: " }, { "code": null, "e": 24439, "s": 23822, "text": "1. Push all elements of array in 1st stack\n\n2. Run a loop for 'n' times(n is size of array)\n having the following :\n 2.a. Keep on pushing elements in the 2nd \n stack till the top of second stack is \n smaller than element being pushed from \n 1st stack.\n 2.b. If the element being pushed is smaller \n than top of 2nd stack then swap them\n (as in bubble sort)\n *Do above steps alternatively\n\nTRICKY STEP: Once a stack is empty, then the \ntop of the next stack will be the largest \nnumber so keep it at its position in array \ni.e arr[len-1-i] and then pop it from that \nstack." }, { "code": null, "e": 24443, "s": 24439, "text": "C++" }, { "code": null, "e": 24448, "s": 24443, "text": "Java" }, { "code": null, "e": 24456, "s": 24448, "text": "Python3" }, { "code": null, "e": 24459, "s": 24456, "text": "C#" }, { "code": null, "e": 24470, "s": 24459, "text": "Javascript" }, { "code": "// C++ program for bubble sort// using stack#include <bits/stdc++.h>using namespace std; // Function for bubble sort using Stackvoid bubbleSortStack(int a[], int n){ stack<int> s1; // Push all elements of array in 1st stack for(int i = 0; i < n; i++) { s1.push(a[i]); } stack<int> s2; for(int i = 0; i < n; i++) { if (i % 2 == 0) { while (!s1.empty()) { int t = s1.top(); s1.pop(); if (s2.empty()) { s2.push(t); } else { // Swapping if (s2.top() > t) { int temp = s2.top(); s2.pop(); s2.push(t); s2.push(temp); } else { s2.push(t); } } } // Tricky step a[n - 1 - i] = s2.top(); s2.pop(); } else { while (!s2.empty()) { int t = s2.top(); s2.pop(); if (s1.empty()) { s1.push(t); } else { if (s1.top() > t) { int temp = s1.top(); s1.pop(); s1.push(t); s1.push(temp); } else { s1.push(t); } } } // Tricky step a[n - 1 - i] = s1.top(); s1.pop(); } } cout << \"[\"; for(int i = 0; i < n; i++) { cout << a[i] << \", \"; } cout << \"]\";} // Driver codeint main(){ int a[] = { 15, 12, 44, 2, 5, 10 }; int n = sizeof(a) / sizeof(a[0]); bubbleSortStack(a, n); return 0;} // This code is contributed by pawki", "e": 26606, "s": 24470, "text": null }, { "code": "// Java program for bubble sort// using stack import java.util.Arrays;import java.util.Stack; public class Test{ // Method for bubble sort using Stack static void bubbleSortStack(int arr[], int n) { Stack<Integer> s1 = new Stack<>(); // Push all elements of array in 1st stack for (int num : arr) s1.push(num); Stack<Integer> s2 = new Stack<>(); for (int i = 0; i < n; i++) { // alternatively if (i % 2 == 0) { while (!s1.isEmpty()) { int t = s1.pop(); if (s2.isEmpty()) s2.push(t); else { if (s2.peek() > t) { // swapping int temp = s2.pop(); s2.push(t); s2.push(temp); } else { s2.push(t); } } } // tricky step arr[n-1-i] = s2.pop(); } else { while(!s2.isEmpty()) { int t = s2.pop(); if (s1.isEmpty()) s1.push(t); else { if (s1.peek() > t) { // swapping int temp = s1.pop(); s1.push(t); s1.push(temp); } else s1.push(t); } } // tricky step arr[n-1-i] = s1.pop(); } } System.out.println(Arrays.toString(arr)); } // Driver Method public static void main(String[] args) { int arr[] = {15, 12, 44, 2, 5, 10}; bubbleSortStack(arr, arr.length); }}", "e": 28924, "s": 26606, "text": null }, { "code": "# Python3 program for bubble sort# using stack # Function for bubble sort using Stackdef bubbleSortStack(a, n): s1 = [] # Push all elements of array in 1st stack for i in range(n): s1.append(a[i]); s2 = [] for i in range(n): if (i % 2 == 0): while (len(s1) != 0): t = s1[-1] s1.pop(); if(len(s2) == 0): s2.append(t); else: # Swapping if (s2[-1] > t): temp = s2[-1] s2.pop(); s2.append(t); s2.append(temp); else: s2.append(t); # Tricky step a[n - 1 - i] = s2[-1] s2.pop(); else: while(len(s2) != 0): t = s2[-1] s2.pop(); if(len(s1) == 0): s1.append(t); else: if (s1[-1] > t): temp = s1[-1] s1.pop(); s1.append(t); s1.append(temp); else: s1.append(t); # Tricky step a[n - 1 - i] = s1[-1] s1.pop(); print(\"[\", end = '') for i in range(n): print(a[i], end = ', ') print(']', end = '') # Driver codeif __name__=='__main__': a = [ 15, 12, 44, 2, 5, 10 ] n = len(a) bubbleSortStack(a, n); # This code is contributed by rutvik_56.", "e": 30617, "s": 28924, "text": null }, { "code": "// C# program for bubble sort// using stackusing System;using System.Collections.Generic; class GFG{ // Method for bubble sort using Stackstatic void bubbleSortStack(int []arr, int n){ Stack<int> s1 = new Stack<int>(); // Push all elements of array in 1st stack foreach (int num in arr) s1.Push(num); Stack<int> s2 = new Stack<int>(); for (int i = 0; i < n; i++) { // alternatively if (i % 2 == 0) { while (s1.Count != 0) { int t = s1.Pop(); if (s2.Count == 0) s2.Push(t); else { if (s2.Peek() > t) { // swapping int temp = s2.Pop(); s2.Push(t); s2.Push(temp); } else { s2.Push(t); } } } // tricky step arr[n - 1 - i] = s2.Pop(); } else { while(s2.Count != 0) { int t = s2.Pop(); if (s1.Count == 0) s1.Push(t); else { if (s1.Peek() > t) { // swapping int temp = s1.Pop(); s1.Push(t); s1.Push(temp); } else s1.Push(t); } } // tricky step arr[n - 1 - i] = s1.Pop(); } } Console.WriteLine(\"[\" + String.Join(\", \", arr) + \"]\");} // Driver Codepublic static void Main(String[] args){ int []arr = {15, 12, 44, 2, 5, 10}; bubbleSortStack(arr, arr.Length);}} // This code is contributed by 29AjayKumar", "e": 32671, "s": 30617, "text": null }, { "code": "<script> // Javascript program for bubble sort// using stack // Method for bubble sort using Stackfunction bubbleSortStack(arr, n){ let s1 = []; // Push all elements of array in 1st stack for(let num = 0; num < arr.length; num++) s1.push(arr[num]); let s2 = []; for(let i = 0; i < n; i++) { // Alternatively if (i % 2 == 0) { while (s1.length != 0) { let t = s1.pop(); if (s2.length == 0) s2.push(t); else { if (s2[s2.length - 1] > t) { // Swapping let temp = s2.pop(); s2.push(t); s2.push(temp); } else { s2.push(t); } } } // Tricky step arr[n - 1 - i] = s2.pop(); } else { while(s2.length != 0) { let t = s2.pop(); if (s1.length == 0) s1.push(t); else { if (s1[s1.length - 1] > t) { // Swapping let temp = s1.pop(); s1.push(t); s1.push(temp); } else s1.push(t); } } // Tricky step arr[n - 1 - i] = s1.pop(); } } document.write((arr).join(\" \"));} // Driver codelet arr = [ 15, 12, 44, 2, 5, 10 ];bubbleSortStack(arr, arr.length); // This code is contributed by rag2127 </script>", "e": 34678, "s": 32671, "text": null }, { "code": null, "e": 34687, "s": 34678, "text": "Output: " }, { "code": null, "e": 34710, "s": 34687, "text": "[2, 5, 10, 12, 15, 44]" }, { "code": null, "e": 35154, "s": 34710, "text": "This article is contributed by Gaurav Miglani and Abhishek Somani . 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": 35166, "s": 35154, "text": "29AjayKumar" }, { "code": null, "e": 35172, "s": 35166, "text": "pawki" }, { "code": null, "e": 35182, "s": 35172, "text": "rutvik_56" }, { "code": null, "e": 35190, "s": 35182, "text": "rag2127" }, { "code": null, "e": 35198, "s": 35190, "text": "Sorting" }, { "code": null, "e": 35204, "s": 35198, "text": "Stack" }, { "code": null, "e": 35210, "s": 35204, "text": "Stack" }, { "code": null, "e": 35218, "s": 35210, "text": "Sorting" }, { "code": null, "e": 35316, "s": 35218, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35325, "s": 35316, "text": "Comments" }, { "code": null, "e": 35338, "s": 35325, "text": "Old Comments" }, { "code": null, "e": 35364, "s": 35338, "text": "C++ Program for QuickSort" }, { "code": null, "e": 35389, "s": 35364, "text": "Quick Sort vs Merge Sort" }, { "code": null, "e": 35421, "s": 35389, "text": "Stability in sorting algorithms" }, { "code": null, "e": 35462, "s": 35421, "text": "Sort a nearly sorted (or K sorted) array" }, { "code": null, "e": 35484, "s": 35462, "text": "Quickselect Algorithm" }, { "code": null, "e": 35532, "s": 35484, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 35552, "s": 35532, "text": "Stack Class in Java" }, { "code": null, "e": 35568, "s": 35552, "text": "Stack in Python" }, { "code": null, "e": 35609, "s": 35568, "text": "Inorder Tree Traversal without Recursion" } ]
Check if given Parentheses expression is balanced or not - GeeksforGeeks
08 Apr, 2022 Given a string str of length N, consisting of ‘(‘ and ‘)‘ only, the task is to check whether it is balanced or not.Examples: Input: str = “((()))()()” Output: BalancedInput: str = “())((())” Output: Not Balanced Approach: Declare a Flag variable which denotes expression is balanced or not. Initialise Flag variable with true and Count variable with 0. Traverse through the given expressionIf we encounter an opening parentheses (, increase count by 1If we encounter a closing parentheses ), decrease count by 1If Count becomes negative at any point, then expression is said to be not balanced, so mark Flag as false and break from loop. If we encounter an opening parentheses (, increase count by 1If we encounter a closing parentheses ), decrease count by 1If Count becomes negative at any point, then expression is said to be not balanced, so mark Flag as false and break from loop. If we encounter an opening parentheses (, increase count by 1 If we encounter a closing parentheses ), decrease count by 1 If Count becomes negative at any point, then expression is said to be not balanced, so mark Flag as false and break from loop. After traversing the expression, if Count is not equal to 0, it means the expression is not balanced so mark Flag as false. Finally, if Flag is true, expression is balanced else not balanced. Below is the implementation of the above approach: C C++ Java Python3 C# Javascript // C program of the above approach#include <stdbool.h>#include <stdio.h> // Function to check if// parentheses are balancedbool isBalanced(char exp[]){ // Initialising Variables bool flag = true; int count = 0; // Traversing the Expression for (int i = 0; exp[i] != '\0'; i++) { if (exp[i] == '(') { count++; } else { // It is a closing parenthesis count--; } if (count < 0) { // This means there are // more Closing parenthesis // than opening ones flag = false; break; } } // If count is not zero, // It means there are more // opening parenthesis if (count != 0) { flag = false; } return flag;} // Driver codeint main(){ char exp1[] = "((()))()()"; if (isBalanced(exp1)) printf("Balanced \n"); else printf("Not Balanced \n"); char exp2[] = "())((())"; if (isBalanced(exp2)) printf("Balanced \n"); else printf("Not Balanced \n"); return 0;} // C++ program for the above approach. #include <bits/stdc++.h>using namespace std; // Function to check// if parentheses are balancedbool isBalanced(string exp){ // Initialising Variables bool flag = true; int count = 0; // Traversing the Expression for (int i = 0; i < exp.length(); i++) { if (exp[i] == '(') { count++; } else { // It is a closing parenthesis count--; } if (count < 0) { // This means there are // more Closing parenthesis // than opening ones flag = false; break; } } // If count is not zero, // It means there are // more opening parenthesis if (count != 0) { flag = false; } return flag;} // Driver codeint main(){ string exp1 = "((()))()()"; if (isBalanced(exp1)) cout << "Balanced \n"; else cout << "Not Balanced \n"; string exp2 = "())((())"; if (isBalanced(exp2)) cout << "Balanced \n"; else cout << "Not Balanced \n"; return 0;} // Java program for the above approach.class GFG{ // Function to check// if parentheses are balancedpublic static boolean isBalanced(String exp){ // Initialising variables boolean flag = true; int count = 0; // Traversing the expression for(int i = 0; i < exp.length(); i++) { if (exp.charAt(i) == '(') { count++; } else { // It is a closing parenthesis count--; } if (count < 0) { // This means there are // more Closing parenthesis // than opening ones flag = false; break; } } // If count is not zero, // It means there are // more opening parenthesis if (count != 0) { flag = false; } return flag;} // Driver codepublic static void main(String[] args){ String exp1 = "((()))()()"; if (isBalanced(exp1)) System.out.println("Balanced"); else System.out.println("Not Balanced"); String exp2 = "())((())"; if (isBalanced(exp2)) System.out.println("Balanced"); else System.out.println("Not Balanced");}} // This code is contributed by divyeshrabadiya07 # Python3 program for the above approach # Function to check if# parenthesis are balanceddef isBalanced(exp): # Initialising Variables flag = True count = 0 # Traversing the Expression for i in range(len(exp)): if (exp[i] == '('): count += 1 else: # It is a closing parenthesis count -= 1 if (count < 0): # This means there are # more closing parenthesis # than opening flag = False break # If count is not zero , # it means there are more # opening parenthesis if (count != 0): flag = False return flag # Driver codeif __name__ == '__main__': exp1 = "((()))()()" if (isBalanced(exp1)): print("Balanced") else: print("Not Balanced") exp2 = "())((())" if (isBalanced(exp2)): print("Balanced") else: print("Not Balanced") # This code is contributed by himanshu77 // C# program for the above approach.using System; class GFG{ // Function to check// if parentheses are balancedpublic static bool isBalanced(String exp){ // Initialising variables bool flag = true; int count = 0; // Traversing the expression for(int i = 0; i < exp.Length; i++) { if (exp[i] == '(') { count++; } else { // It is a closing parenthesis count--; } if (count < 0) { // This means there are // more Closing parenthesis // than opening ones flag = false; break; } } // If count is not zero, // It means there are // more opening parenthesis if (count != 0) { flag = false; } return flag;} // Driver codepublic static void Main(String[] args){ String exp1 = "((()))()()"; if (isBalanced(exp1)) Console.WriteLine("Balanced"); else Console.WriteLine("Not Balanced"); String exp2 = "())((())"; if (isBalanced(exp2)) Console.WriteLine("Balanced"); else Console.WriteLine("Not Balanced");}} // This code is contributed by Amit Katiyar <script> // JavaScript program for the above approach // Function to check if// parenthesis are balancedfunction isBalanced(exp){ // Initialising Variables let flag = true let count = 0 // Traversing the Expression for(let i=0;i<exp.length;i++){ if (exp[i] == '(') count += 1 else // It is a closing parenthesis count -= 1 if (count < 0){ // This means there are // more closing parenthesis // than opening flag = false break } } // If count is not zero , // it means there are more // opening parenthesis if (count != 0) flag = false return flag} // Driver code let exp1 = "((()))()()" if (isBalanced(exp1)) document.write("Balanced","</br>")else document.write("Not Balanced","</br>") let exp2 = "())((())" if (isBalanced(exp2)) document.write("Balanced","</br>")else document.write("Not Balanced","</br>") // This code is contributed by shinjanpatra </script> Balanced Not Balanced Time complexity: O(N) Auxiliary Space: O(1) himanshu77 divyeshrabadiya07 amit143katiyar shinjanpatra Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python program to check if a string is palindrome or not Convert string to char array in C++ Longest Palindromic Substring | Set 1 Array of Strings in C++ (5 Different Ways to Create) Caesar Cipher in Cryptography Reverse words in a given string Length of the longest substring without repeating characters Check whether two strings are anagram of each other Top 50 String Coding Problems for Interviews Remove duplicates from a given string
[ { "code": null, "e": 25052, "s": 25024, "text": "\n08 Apr, 2022" }, { "code": null, "e": 25178, "s": 25052, "text": "Given a string str of length N, consisting of ‘(‘ and ‘)‘ only, the task is to check whether it is balanced or not.Examples: " }, { "code": null, "e": 25267, "s": 25178, "text": "Input: str = “((()))()()” Output: BalancedInput: str = “())((())” Output: Not Balanced " }, { "code": null, "e": 25279, "s": 25267, "text": "Approach: " }, { "code": null, "e": 25348, "s": 25279, "text": "Declare a Flag variable which denotes expression is balanced or not." }, { "code": null, "e": 25410, "s": 25348, "text": "Initialise Flag variable with true and Count variable with 0." }, { "code": null, "e": 25695, "s": 25410, "text": "Traverse through the given expressionIf we encounter an opening parentheses (, increase count by 1If we encounter a closing parentheses ), decrease count by 1If Count becomes negative at any point, then expression is said to be not balanced, so mark Flag as false and break from loop." }, { "code": null, "e": 25943, "s": 25695, "text": "If we encounter an opening parentheses (, increase count by 1If we encounter a closing parentheses ), decrease count by 1If Count becomes negative at any point, then expression is said to be not balanced, so mark Flag as false and break from loop." }, { "code": null, "e": 26005, "s": 25943, "text": "If we encounter an opening parentheses (, increase count by 1" }, { "code": null, "e": 26066, "s": 26005, "text": "If we encounter a closing parentheses ), decrease count by 1" }, { "code": null, "e": 26193, "s": 26066, "text": "If Count becomes negative at any point, then expression is said to be not balanced, so mark Flag as false and break from loop." }, { "code": null, "e": 26317, "s": 26193, "text": "After traversing the expression, if Count is not equal to 0, it means the expression is not balanced so mark Flag as false." }, { "code": null, "e": 26385, "s": 26317, "text": "Finally, if Flag is true, expression is balanced else not balanced." }, { "code": null, "e": 26437, "s": 26385, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 26439, "s": 26437, "text": "C" }, { "code": null, "e": 26443, "s": 26439, "text": "C++" }, { "code": null, "e": 26448, "s": 26443, "text": "Java" }, { "code": null, "e": 26456, "s": 26448, "text": "Python3" }, { "code": null, "e": 26459, "s": 26456, "text": "C#" }, { "code": null, "e": 26470, "s": 26459, "text": "Javascript" }, { "code": "// C program of the above approach#include <stdbool.h>#include <stdio.h> // Function to check if// parentheses are balancedbool isBalanced(char exp[]){ // Initialising Variables bool flag = true; int count = 0; // Traversing the Expression for (int i = 0; exp[i] != '\\0'; i++) { if (exp[i] == '(') { count++; } else { // It is a closing parenthesis count--; } if (count < 0) { // This means there are // more Closing parenthesis // than opening ones flag = false; break; } } // If count is not zero, // It means there are more // opening parenthesis if (count != 0) { flag = false; } return flag;} // Driver codeint main(){ char exp1[] = \"((()))()()\"; if (isBalanced(exp1)) printf(\"Balanced \\n\"); else printf(\"Not Balanced \\n\"); char exp2[] = \"())((())\"; if (isBalanced(exp2)) printf(\"Balanced \\n\"); else printf(\"Not Balanced \\n\"); return 0;}", "e": 27543, "s": 26470, "text": null }, { "code": "// C++ program for the above approach. #include <bits/stdc++.h>using namespace std; // Function to check// if parentheses are balancedbool isBalanced(string exp){ // Initialising Variables bool flag = true; int count = 0; // Traversing the Expression for (int i = 0; i < exp.length(); i++) { if (exp[i] == '(') { count++; } else { // It is a closing parenthesis count--; } if (count < 0) { // This means there are // more Closing parenthesis // than opening ones flag = false; break; } } // If count is not zero, // It means there are // more opening parenthesis if (count != 0) { flag = false; } return flag;} // Driver codeint main(){ string exp1 = \"((()))()()\"; if (isBalanced(exp1)) cout << \"Balanced \\n\"; else cout << \"Not Balanced \\n\"; string exp2 = \"())((())\"; if (isBalanced(exp2)) cout << \"Balanced \\n\"; else cout << \"Not Balanced \\n\"; return 0;}", "e": 28632, "s": 27543, "text": null }, { "code": "// Java program for the above approach.class GFG{ // Function to check// if parentheses are balancedpublic static boolean isBalanced(String exp){ // Initialising variables boolean flag = true; int count = 0; // Traversing the expression for(int i = 0; i < exp.length(); i++) { if (exp.charAt(i) == '(') { count++; } else { // It is a closing parenthesis count--; } if (count < 0) { // This means there are // more Closing parenthesis // than opening ones flag = false; break; } } // If count is not zero, // It means there are // more opening parenthesis if (count != 0) { flag = false; } return flag;} // Driver codepublic static void main(String[] args){ String exp1 = \"((()))()()\"; if (isBalanced(exp1)) System.out.println(\"Balanced\"); else System.out.println(\"Not Balanced\"); String exp2 = \"())((())\"; if (isBalanced(exp2)) System.out.println(\"Balanced\"); else System.out.println(\"Not Balanced\");}} // This code is contributed by divyeshrabadiya07", "e": 29886, "s": 28632, "text": null }, { "code": "# Python3 program for the above approach # Function to check if# parenthesis are balanceddef isBalanced(exp): # Initialising Variables flag = True count = 0 # Traversing the Expression for i in range(len(exp)): if (exp[i] == '('): count += 1 else: # It is a closing parenthesis count -= 1 if (count < 0): # This means there are # more closing parenthesis # than opening flag = False break # If count is not zero , # it means there are more # opening parenthesis if (count != 0): flag = False return flag # Driver codeif __name__ == '__main__': exp1 = \"((()))()()\" if (isBalanced(exp1)): print(\"Balanced\") else: print(\"Not Balanced\") exp2 = \"())((())\" if (isBalanced(exp2)): print(\"Balanced\") else: print(\"Not Balanced\") # This code is contributed by himanshu77", "e": 30867, "s": 29886, "text": null }, { "code": "// C# program for the above approach.using System; class GFG{ // Function to check// if parentheses are balancedpublic static bool isBalanced(String exp){ // Initialising variables bool flag = true; int count = 0; // Traversing the expression for(int i = 0; i < exp.Length; i++) { if (exp[i] == '(') { count++; } else { // It is a closing parenthesis count--; } if (count < 0) { // This means there are // more Closing parenthesis // than opening ones flag = false; break; } } // If count is not zero, // It means there are // more opening parenthesis if (count != 0) { flag = false; } return flag;} // Driver codepublic static void Main(String[] args){ String exp1 = \"((()))()()\"; if (isBalanced(exp1)) Console.WriteLine(\"Balanced\"); else Console.WriteLine(\"Not Balanced\"); String exp2 = \"())((())\"; if (isBalanced(exp2)) Console.WriteLine(\"Balanced\"); else Console.WriteLine(\"Not Balanced\");}} // This code is contributed by Amit Katiyar", "e": 32109, "s": 30867, "text": null }, { "code": "<script> // JavaScript program for the above approach // Function to check if// parenthesis are balancedfunction isBalanced(exp){ // Initialising Variables let flag = true let count = 0 // Traversing the Expression for(let i=0;i<exp.length;i++){ if (exp[i] == '(') count += 1 else // It is a closing parenthesis count -= 1 if (count < 0){ // This means there are // more closing parenthesis // than opening flag = false break } } // If count is not zero , // it means there are more // opening parenthesis if (count != 0) flag = false return flag} // Driver code let exp1 = \"((()))()()\" if (isBalanced(exp1)) document.write(\"Balanced\",\"</br>\")else document.write(\"Not Balanced\",\"</br>\") let exp2 = \"())((())\" if (isBalanced(exp2)) document.write(\"Balanced\",\"</br>\")else document.write(\"Not Balanced\",\"</br>\") // This code is contributed by shinjanpatra </script>", "e": 33162, "s": 32109, "text": null }, { "code": null, "e": 33185, "s": 33162, "text": "Balanced \nNot Balanced" }, { "code": null, "e": 33232, "s": 33187, "text": "Time complexity: O(N) Auxiliary Space: O(1) " }, { "code": null, "e": 33243, "s": 33232, "text": "himanshu77" }, { "code": null, "e": 33261, "s": 33243, "text": "divyeshrabadiya07" }, { "code": null, "e": 33276, "s": 33261, "text": "amit143katiyar" }, { "code": null, "e": 33289, "s": 33276, "text": "shinjanpatra" }, { "code": null, "e": 33297, "s": 33289, "text": "Strings" }, { "code": null, "e": 33305, "s": 33297, "text": "Strings" }, { "code": null, "e": 33403, "s": 33305, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33412, "s": 33403, "text": "Comments" }, { "code": null, "e": 33425, "s": 33412, "text": "Old Comments" }, { "code": null, "e": 33482, "s": 33425, "text": "Python program to check if a string is palindrome or not" }, { "code": null, "e": 33518, "s": 33482, "text": "Convert string to char array in C++" }, { "code": null, "e": 33556, "s": 33518, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 33609, "s": 33556, "text": "Array of Strings in C++ (5 Different Ways to Create)" }, { "code": null, "e": 33639, "s": 33609, "text": "Caesar Cipher in Cryptography" }, { "code": null, "e": 33671, "s": 33639, "text": "Reverse words in a given string" }, { "code": null, "e": 33732, "s": 33671, "text": "Length of the longest substring without repeating characters" }, { "code": null, "e": 33784, "s": 33732, "text": "Check whether two strings are anagram of each other" }, { "code": null, "e": 33829, "s": 33784, "text": "Top 50 String Coding Problems for Interviews" } ]
Understanding Aircraft Accidents Trends with PyMC3 | by Anirudh Chandra | Towards Data Science
Visually exploring historic airline accidents, applying frequentist interpretations and validating changing trends with PyMC3. On the 7th of August this year, an Air India Express flight on a repatriation mission from Dubai (United Arab Emirates) to Kozhikode (Kerala, India) skidded off the runway under heavy rainfall and fell into a valley [1]. The ensuing 35 foot drop broke the aircraft into two. The flight was ferrying a total of 180 souls and 18 of them lost their lives as an immediate consequence of the accident. The remaining 172 were injured to varying degrees and underwent treatment [2]. The official probe into this horrifying accident will naturally be a fact finding mission and would try to make sense of what went wrong and who’s to blame. Following this story, I started Googling about recent aircraft accidents, to understand the context and to look at these events from a global perspective. This search led me to numerous webpages that had photos and videos of plane crashes, tables of crash statistics, accident investigation reports and sound bites from different aviation industry experts following such catastrophic accidents. The bottom line of this search was that we are in the midst of an increasingly safe flying environment. Regulatory, Design, Mechanical and Electronic safety measures are more stringent than ever before, thus making flying a relatively safer means of transport. But I wanted to play with these numbers myself to validate this conclusion. The motivating question for this exercise was — Has flying become relatively safer in recent times than in the past? I looked at publicly available air crash data on Wikipedia and the National Transportation Safety Board (NTSB) and created a dataset that suited the needs of this exercise. The entire exercise and dataset can be found on my GitHub repository. Switching over to the first person plural....Now. To answer the motivating question, we divide the task into two parts — Exploratory Data Analysis (EDA) in Python.Probabilistic programming (PyMC3) in Python. Exploratory Data Analysis (EDA) in Python. Probabilistic programming (PyMC3) in Python. In this part, we look at the aircraft crashes in the past, which forms our time series for analysis. A few things to remember - The Convention on International Civil Aviation differentiates an aircraft accident from an aircraft incident. The difference is essentially whether fatalities occurred or not.Our focus in this exercise is restricted to the occurrence of the accident, rather than its cause.We look at commercial aircraft accidents from 1975 till 2019. The Convention on International Civil Aviation differentiates an aircraft accident from an aircraft incident. The difference is essentially whether fatalities occurred or not. Our focus in this exercise is restricted to the occurrence of the accident, rather than its cause. We look at commercial aircraft accidents from 1975 till 2019. Looking at the historic time series, we visually sense a decline in number of accidents per year from 1978 onwards. There appears to be a minor rise in number of accidents between 1987 and 1989, after which the numbers steadily decrease. The lowest number of accidents was observed in 2017, which is considered the safest year in aviation history. After 2017, the numbers seem to increase marginally. Another clear trend observable is the drop in the number of fatalities over time. The 1970s and 80s were dangerous times to fly, with aircraft accidents, on an average, causing nearly 2200 fatalities a year. But over time we see that this number has dramatically reduced. When this declining trend is looked at in the context of rising number of air travellers (green shaded region in Fig. 1), we get a better picture of airline safety. When the declining number of fatalities are looked at from the perspective of rising number of air travellers, we get a clearly declining trend. The number of fatalities per million passengers travelling by air every year, has dropped drastically from 5 in a million to less than 1 in a million. (Disclaimer: Bayesians, keep that pinch of salt ready) Another measure of aircraft safety is the number of fatalities per accident. Although there may be a number of exogenous factors (external factors) that influence the number of fatalities in a given accident — weather, nature of crash, time of day etc. — we still look at this measure as a rough estimate of aircraft safety. There seems to be a slight decrease in trend beyond 1995 but it is not immediately observable from the graph. We also see that 1985, 1996, 2014 and 2018 were fatal years involving major crashes, because the average number of fatalities per crash is large. A final piece of evidence, before we begin the probabilistic testing of the motivating question, is the yearly rate of change of accidents. If we are truly living in safe times, then we expect the graph to show a series of successively increasing green bars. Such a window was observed only in 1979–80, 1980–84, 1999–00, 2006–07 and 2013–14. Extended periods of relatively safe travel can be seen from 1980–84 and 1996–2000. If we look at the rate of change beyond 1995, we see that there has largely been a decline in year-on-year accidents (very few red bars and more of green bars). It appears that some external factor (like change in aircraft design, civil aviation regulations, better ATC technology etc.) may have caused this decline beyond 1995. From our data exploration we saw that there is a continued decline in number of aircraft accidents every decade and we validated this trend with a couple of statistical measures. We also saw that 1995 was, presumably, a turning point for the aviation industry. How can we validate this assumption? One interesting technique to do so, with the limited data and non-repeatability of events (Let us assume that we can’t simulate these accidents a million times) is the use of probabilistic techniques like Markov Chain Monte Carlo (MCMC). And one of the ways of implementing these techniques is by means of the PyMC3 library in Python. PyMC3 is a library in Python that helps us carry out probabilistic programming. This does not mean that the programming is probabilistic (it is still a very much deterministic process!), but instead, we employ probability distributions and Bayesian methods. This technique is built on top of a Bayesian outlook of the world. We start with a belief (called prior probability)about a certain process or a parameter and we update this belief (called posterior probability) after several thousand runs (a.k.a random sampling). This method is opposite to that of the frequentist way of looking at things (like we did in the EDA). The second foundation for this process is the random sampling methods of Markov Chain Monte Carlo (MCMC). This is a set of algorithms that allows us to sample from the prior probability distributions and generate data to test our prior beliefs and update them. The documentation provided on the PyMC3 webpage and this hands on approach by Susan Li are excellent for a high-level understanding of the library and the techniques. The book Bayesian Methods for Hackers, by Cam Davidson-Pilon is really helpful if you are thinking of getting your hands dirty. We begin by establishing our prior beliefs about the accidents — What kind of distribution do aircraft accidents follow? Here we assume that the accidents follow a Poisson Distribution. P(x|lambda) = (lambda^x)*(exp^-lambda)/(lambda!)x: number of accidentslambda: rate of occurrence of the accident What would be the rate of occurrence? Given our initial assumption, we further presume that this rate of occurrence can be roughly the reciprocal of the average occurrences for the whole dataset. In other words, lambda = 1/(mean of number of accidents from 1975 to 2019) What would be the initial turning point? The turning point is that year before which the rate of occurrence was high and after which, it became low. We initially assume that every year from 1975 to 2019 has an equal probability (drawn from a discrete uniform distribution) of being considered as a turning point. With these set of prior beliefs, we instantiate the model — import pymc3 as pmimport arviz as azyears = np.arange(1975, 2020)with pm.Model() as accident_model: alpha = 1/df.loc[df.year>=1975].num_crashes.mean() # Setting the prior belief for the inflection point change_point = pm.DiscreteUniform( 'change_point', lower=1975, upper=2020) # Setting prior belief for the rate of occurrence, ie, lambda, before and after inflection rate_before = pm.Exponential('before_change', alpha) rate_after = pm.Exponential('after_change', alpha) # Allocate appropriate Poisson rates to years before and after current rate = pm.math.switch(change_point >= years, rate_before, rate_after)accidents = pm.Poisson("accidents", rate, observed=df.loc[df.year>=1975].num_crashes) And we sample these distributions using the No-U-Turn Sampler (NUTS) at least 10,000 times — with accident_model: trace = pm.sample(10000, return_inferencedata=False) We see that after sampling 10,000 times our initial belief that all years have an equal chance of being considered a turning point was updated. The result indicates that 1997 (and not 1995) is the most likely candidate for being considered a turning point in aviation accident history. And the initial assumption that the rate of occurrences would be the reciprocal of the 45 year average has been updated. 1997 was considered the turning point because the rate of occurrences of accident changed from about 300 per year to 165 per year! So how sure are these predictions? The USP of probabilistic programming is that predictions are made with a pinch of salt! Unlike a frequentist prediction, the predictions from the Bayesian methods come with uncertainties attached (which is more realistic). Our model shows that the 94% High Density Interval (HDI) is between 1996 and 1999, with 1997 being the mean. In other words, 1997 has a higher probability of being the turning point. Similar 94% HDI for the rate of occurrences before this turning point is between 295 to 312 accidents per year; and for accidents after 1997 it is between 158 and 172 accidents per year. Since our motivating question was restricted to ‘recent times’, we apply this model to data from 2000 to 2019 (assuming the last 20 years to be recent enough). We observe that 2012 is a strong candidate for a turning point (with the 94% HDI being 2010 to 2013), with the rate of accidents being nearly 180 per year before 2012 and about 120 per year after 2012. So by carrying out this small exercise, I was able to satisfy my curiosity and answer the motivating question — If low rates of aviation accidents per year are the sole indicators of aviation safety, then after 1997, the rates have significantly reduced and in the last 20 years the numbers have dropped further beyond 2012. Despite the low number of accidents every year, it is relatively safer to fly right now than it was 20 years ago.
[ { "code": null, "e": 174, "s": 47, "text": "Visually exploring historic airline accidents, applying frequentist interpretations and validating changing trends with PyMC3." }, { "code": null, "e": 395, "s": 174, "text": "On the 7th of August this year, an Air India Express flight on a repatriation mission from Dubai (United Arab Emirates) to Kozhikode (Kerala, India) skidded off the runway under heavy rainfall and fell into a valley [1]." }, { "code": null, "e": 650, "s": 395, "text": "The ensuing 35 foot drop broke the aircraft into two. The flight was ferrying a total of 180 souls and 18 of them lost their lives as an immediate consequence of the accident. The remaining 172 were injured to varying degrees and underwent treatment [2]." }, { "code": null, "e": 807, "s": 650, "text": "The official probe into this horrifying accident will naturally be a fact finding mission and would try to make sense of what went wrong and who’s to blame." }, { "code": null, "e": 962, "s": 807, "text": "Following this story, I started Googling about recent aircraft accidents, to understand the context and to look at these events from a global perspective." }, { "code": null, "e": 1202, "s": 962, "text": "This search led me to numerous webpages that had photos and videos of plane crashes, tables of crash statistics, accident investigation reports and sound bites from different aviation industry experts following such catastrophic accidents." }, { "code": null, "e": 1463, "s": 1202, "text": "The bottom line of this search was that we are in the midst of an increasingly safe flying environment. Regulatory, Design, Mechanical and Electronic safety measures are more stringent than ever before, thus making flying a relatively safer means of transport." }, { "code": null, "e": 1539, "s": 1463, "text": "But I wanted to play with these numbers myself to validate this conclusion." }, { "code": null, "e": 1587, "s": 1539, "text": "The motivating question for this exercise was —" }, { "code": null, "e": 1656, "s": 1587, "text": "Has flying become relatively safer in recent times than in the past?" }, { "code": null, "e": 1829, "s": 1656, "text": "I looked at publicly available air crash data on Wikipedia and the National Transportation Safety Board (NTSB) and created a dataset that suited the needs of this exercise." }, { "code": null, "e": 1899, "s": 1829, "text": "The entire exercise and dataset can be found on my GitHub repository." }, { "code": null, "e": 1949, "s": 1899, "text": "Switching over to the first person plural....Now." }, { "code": null, "e": 2020, "s": 1949, "text": "To answer the motivating question, we divide the task into two parts —" }, { "code": null, "e": 2107, "s": 2020, "text": "Exploratory Data Analysis (EDA) in Python.Probabilistic programming (PyMC3) in Python." }, { "code": null, "e": 2150, "s": 2107, "text": "Exploratory Data Analysis (EDA) in Python." }, { "code": null, "e": 2195, "s": 2150, "text": "Probabilistic programming (PyMC3) in Python." }, { "code": null, "e": 2323, "s": 2195, "text": "In this part, we look at the aircraft crashes in the past, which forms our time series for analysis. A few things to remember -" }, { "code": null, "e": 2658, "s": 2323, "text": "The Convention on International Civil Aviation differentiates an aircraft accident from an aircraft incident. The difference is essentially whether fatalities occurred or not.Our focus in this exercise is restricted to the occurrence of the accident, rather than its cause.We look at commercial aircraft accidents from 1975 till 2019." }, { "code": null, "e": 2834, "s": 2658, "text": "The Convention on International Civil Aviation differentiates an aircraft accident from an aircraft incident. The difference is essentially whether fatalities occurred or not." }, { "code": null, "e": 2933, "s": 2834, "text": "Our focus in this exercise is restricted to the occurrence of the accident, rather than its cause." }, { "code": null, "e": 2995, "s": 2933, "text": "We look at commercial aircraft accidents from 1975 till 2019." }, { "code": null, "e": 3396, "s": 2995, "text": "Looking at the historic time series, we visually sense a decline in number of accidents per year from 1978 onwards. There appears to be a minor rise in number of accidents between 1987 and 1989, after which the numbers steadily decrease. The lowest number of accidents was observed in 2017, which is considered the safest year in aviation history. After 2017, the numbers seem to increase marginally." }, { "code": null, "e": 3668, "s": 3396, "text": "Another clear trend observable is the drop in the number of fatalities over time. The 1970s and 80s were dangerous times to fly, with aircraft accidents, on an average, causing nearly 2200 fatalities a year. But over time we see that this number has dramatically reduced." }, { "code": null, "e": 3833, "s": 3668, "text": "When this declining trend is looked at in the context of rising number of air travellers (green shaded region in Fig. 1), we get a better picture of airline safety." }, { "code": null, "e": 4129, "s": 3833, "text": "When the declining number of fatalities are looked at from the perspective of rising number of air travellers, we get a clearly declining trend. The number of fatalities per million passengers travelling by air every year, has dropped drastically from 5 in a million to less than 1 in a million." }, { "code": null, "e": 4184, "s": 4129, "text": "(Disclaimer: Bayesians, keep that pinch of salt ready)" }, { "code": null, "e": 4509, "s": 4184, "text": "Another measure of aircraft safety is the number of fatalities per accident. Although there may be a number of exogenous factors (external factors) that influence the number of fatalities in a given accident — weather, nature of crash, time of day etc. — we still look at this measure as a rough estimate of aircraft safety." }, { "code": null, "e": 4765, "s": 4509, "text": "There seems to be a slight decrease in trend beyond 1995 but it is not immediately observable from the graph. We also see that 1985, 1996, 2014 and 2018 were fatal years involving major crashes, because the average number of fatalities per crash is large." }, { "code": null, "e": 4905, "s": 4765, "text": "A final piece of evidence, before we begin the probabilistic testing of the motivating question, is the yearly rate of change of accidents." }, { "code": null, "e": 5190, "s": 4905, "text": "If we are truly living in safe times, then we expect the graph to show a series of successively increasing green bars. Such a window was observed only in 1979–80, 1980–84, 1999–00, 2006–07 and 2013–14. Extended periods of relatively safe travel can be seen from 1980–84 and 1996–2000." }, { "code": null, "e": 5351, "s": 5190, "text": "If we look at the rate of change beyond 1995, we see that there has largely been a decline in year-on-year accidents (very few red bars and more of green bars)." }, { "code": null, "e": 5519, "s": 5351, "text": "It appears that some external factor (like change in aircraft design, civil aviation regulations, better ATC technology etc.) may have caused this decline beyond 1995." }, { "code": null, "e": 5698, "s": 5519, "text": "From our data exploration we saw that there is a continued decline in number of aircraft accidents every decade and we validated this trend with a couple of statistical measures." }, { "code": null, "e": 5817, "s": 5698, "text": "We also saw that 1995 was, presumably, a turning point for the aviation industry. How can we validate this assumption?" }, { "code": null, "e": 6055, "s": 5817, "text": "One interesting technique to do so, with the limited data and non-repeatability of events (Let us assume that we can’t simulate these accidents a million times) is the use of probabilistic techniques like Markov Chain Monte Carlo (MCMC)." }, { "code": null, "e": 6152, "s": 6055, "text": "And one of the ways of implementing these techniques is by means of the PyMC3 library in Python." }, { "code": null, "e": 6410, "s": 6152, "text": "PyMC3 is a library in Python that helps us carry out probabilistic programming. This does not mean that the programming is probabilistic (it is still a very much deterministic process!), but instead, we employ probability distributions and Bayesian methods." }, { "code": null, "e": 6777, "s": 6410, "text": "This technique is built on top of a Bayesian outlook of the world. We start with a belief (called prior probability)about a certain process or a parameter and we update this belief (called posterior probability) after several thousand runs (a.k.a random sampling). This method is opposite to that of the frequentist way of looking at things (like we did in the EDA)." }, { "code": null, "e": 7038, "s": 6777, "text": "The second foundation for this process is the random sampling methods of Markov Chain Monte Carlo (MCMC). This is a set of algorithms that allows us to sample from the prior probability distributions and generate data to test our prior beliefs and update them." }, { "code": null, "e": 7333, "s": 7038, "text": "The documentation provided on the PyMC3 webpage and this hands on approach by Susan Li are excellent for a high-level understanding of the library and the techniques. The book Bayesian Methods for Hackers, by Cam Davidson-Pilon is really helpful if you are thinking of getting your hands dirty." }, { "code": null, "e": 7398, "s": 7333, "text": "We begin by establishing our prior beliefs about the accidents —" }, { "code": null, "e": 7454, "s": 7398, "text": "What kind of distribution do aircraft accidents follow?" }, { "code": null, "e": 7519, "s": 7454, "text": "Here we assume that the accidents follow a Poisson Distribution." }, { "code": null, "e": 7632, "s": 7519, "text": "P(x|lambda) = (lambda^x)*(exp^-lambda)/(lambda!)x: number of accidentslambda: rate of occurrence of the accident" }, { "code": null, "e": 7670, "s": 7632, "text": "What would be the rate of occurrence?" }, { "code": null, "e": 7828, "s": 7670, "text": "Given our initial assumption, we further presume that this rate of occurrence can be roughly the reciprocal of the average occurrences for the whole dataset." }, { "code": null, "e": 7844, "s": 7828, "text": "In other words," }, { "code": null, "e": 7903, "s": 7844, "text": "lambda = 1/(mean of number of accidents from 1975 to 2019)" }, { "code": null, "e": 7944, "s": 7903, "text": "What would be the initial turning point?" }, { "code": null, "e": 8216, "s": 7944, "text": "The turning point is that year before which the rate of occurrence was high and after which, it became low. We initially assume that every year from 1975 to 2019 has an equal probability (drawn from a discrete uniform distribution) of being considered as a turning point." }, { "code": null, "e": 8276, "s": 8216, "text": "With these set of prior beliefs, we instantiate the model —" }, { "code": null, "e": 9030, "s": 8276, "text": "import pymc3 as pmimport arviz as azyears = np.arange(1975, 2020)with pm.Model() as accident_model: alpha = 1/df.loc[df.year>=1975].num_crashes.mean() # Setting the prior belief for the inflection point change_point = pm.DiscreteUniform( 'change_point', lower=1975, upper=2020) # Setting prior belief for the rate of occurrence, ie, lambda, before and after inflection rate_before = pm.Exponential('before_change', alpha) rate_after = pm.Exponential('after_change', alpha) # Allocate appropriate Poisson rates to years before and after current rate = pm.math.switch(change_point >= years, rate_before, rate_after)accidents = pm.Poisson(\"accidents\", rate, observed=df.loc[df.year>=1975].num_crashes)" }, { "code": null, "e": 9123, "s": 9030, "text": "And we sample these distributions using the No-U-Turn Sampler (NUTS) at least 10,000 times —" }, { "code": null, "e": 9200, "s": 9123, "text": "with accident_model: trace = pm.sample(10000, return_inferencedata=False)" }, { "code": null, "e": 9486, "s": 9200, "text": "We see that after sampling 10,000 times our initial belief that all years have an equal chance of being considered a turning point was updated. The result indicates that 1997 (and not 1995) is the most likely candidate for being considered a turning point in aviation accident history." }, { "code": null, "e": 9738, "s": 9486, "text": "And the initial assumption that the rate of occurrences would be the reciprocal of the 45 year average has been updated. 1997 was considered the turning point because the rate of occurrences of accident changed from about 300 per year to 165 per year!" }, { "code": null, "e": 9773, "s": 9738, "text": "So how sure are these predictions?" }, { "code": null, "e": 9996, "s": 9773, "text": "The USP of probabilistic programming is that predictions are made with a pinch of salt! Unlike a frequentist prediction, the predictions from the Bayesian methods come with uncertainties attached (which is more realistic)." }, { "code": null, "e": 10179, "s": 9996, "text": "Our model shows that the 94% High Density Interval (HDI) is between 1996 and 1999, with 1997 being the mean. In other words, 1997 has a higher probability of being the turning point." }, { "code": null, "e": 10366, "s": 10179, "text": "Similar 94% HDI for the rate of occurrences before this turning point is between 295 to 312 accidents per year; and for accidents after 1997 it is between 158 and 172 accidents per year." }, { "code": null, "e": 10526, "s": 10366, "text": "Since our motivating question was restricted to ‘recent times’, we apply this model to data from 2000 to 2019 (assuming the last 20 years to be recent enough)." }, { "code": null, "e": 10728, "s": 10526, "text": "We observe that 2012 is a strong candidate for a turning point (with the 94% HDI being 2010 to 2013), with the rate of accidents being nearly 180 per year before 2012 and about 120 per year after 2012." }, { "code": null, "e": 10840, "s": 10728, "text": "So by carrying out this small exercise, I was able to satisfy my curiosity and answer the motivating question —" }, { "code": null, "e": 11053, "s": 10840, "text": "If low rates of aviation accidents per year are the sole indicators of aviation safety, then after 1997, the rates have significantly reduced and in the last 20 years the numbers have dropped further beyond 2012." } ]
What does .shape[] do in “for i in range(Y.shape[0])” using Matplotlib?
The shape property is usually used to get the current shape of an array, but it may also be used to reshape the array in-place by assigning a tuple of array dimensions to it. Get an array Y using np.array method. Get an array Y using np.array method. Y.shape would return a tuple (4, ). Y.shape would return a tuple (4, ). Y.shape[0] method would return 4, i.e., the first element of the tuple. Y.shape[0] method would return 4, i.e., the first element of the tuple. import numpy as np Y = np.array([1, 2, 3, 4]) print("Output of .show method would be: ", Y.shape, " for ", Y) print("Output of .show[0] method would be: ", Y.shape[0], " for ", Y) print("Output for i in range(Y.shape[0]): ", end=" ") for i in range(Y.shape[0]): print(Y[i], end=" ") Output of .show method would be: (4,) for [1 2 3 4] Output of .show[0] method would be: 4 for [1 2 3 4] Output for i in range(Y.shape[0]): 1 2 3 4
[ { "code": null, "e": 1237, "s": 1062, "text": "The shape property is usually used to get the current shape of an array, but it may also be used to reshape the array in-place by assigning a tuple of array dimensions to it." }, { "code": null, "e": 1275, "s": 1237, "text": "Get an array Y using np.array method." }, { "code": null, "e": 1313, "s": 1275, "text": "Get an array Y using np.array method." }, { "code": null, "e": 1349, "s": 1313, "text": "Y.shape would return a tuple (4, )." }, { "code": null, "e": 1385, "s": 1349, "text": "Y.shape would return a tuple (4, )." }, { "code": null, "e": 1457, "s": 1385, "text": "Y.shape[0] method would return 4, i.e., the first element of the tuple." }, { "code": null, "e": 1529, "s": 1457, "text": "Y.shape[0] method would return 4, i.e., the first element of the tuple." }, { "code": null, "e": 1816, "s": 1529, "text": "import numpy as np\n\nY = np.array([1, 2, 3, 4])\nprint(\"Output of .show method would be: \", Y.shape, \" for \", Y)\nprint(\"Output of .show[0] method would be: \", Y.shape[0], \" for \", Y)\nprint(\"Output for i in range(Y.shape[0]): \", end=\" \")\nfor i in range(Y.shape[0]):\n print(Y[i], end=\" \")" }, { "code": null, "e": 1963, "s": 1816, "text": "Output of .show method would be: (4,) for [1 2 3 4]\nOutput of .show[0] method would be: 4 for [1 2 3 4]\nOutput for i in range(Y.shape[0]): 1 2 3 4" } ]
Detailed Guide to Multiple Linear Regression Model, Assessment, and Inference in R | by Rashida Nasrin Sucky | Towards Data Science
Linear regression is one of those old-school statistical modeling approaches that are still popular. With the development of new languages and libraries, it is now in a much-improved version and much easier to work on. Multiple linear regression is an extension of simple linear regression. In simple linear regression, we worked on the relationship between one independent variable or explanatory variable and one dependent variable or response variable. Simple linear regression uses this very common general formula: y = mx + c where, y = dependent variable or response variable x = independent variable or explanatory variable m = slope c = intercept If x and y share a linear relationship, you can predict ‘y’ if you have the ‘x’ data available. In statistics, beta0 and beta1 are used instead of c and m. So, the formula becomes: This equation is good enough when you are establishing a relationship between profit and sales, arm length and leg lengths, systolic blood pressure and diastolic blood pressure, etc. That means when there is only one explanatory variable and one response variable. But in the real world scenario, we often want to analyze the relationship between one response variable and several explanatory variables. When the response variable is exam score, there might be several explanatory variables such as study time, attendance in school, playtime, and sleep hours. We want to analyze the relationship between all the possible explanatory variables with the response variable(exam score). In this case, the equation of the linear regression becomes: Equation 1 If we think of the exam score in the example mentioned before, y is the exam score. x1, x2, and x3 are the study time, attendance at school, playtime. We need to determine the values of beta0, beta1, beta2, beta3 ..... Calculating the values of betas are very easy and straightforward in R. Let’s work on an example. For this demonstration, we will use a dataset that contains age, weight, body mass index(BMI), and systolic blood pressure. We will consider systolic blood pressure as the dependent variable and weight, BMI, and age as the independent or explanatory variables. I will start with age as the only explanatory variable in the beginning. Then add weight and BMI later one by one to understand the effect of each one of them on the model and on the response variable(systolic blood pressure). Please feel free to download the dataset and follow along, if you want to practice: github.com Let’s import the dataset first. data = read.csv("health_data.csv")head(data) As we will examine the relationship between age and systolic blood pressure first, it will be interesting to see a scatter plot of age and systolic blood pressure. Here is the scatter plot: plot(data$Age, data$Systolic_blood_pressure, main= "Systolic Blood Pressure vs Age", xlab = "Age", ylab = "Systolic Blood Pressure") It shows a linear trend. Though a lot of noise around. In R, we can directly find the linear regression model using the ‘lm’ function. I will save this model in a variable ‘m’. m = lm(data$Systolic_blood_pressure ~ data$Age)m Output: Call:lm(formula = data$Systolic_blood_pressure ~ data$Age)Coefficients:(Intercept) data$Age 94.872 0.635 The output shows that the intercept(beta0) is 94.872 and the slope is 0.635(beta1). We considered x1 as age. So the linear regression equation becomes: y = 94.872 + 0.635*Age As we considered only one explanatory variable, no x2, x3, or beta2, beta3. Here, intercept 94.872 means that if the age is zero or very close to zero systolic blood pressure will still be 94.872. In this dataset, the minimum age in the dataset is 18(feel free to check on your own). So, talking about zero age is far out of the range of this dataset. That’s why it is not so reasonable in this case. The slope of 0.635 means that if the age increases by 1 unit the systolic blood pressure will increase by 0.635 unit on average. Using this equation you can calculate the systolic blood pressure of a person’s age if you know the age. For example, if a person is 32 years old, the calculated systolic blood pressure will be: y = 94.872 + 0.635*32 = 115.192 Now, how correct this estimate is, we will determine that later in this article. This is time to add one more variable. Add weight to the model: This is pretty simple. In the model ‘m’, we considered only one explanatory variable ‘Age’. This time we will have two explanatory variables: Age and Weight. It can be done using the same ‘lm’ function and I will save this model in a variable ‘m1’. m1 = lm(data$Systolic_blood_pressure ~ data$Age + data$Weight)m1 Output: Call:lm(formula = data$Systolic_blood_pressure ~ data$Age + data$Weight)Coefficients:(Intercept) data$Age data$Weight 84.2799 0.6300 0.1386 Here, intercept(beta0) is 84.28. If you notice it is different than the intercept in ‘m’(94.87). This time slope(beta1) for Age variable becomes 0.63 which is not so different than the beta1 in model ‘m’. This slope means if Age increases by 1 unit systolic blood pressure will increase by 0.63 unit on average when the Weight variable is controlled or fixed. On the other hand, the slope for the Weight variable(beta2) is 0.1386 means that if weight increases by 1 unit, systolic blood pressure will increase by 0.1386 unit on average when the Age variable is controlled or fixed. The linear regression equation becomes: y = 84.2799 + 0.63* Age + 0.1386 * Weight If you know a person’s Age and Weight you will be able to estimate that person’s systolic blood pressure using this formula. Adding BMI to this Model Lastly, we add BMI to this model to see if BMI changes the dynamic of this model. Let’s use the ‘lm’ function again and save this model in a variable named ‘m2’. m2 = lm(data$Systolic_blood_pressure ~ data$Age + data$Weight+data$BMI)m2 Output: Call:lm(formula = data$Systolic_blood_pressure ~ data$Age + data$Weight + data$BMI)Coefficients:(Intercept) data$Age data$Weight data$BMI 89.5218 0.6480 0.3209 -0.7244 Notice the output carefully. The intercept changed again. It is 89.52 this time. The slope for Age is 0.648 now. It was 0.63 in the previous model. The slope for weight is 0.3209 while it was 0.1386 in the previous model. So, After adding the BMI in the model the value beta0, beta1 and beta2 changed pretty significantly. The slope of the BMI variable is -0.7244. The linear regression equation becomes: y = 89.5218 + 0.648*Age + 0.3209*Weight — 0.7244*BMI Woo! Our multiple linear regression model is ready! Now if we know the age, weight, and BMI of a person, we will be able to calculate the systolic blood pressure of that person! How accurate that systolic blood pressure calculation from this equation is? Let’s find out. One very common and popular way to assess the fit of the data in multiple linear regression is the coefficient of variation (R-squared). The formula for R-squared is the same as the simple linear regression: Here, y_calc is the calculated value of the response variable. In this case, the values of systolic blood pressure that are calculated using the linear regression model y_mean is the mean of original systolic blood pressure values y is the original systolic blood pressures from the dataset The R-squared value represents the proportion of the response variable that can be explained by the explanatory variables. I will use R to calculate R-squared. It is very simple in R. We have three models, and we saved them in three different variables m, m1, and m2. It will be good to see the fit of each model. I will calculate the R-squared value for all three models. Here is the R-squared value for the first model ‘m’ where the explanatory variable was only the ‘Age’. R_squared1 = sum((fitted(m) - mean(data$Systolic_blood_pressure))**2) / sum((data$Systolic_blood_pressure - mean(data$Systolic_blood_pressure))**2)R_squared1 Output: 0.3795497 That means 37.95% of the systolic blood pressure can be explained by Age. The R-squared value for the second model ‘m1’ where explanatory variables were ‘Age’ and ‘Weight’: R_squared2 = sum((fitted(m1) - mean(data$Systolic_blood_pressure))**2) / sum((data$Systolic_blood_pressure - mean(data$Systolic_blood_pressure))**2)R_squared2 Output: 0.3958562 39.58% of the systolic blood pressure can be explained by ‘Age’ and ‘Weight’ together. Look R-squared improved a bit after adding the Weight to the model. Lastly, the R-squared value for the model m2 where the explanatory variables were ‘Age’, ‘Weight’, and ‘BMI’. R_squared3 = sum((fitted(m2) - mean(data$Systolic_blood_pressure))**2) / sum((data$Systolic_blood_pressure - mean(data$Systolic_blood_pressure))**2)R_squared3 Output: 0.4099555 40.99% of the systolic blood pressure can be explained by the ‘Age’, ‘Weight’, and ‘BMI’. The next steps might be a bit hard for you to understand totally if you are not familiar with confidence intervals or hypothesis test concepts. Here is an article to learn confidence interval concepts: towardsdatascience.com Here is an article on the hypothesis tests. Please check: towardsdatascience.com Inference In this section, we will work on an F-test to see if the model was significant. That means if at least one of the explanatory variables has a linear association with the response variable. There is a five-step process to perform this hypothesis test: step 1: Set the hypothesis and select the alpha level: We set a null hypothesis and an alternative hypothesis. The null hypothesis is that the slope of all the variables is zeros. That means there is no association between any of the variables and the response variable. Here is the null hypothesis: If we do not find enough evidence that the null hypothesis is true then we will reject the null hypothesis. That will give us the evidence that at least one of the slopes not equal to zero. That means at least one of the explanatory variables has a linear association with the response variable. This is the alternative hypothesis: I am setting the alpha level as 0.05. That means the confidence level is 95%. Step 2: Select the appropriate test statistic. Here we will use F-test. The test statistic is: Here, df is the degrees of freedom. That is the number of explanatory variables. In this example that is 3 (Age, Weight, and BMI). n is the number of rows or the number of data points. In this dataset, there are 100 rows. So, n = 100. Feel free to check it using the ‘nrows(data)’ function We will discuss how to calculate the F-stat in a little bit. Step 3: State the decision rule: We need to determine the appropriate value from the F-distribution with df = 3, n-k-1 = 100–3- 1 = 96, and the alpha = 0.05. There are 2 ways to find the appropriate value. You can use the F distribution table. But I prefer using R. So, here is the value from the F-distribution calculated in R: qf(0.95, 3, 96) Output: [1] 2.699393 The appropriate value from F-distribution is 2.699. The decision rule is: Reject the null hypothesis if F ≥ 2.699 Otherwise, do not reject the null hypothesis. Step 4: Compute the F-Statistic. Here is the table that calculates the F-statistic. Here in the table above, The Reg SS is the regression sum of squares that can be calculated with this formula The Res SS is the residual sum of squares and here is the expression to calculate it: Total SS can also be calculated as the sum of ‘Reg SS’ and ‘Res SS’. The following expression will also give you the same result as the sum of Reg SS and Res SS. Reg df or the regression degrees of freedom is the number of explanatory variables. In this example that is 3. n is the number of rows of the data. I will use R to calculate Reg SS, Res SS, and n: regSS = sum((fitted(m2) - mean(data$Systolic_blood_pressure))**2)resSS = sum((data$Systolic_blood_pressure - mean(data$Systolic_blood_pressure))**2) Output: [1] 16050.88[1] 39091.84 Finding the number of rows in the data: nrow(data) Output: [1] 100 The rest of the elements in the table can be calculated now. I used an excel sheet to generate the table. Though it is possible to find everything in R. But to make it in a table format I used excel. Here are the results: The F-statistic is 13.139. Feel free to download this excel file here: github.com Step 5: Conclusion: F is 13.139 which is greater than 2.699. So, we have enough evidence to reject the null hypothesis. That means At least one of the explanatory variables has a linear association with the response variable. So, the model is significant. From the F-test, we came to know that the model is significant. That means at least one of the explanatory variables has a linear association with the response variable. It will be helpful to know exactly which variable or variables have a linear association with the response variable(systolic blood pressure). We will perform a t-test for that. t-test for individual explanatory variables The F-test above shows that the model is significant. Now, we can test for each of the explanatory variables that if each of them has a linear association. As we already state five-step rule before. I will not go through the whole thing here. Step 1: The hypothesis and the alpha are exactly the same as the F-test above. Step 2: In step 2, the test statistic will be the t-statistic with the degrees of freedom of n -k-1. We will use R to find the t-statistic in step 4 later. Step 3: In step 3, we need to find the appropriate value from the t-distribution this time. There is a ‘t-distribution’ table to find out the appropriate value. I prefer to use R. qt(0.975, 96) Output: [1] 1.984984 If the t-statistic for any explanatory variable is greater than or equal to 1.985, reject the null hypothesis. Otherwise do not reject the null hypothesis. Step 4: Compute the test statistic: This is what makes a t-test that easy. If you just take a summary of your linear regression model in R that gives you the t-statistic and also the p-value. I will take the summary of the model ‘m2’ because we included all three explanatory variables in that model. summary(m2) Output: Call:lm(formula = data$Systolic_blood_pressure ~ data$Age + data$Weight + data$BMI)Residuals: Min 1Q Median 3Q Max -33.218 -10.572 -0.187 8.171 47.071Coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) 90.14758 8.34933 10.797 < 2e-16 ***data$Age 0.64315 0.08109 7.931 3.97e-12 ***data$Weight 0.32226 0.14753 2.184 0.0314 * data$BMI -0.73980 0.47751 -1.549 0.1246 ---Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1Residual standard error: 15.49 on 96 degrees of freedomMultiple R-squared: 0.4106, Adjusted R-squared: 0.3922 F-statistic: 22.29 on 3 and 96 DF, p-value: 4.89e-11 Look at the output carefully. There are t-statistic for each of the explanatory variables here. Also the p-values for each of them. Step 5: Here is the conclusion from the test: As per our decision rule, we should reject the null hypothesis if the t-statistic is greater than or equal to 1.985. You can see that for Age and Weight variable t-statistic is greater than 1.985. So, we can reject the null hypothesis for both of them. Let’s talk about each of them one by one. As per the t-test, Age variable is significant and has a linear association with the systolic blood pressure when Weight and BMI are controlled. In the same way Weight variable is also significant and has a linear association with the systolic blood pressure when Age and BMI are controlled. On the other hand, the t-statistic for the BMI variable is -1.549 which is smaller than 1.985. So, we do not have enough evidence to reject the null hypothesis for the BMI variable. That means the BMI variable does not have a linear association with the systolic blood pressure when Age and Weight are controlled. You can also use the p-value to draw a conclusion. If the p-value is greater than or equal to the alpha level (in this example 0.05), we have enough evidence to reject the null hypothesis. If you notice in the summary output above, for the Age and Weight variable, the p-value is less than the alpha level 0.05. So, this way also we can conclude that Age and Weight variables have a linear association with systolic blood pressure. On the other hand, the p-value for BMI is greater than 0.05. Using p-value also you can determine that the BMI variable does not have a linear association with the systolic blood pressure. If you read my article on simple linear regression, you may be wondering why I did not use ANOVA for the inference part here. Using ANOVA in multiple linear regression is not a good idea. Because it gives you different results if you put the response variable in a different order. It becomes very confusing. Try using the ‘anova()’ function in R with ‘Age’, Weight, BMI once. And Weight, Age, BMI once. You might get a different ANOVA table. I hope this was helpful. This is a lot of material covered in this article. If all this material is totally new to you it may take some time to really grasp all these ideas. These are not the only tests. There are several other tests in statistics. These are just some common and popular hypothesis tests. I suggest, take a dataset of your own and try developing a linear regression model and running hypothesis tests like this article. If you read this for learning, that’s the only way to learn. Feel free to follow me on Twitter and like my Facebook page.
[ { "code": null, "e": 391, "s": 172, "text": "Linear regression is one of those old-school statistical modeling approaches that are still popular. With the development of new languages and libraries, it is now in a much-improved version and much easier to work on." }, { "code": null, "e": 692, "s": 391, "text": "Multiple linear regression is an extension of simple linear regression. In simple linear regression, we worked on the relationship between one independent variable or explanatory variable and one dependent variable or response variable. Simple linear regression uses this very common general formula:" }, { "code": null, "e": 703, "s": 692, "text": "y = mx + c" }, { "code": null, "e": 710, "s": 703, "text": "where," }, { "code": null, "e": 754, "s": 710, "text": "y = dependent variable or response variable" }, { "code": null, "e": 803, "s": 754, "text": "x = independent variable or explanatory variable" }, { "code": null, "e": 813, "s": 803, "text": "m = slope" }, { "code": null, "e": 827, "s": 813, "text": "c = intercept" }, { "code": null, "e": 923, "s": 827, "text": "If x and y share a linear relationship, you can predict ‘y’ if you have the ‘x’ data available." }, { "code": null, "e": 1008, "s": 923, "text": "In statistics, beta0 and beta1 are used instead of c and m. So, the formula becomes:" }, { "code": null, "e": 1273, "s": 1008, "text": "This equation is good enough when you are establishing a relationship between profit and sales, arm length and leg lengths, systolic blood pressure and diastolic blood pressure, etc. That means when there is only one explanatory variable and one response variable." }, { "code": null, "e": 1691, "s": 1273, "text": "But in the real world scenario, we often want to analyze the relationship between one response variable and several explanatory variables. When the response variable is exam score, there might be several explanatory variables such as study time, attendance in school, playtime, and sleep hours. We want to analyze the relationship between all the possible explanatory variables with the response variable(exam score)." }, { "code": null, "e": 1752, "s": 1691, "text": "In this case, the equation of the linear regression becomes:" }, { "code": null, "e": 1763, "s": 1752, "text": "Equation 1" }, { "code": null, "e": 1982, "s": 1763, "text": "If we think of the exam score in the example mentioned before, y is the exam score. x1, x2, and x3 are the study time, attendance at school, playtime. We need to determine the values of beta0, beta1, beta2, beta3 ....." }, { "code": null, "e": 2080, "s": 1982, "text": "Calculating the values of betas are very easy and straightforward in R. Let’s work on an example." }, { "code": null, "e": 2568, "s": 2080, "text": "For this demonstration, we will use a dataset that contains age, weight, body mass index(BMI), and systolic blood pressure. We will consider systolic blood pressure as the dependent variable and weight, BMI, and age as the independent or explanatory variables. I will start with age as the only explanatory variable in the beginning. Then add weight and BMI later one by one to understand the effect of each one of them on the model and on the response variable(systolic blood pressure)." }, { "code": null, "e": 2652, "s": 2568, "text": "Please feel free to download the dataset and follow along, if you want to practice:" }, { "code": null, "e": 2663, "s": 2652, "text": "github.com" }, { "code": null, "e": 2695, "s": 2663, "text": "Let’s import the dataset first." }, { "code": null, "e": 2740, "s": 2695, "text": "data = read.csv(\"health_data.csv\")head(data)" }, { "code": null, "e": 2930, "s": 2740, "text": "As we will examine the relationship between age and systolic blood pressure first, it will be interesting to see a scatter plot of age and systolic blood pressure. Here is the scatter plot:" }, { "code": null, "e": 3071, "s": 2930, "text": "plot(data$Age, data$Systolic_blood_pressure, main= \"Systolic Blood Pressure vs Age\", xlab = \"Age\", ylab = \"Systolic Blood Pressure\")" }, { "code": null, "e": 3248, "s": 3071, "text": "It shows a linear trend. Though a lot of noise around. In R, we can directly find the linear regression model using the ‘lm’ function. I will save this model in a variable ‘m’." }, { "code": null, "e": 3297, "s": 3248, "text": "m = lm(data$Systolic_blood_pressure ~ data$Age)m" }, { "code": null, "e": 3305, "s": 3297, "text": "Output:" }, { "code": null, "e": 3427, "s": 3305, "text": "Call:lm(formula = data$Systolic_blood_pressure ~ data$Age)Coefficients:(Intercept) data$Age 94.872 0.635" }, { "code": null, "e": 3579, "s": 3427, "text": "The output shows that the intercept(beta0) is 94.872 and the slope is 0.635(beta1). We considered x1 as age. So the linear regression equation becomes:" }, { "code": null, "e": 3602, "s": 3579, "text": "y = 94.872 + 0.635*Age" }, { "code": null, "e": 3678, "s": 3602, "text": "As we considered only one explanatory variable, no x2, x3, or beta2, beta3." }, { "code": null, "e": 4003, "s": 3678, "text": "Here, intercept 94.872 means that if the age is zero or very close to zero systolic blood pressure will still be 94.872. In this dataset, the minimum age in the dataset is 18(feel free to check on your own). So, talking about zero age is far out of the range of this dataset. That’s why it is not so reasonable in this case." }, { "code": null, "e": 4132, "s": 4003, "text": "The slope of 0.635 means that if the age increases by 1 unit the systolic blood pressure will increase by 0.635 unit on average." }, { "code": null, "e": 4327, "s": 4132, "text": "Using this equation you can calculate the systolic blood pressure of a person’s age if you know the age. For example, if a person is 32 years old, the calculated systolic blood pressure will be:" }, { "code": null, "e": 4359, "s": 4327, "text": "y = 94.872 + 0.635*32 = 115.192" }, { "code": null, "e": 4479, "s": 4359, "text": "Now, how correct this estimate is, we will determine that later in this article. This is time to add one more variable." }, { "code": null, "e": 4504, "s": 4479, "text": "Add weight to the model:" }, { "code": null, "e": 4753, "s": 4504, "text": "This is pretty simple. In the model ‘m’, we considered only one explanatory variable ‘Age’. This time we will have two explanatory variables: Age and Weight. It can be done using the same ‘lm’ function and I will save this model in a variable ‘m1’." }, { "code": null, "e": 4818, "s": 4753, "text": "m1 = lm(data$Systolic_blood_pressure ~ data$Age + data$Weight)m1" }, { "code": null, "e": 4826, "s": 4818, "text": "Output:" }, { "code": null, "e": 4988, "s": 4826, "text": "Call:lm(formula = data$Systolic_blood_pressure ~ data$Age + data$Weight)Coefficients:(Intercept) data$Age data$Weight 84.2799 0.6300 0.1386" }, { "code": null, "e": 5348, "s": 4988, "text": "Here, intercept(beta0) is 84.28. If you notice it is different than the intercept in ‘m’(94.87). This time slope(beta1) for Age variable becomes 0.63 which is not so different than the beta1 in model ‘m’. This slope means if Age increases by 1 unit systolic blood pressure will increase by 0.63 unit on average when the Weight variable is controlled or fixed." }, { "code": null, "e": 5570, "s": 5348, "text": "On the other hand, the slope for the Weight variable(beta2) is 0.1386 means that if weight increases by 1 unit, systolic blood pressure will increase by 0.1386 unit on average when the Age variable is controlled or fixed." }, { "code": null, "e": 5610, "s": 5570, "text": "The linear regression equation becomes:" }, { "code": null, "e": 5652, "s": 5610, "text": "y = 84.2799 + 0.63* Age + 0.1386 * Weight" }, { "code": null, "e": 5777, "s": 5652, "text": "If you know a person’s Age and Weight you will be able to estimate that person’s systolic blood pressure using this formula." }, { "code": null, "e": 5802, "s": 5777, "text": "Adding BMI to this Model" }, { "code": null, "e": 5964, "s": 5802, "text": "Lastly, we add BMI to this model to see if BMI changes the dynamic of this model. Let’s use the ‘lm’ function again and save this model in a variable named ‘m2’." }, { "code": null, "e": 6038, "s": 5964, "text": "m2 = lm(data$Systolic_blood_pressure ~ data$Age + data$Weight+data$BMI)m2" }, { "code": null, "e": 6046, "s": 6038, "text": "Output:" }, { "code": null, "e": 6249, "s": 6046, "text": "Call:lm(formula = data$Systolic_blood_pressure ~ data$Age + data$Weight + data$BMI)Coefficients:(Intercept) data$Age data$Weight data$BMI 89.5218 0.6480 0.3209 -0.7244" }, { "code": null, "e": 6614, "s": 6249, "text": "Notice the output carefully. The intercept changed again. It is 89.52 this time. The slope for Age is 0.648 now. It was 0.63 in the previous model. The slope for weight is 0.3209 while it was 0.1386 in the previous model. So, After adding the BMI in the model the value beta0, beta1 and beta2 changed pretty significantly. The slope of the BMI variable is -0.7244." }, { "code": null, "e": 6654, "s": 6614, "text": "The linear regression equation becomes:" }, { "code": null, "e": 6707, "s": 6654, "text": "y = 89.5218 + 0.648*Age + 0.3209*Weight — 0.7244*BMI" }, { "code": null, "e": 6885, "s": 6707, "text": "Woo! Our multiple linear regression model is ready! Now if we know the age, weight, and BMI of a person, we will be able to calculate the systolic blood pressure of that person!" }, { "code": null, "e": 6962, "s": 6885, "text": "How accurate that systolic blood pressure calculation from this equation is?" }, { "code": null, "e": 7186, "s": 6962, "text": "Let’s find out. One very common and popular way to assess the fit of the data in multiple linear regression is the coefficient of variation (R-squared). The formula for R-squared is the same as the simple linear regression:" }, { "code": null, "e": 7192, "s": 7186, "text": "Here," }, { "code": null, "e": 7355, "s": 7192, "text": "y_calc is the calculated value of the response variable. In this case, the values of systolic blood pressure that are calculated using the linear regression model" }, { "code": null, "e": 7417, "s": 7355, "text": "y_mean is the mean of original systolic blood pressure values" }, { "code": null, "e": 7477, "s": 7417, "text": "y is the original systolic blood pressures from the dataset" }, { "code": null, "e": 7600, "s": 7477, "text": "The R-squared value represents the proportion of the response variable that can be explained by the explanatory variables." }, { "code": null, "e": 7953, "s": 7600, "text": "I will use R to calculate R-squared. It is very simple in R. We have three models, and we saved them in three different variables m, m1, and m2. It will be good to see the fit of each model. I will calculate the R-squared value for all three models. Here is the R-squared value for the first model ‘m’ where the explanatory variable was only the ‘Age’." }, { "code": null, "e": 8111, "s": 7953, "text": "R_squared1 = sum((fitted(m) - mean(data$Systolic_blood_pressure))**2) / sum((data$Systolic_blood_pressure - mean(data$Systolic_blood_pressure))**2)R_squared1" }, { "code": null, "e": 8119, "s": 8111, "text": "Output:" }, { "code": null, "e": 8129, "s": 8119, "text": "0.3795497" }, { "code": null, "e": 8203, "s": 8129, "text": "That means 37.95% of the systolic blood pressure can be explained by Age." }, { "code": null, "e": 8302, "s": 8203, "text": "The R-squared value for the second model ‘m1’ where explanatory variables were ‘Age’ and ‘Weight’:" }, { "code": null, "e": 8461, "s": 8302, "text": "R_squared2 = sum((fitted(m1) - mean(data$Systolic_blood_pressure))**2) / sum((data$Systolic_blood_pressure - mean(data$Systolic_blood_pressure))**2)R_squared2" }, { "code": null, "e": 8469, "s": 8461, "text": "Output:" }, { "code": null, "e": 8479, "s": 8469, "text": "0.3958562" }, { "code": null, "e": 8634, "s": 8479, "text": "39.58% of the systolic blood pressure can be explained by ‘Age’ and ‘Weight’ together. Look R-squared improved a bit after adding the Weight to the model." }, { "code": null, "e": 8744, "s": 8634, "text": "Lastly, the R-squared value for the model m2 where the explanatory variables were ‘Age’, ‘Weight’, and ‘BMI’." }, { "code": null, "e": 8903, "s": 8744, "text": "R_squared3 = sum((fitted(m2) - mean(data$Systolic_blood_pressure))**2) / sum((data$Systolic_blood_pressure - mean(data$Systolic_blood_pressure))**2)R_squared3" }, { "code": null, "e": 8911, "s": 8903, "text": "Output:" }, { "code": null, "e": 8921, "s": 8911, "text": "0.4099555" }, { "code": null, "e": 9011, "s": 8921, "text": "40.99% of the systolic blood pressure can be explained by the ‘Age’, ‘Weight’, and ‘BMI’." }, { "code": null, "e": 9213, "s": 9011, "text": "The next steps might be a bit hard for you to understand totally if you are not familiar with confidence intervals or hypothesis test concepts. Here is an article to learn confidence interval concepts:" }, { "code": null, "e": 9236, "s": 9213, "text": "towardsdatascience.com" }, { "code": null, "e": 9294, "s": 9236, "text": "Here is an article on the hypothesis tests. Please check:" }, { "code": null, "e": 9317, "s": 9294, "text": "towardsdatascience.com" }, { "code": null, "e": 9327, "s": 9317, "text": "Inference" }, { "code": null, "e": 9516, "s": 9327, "text": "In this section, we will work on an F-test to see if the model was significant. That means if at least one of the explanatory variables has a linear association with the response variable." }, { "code": null, "e": 9578, "s": 9516, "text": "There is a five-step process to perform this hypothesis test:" }, { "code": null, "e": 9586, "s": 9578, "text": "step 1:" }, { "code": null, "e": 9633, "s": 9586, "text": "Set the hypothesis and select the alpha level:" }, { "code": null, "e": 9878, "s": 9633, "text": "We set a null hypothesis and an alternative hypothesis. The null hypothesis is that the slope of all the variables is zeros. That means there is no association between any of the variables and the response variable. Here is the null hypothesis:" }, { "code": null, "e": 10210, "s": 9878, "text": "If we do not find enough evidence that the null hypothesis is true then we will reject the null hypothesis. That will give us the evidence that at least one of the slopes not equal to zero. That means at least one of the explanatory variables has a linear association with the response variable. This is the alternative hypothesis:" }, { "code": null, "e": 10288, "s": 10210, "text": "I am setting the alpha level as 0.05. That means the confidence level is 95%." }, { "code": null, "e": 10296, "s": 10288, "text": "Step 2:" }, { "code": null, "e": 10383, "s": 10296, "text": "Select the appropriate test statistic. Here we will use F-test. The test statistic is:" }, { "code": null, "e": 10514, "s": 10383, "text": "Here, df is the degrees of freedom. That is the number of explanatory variables. In this example that is 3 (Age, Weight, and BMI)." }, { "code": null, "e": 10673, "s": 10514, "text": "n is the number of rows or the number of data points. In this dataset, there are 100 rows. So, n = 100. Feel free to check it using the ‘nrows(data)’ function" }, { "code": null, "e": 10734, "s": 10673, "text": "We will discuss how to calculate the F-stat in a little bit." }, { "code": null, "e": 10742, "s": 10734, "text": "Step 3:" }, { "code": null, "e": 10767, "s": 10742, "text": "State the decision rule:" }, { "code": null, "e": 10892, "s": 10767, "text": "We need to determine the appropriate value from the F-distribution with df = 3, n-k-1 = 100–3- 1 = 96, and the alpha = 0.05." }, { "code": null, "e": 11063, "s": 10892, "text": "There are 2 ways to find the appropriate value. You can use the F distribution table. But I prefer using R. So, here is the value from the F-distribution calculated in R:" }, { "code": null, "e": 11079, "s": 11063, "text": "qf(0.95, 3, 96)" }, { "code": null, "e": 11087, "s": 11079, "text": "Output:" }, { "code": null, "e": 11100, "s": 11087, "text": "[1] 2.699393" }, { "code": null, "e": 11152, "s": 11100, "text": "The appropriate value from F-distribution is 2.699." }, { "code": null, "e": 11174, "s": 11152, "text": "The decision rule is:" }, { "code": null, "e": 11214, "s": 11174, "text": "Reject the null hypothesis if F ≥ 2.699" }, { "code": null, "e": 11260, "s": 11214, "text": "Otherwise, do not reject the null hypothesis." }, { "code": null, "e": 11268, "s": 11260, "text": "Step 4:" }, { "code": null, "e": 11293, "s": 11268, "text": "Compute the F-Statistic." }, { "code": null, "e": 11344, "s": 11293, "text": "Here is the table that calculates the F-statistic." }, { "code": null, "e": 11369, "s": 11344, "text": "Here in the table above," }, { "code": null, "e": 11454, "s": 11369, "text": "The Reg SS is the regression sum of squares that can be calculated with this formula" }, { "code": null, "e": 11540, "s": 11454, "text": "The Res SS is the residual sum of squares and here is the expression to calculate it:" }, { "code": null, "e": 11702, "s": 11540, "text": "Total SS can also be calculated as the sum of ‘Reg SS’ and ‘Res SS’. The following expression will also give you the same result as the sum of Reg SS and Res SS." }, { "code": null, "e": 11813, "s": 11702, "text": "Reg df or the regression degrees of freedom is the number of explanatory variables. In this example that is 3." }, { "code": null, "e": 11850, "s": 11813, "text": "n is the number of rows of the data." }, { "code": null, "e": 11899, "s": 11850, "text": "I will use R to calculate Reg SS, Res SS, and n:" }, { "code": null, "e": 12048, "s": 11899, "text": "regSS = sum((fitted(m2) - mean(data$Systolic_blood_pressure))**2)resSS = sum((data$Systolic_blood_pressure - mean(data$Systolic_blood_pressure))**2)" }, { "code": null, "e": 12056, "s": 12048, "text": "Output:" }, { "code": null, "e": 12081, "s": 12056, "text": "[1] 16050.88[1] 39091.84" }, { "code": null, "e": 12121, "s": 12081, "text": "Finding the number of rows in the data:" }, { "code": null, "e": 12132, "s": 12121, "text": "nrow(data)" }, { "code": null, "e": 12140, "s": 12132, "text": "Output:" }, { "code": null, "e": 12148, "s": 12140, "text": "[1] 100" }, { "code": null, "e": 12370, "s": 12148, "text": "The rest of the elements in the table can be calculated now. I used an excel sheet to generate the table. Though it is possible to find everything in R. But to make it in a table format I used excel. Here are the results:" }, { "code": null, "e": 12397, "s": 12370, "text": "The F-statistic is 13.139." }, { "code": null, "e": 12441, "s": 12397, "text": "Feel free to download this excel file here:" }, { "code": null, "e": 12452, "s": 12441, "text": "github.com" }, { "code": null, "e": 12460, "s": 12452, "text": "Step 5:" }, { "code": null, "e": 12708, "s": 12460, "text": "Conclusion: F is 13.139 which is greater than 2.699. So, we have enough evidence to reject the null hypothesis. That means At least one of the explanatory variables has a linear association with the response variable. So, the model is significant." }, { "code": null, "e": 13020, "s": 12708, "text": "From the F-test, we came to know that the model is significant. That means at least one of the explanatory variables has a linear association with the response variable. It will be helpful to know exactly which variable or variables have a linear association with the response variable(systolic blood pressure)." }, { "code": null, "e": 13055, "s": 13020, "text": "We will perform a t-test for that." }, { "code": null, "e": 13099, "s": 13055, "text": "t-test for individual explanatory variables" }, { "code": null, "e": 13342, "s": 13099, "text": "The F-test above shows that the model is significant. Now, we can test for each of the explanatory variables that if each of them has a linear association. As we already state five-step rule before. I will not go through the whole thing here." }, { "code": null, "e": 13421, "s": 13342, "text": "Step 1: The hypothesis and the alpha are exactly the same as the F-test above." }, { "code": null, "e": 13429, "s": 13421, "text": "Step 2:" }, { "code": null, "e": 13577, "s": 13429, "text": "In step 2, the test statistic will be the t-statistic with the degrees of freedom of n -k-1. We will use R to find the t-statistic in step 4 later." }, { "code": null, "e": 13585, "s": 13577, "text": "Step 3:" }, { "code": null, "e": 13757, "s": 13585, "text": "In step 3, we need to find the appropriate value from the t-distribution this time. There is a ‘t-distribution’ table to find out the appropriate value. I prefer to use R." }, { "code": null, "e": 13771, "s": 13757, "text": "qt(0.975, 96)" }, { "code": null, "e": 13779, "s": 13771, "text": "Output:" }, { "code": null, "e": 13792, "s": 13779, "text": "[1] 1.984984" }, { "code": null, "e": 13903, "s": 13792, "text": "If the t-statistic for any explanatory variable is greater than or equal to 1.985, reject the null hypothesis." }, { "code": null, "e": 13948, "s": 13903, "text": "Otherwise do not reject the null hypothesis." }, { "code": null, "e": 13956, "s": 13948, "text": "Step 4:" }, { "code": null, "e": 13984, "s": 13956, "text": "Compute the test statistic:" }, { "code": null, "e": 14249, "s": 13984, "text": "This is what makes a t-test that easy. If you just take a summary of your linear regression model in R that gives you the t-statistic and also the p-value. I will take the summary of the model ‘m2’ because we included all three explanatory variables in that model." }, { "code": null, "e": 14261, "s": 14249, "text": "summary(m2)" }, { "code": null, "e": 14269, "s": 14261, "text": "Output:" }, { "code": null, "e": 14949, "s": 14269, "text": "Call:lm(formula = data$Systolic_blood_pressure ~ data$Age + data$Weight + data$BMI)Residuals: Min 1Q Median 3Q Max -33.218 -10.572 -0.187 8.171 47.071Coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) 90.14758 8.34933 10.797 < 2e-16 ***data$Age 0.64315 0.08109 7.931 3.97e-12 ***data$Weight 0.32226 0.14753 2.184 0.0314 * data$BMI -0.73980 0.47751 -1.549 0.1246 ---Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1Residual standard error: 15.49 on 96 degrees of freedomMultiple R-squared: 0.4106, Adjusted R-squared: 0.3922 F-statistic: 22.29 on 3 and 96 DF, p-value: 4.89e-11" }, { "code": null, "e": 15081, "s": 14949, "text": "Look at the output carefully. There are t-statistic for each of the explanatory variables here. Also the p-values for each of them." }, { "code": null, "e": 15089, "s": 15081, "text": "Step 5:" }, { "code": null, "e": 15127, "s": 15089, "text": "Here is the conclusion from the test:" }, { "code": null, "e": 15422, "s": 15127, "text": "As per our decision rule, we should reject the null hypothesis if the t-statistic is greater than or equal to 1.985. You can see that for Age and Weight variable t-statistic is greater than 1.985. So, we can reject the null hypothesis for both of them. Let’s talk about each of them one by one." }, { "code": null, "e": 15567, "s": 15422, "text": "As per the t-test, Age variable is significant and has a linear association with the systolic blood pressure when Weight and BMI are controlled." }, { "code": null, "e": 15714, "s": 15567, "text": "In the same way Weight variable is also significant and has a linear association with the systolic blood pressure when Age and BMI are controlled." }, { "code": null, "e": 16028, "s": 15714, "text": "On the other hand, the t-statistic for the BMI variable is -1.549 which is smaller than 1.985. So, we do not have enough evidence to reject the null hypothesis for the BMI variable. That means the BMI variable does not have a linear association with the systolic blood pressure when Age and Weight are controlled." }, { "code": null, "e": 16649, "s": 16028, "text": "You can also use the p-value to draw a conclusion. If the p-value is greater than or equal to the alpha level (in this example 0.05), we have enough evidence to reject the null hypothesis. If you notice in the summary output above, for the Age and Weight variable, the p-value is less than the alpha level 0.05. So, this way also we can conclude that Age and Weight variables have a linear association with systolic blood pressure. On the other hand, the p-value for BMI is greater than 0.05. Using p-value also you can determine that the BMI variable does not have a linear association with the systolic blood pressure." }, { "code": null, "e": 17092, "s": 16649, "text": "If you read my article on simple linear regression, you may be wondering why I did not use ANOVA for the inference part here. Using ANOVA in multiple linear regression is not a good idea. Because it gives you different results if you put the response variable in a different order. It becomes very confusing. Try using the ‘anova()’ function in R with ‘Age’, Weight, BMI once. And Weight, Age, BMI once. You might get a different ANOVA table." }, { "code": null, "e": 17590, "s": 17092, "text": "I hope this was helpful. This is a lot of material covered in this article. If all this material is totally new to you it may take some time to really grasp all these ideas. These are not the only tests. There are several other tests in statistics. These are just some common and popular hypothesis tests. I suggest, take a dataset of your own and try developing a linear regression model and running hypothesis tests like this article. If you read this for learning, that’s the only way to learn." } ]
Frequency of an integer in the given array using Divide and Conquer - GeeksforGeeks
03 Jun, 2021 Given an unsorted array arr[] and an integer K, the task is to count the occurrences of K in the given array using the Divide and Conquer method. Examples: Input: arr[] = {1, 1, 2, 2, 2, 2, 3}, K = 1 Output: 2 Input: arr[] = {1, 1, 2, 2, 2, 2, 3}, K = 4 Output: 0 Approach: The idea is to divide the array into two parts of equal size and count the number of occurrences of K in each half and then add them up. Divide the array into two parts until there is only one element left in the array. Check whether a single element in the array is K or not. If it is K then return 1 otherwise 0. Add up the returned values for each of the elements to find the occurrence of K in the whole array. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implrmrntation of the approach #include <iostream>using namespace std; // Function to return the frequency of x// in the subarray arr[low...high]int count(int arr[], int low, int high, int x){ // If the subarray is invalid or the // element is not found if ((low > high) || (low == high && arr[low] != x)) return 0; // If there's only a single element // which is equal to x if (low == high && arr[low] == x) return 1; // Divide the array into two parts and // then find the count of occurrences // of x in both the parts return count(arr, low, (low + high) / 2, x) + count(arr, 1 + (low + high) / 2, high, x);} // Driver codeint main(){ int arr[] = { 30, 1, 42, 5, 56, 3, 56, 9 }; int n = sizeof(arr) / sizeof(int); int x = 56; cout << count(arr, 0, n - 1, x); return 0;} // Java implrmrntation of the approach class GFG { // Function to return the frequency of x // in the subarray arr[low...high] static int count(int arr[], int low, int high, int x) { // If the subarray is invalid or the // element is not found if ((low > high) || (low == high && arr[low] != x)) return 0; // If there's only a single element // which is equal to x if (low == high && arr[low] == x) return 1; // Divide the array into two parts and // then find the count of occurrences // of x in both the parts return count(arr, low, (low + high) / 2, x) + count(arr, 1 + (low + high) / 2, high, x); } // Driver code public static void main(String args[]) { int arr[] = { 30, 1, 42, 5, 56, 3, 56, 9 }; int n = arr.length; int x = 56; System.out.print(count(arr, 0, n - 1, x)); }} # Python3 implrmrntation of the approach # Function to return the frequency of x# in the subarray arr[low...high]def count(arr, low, high, x): # If the subarray is invalid or the # element is not found if ((low > high) or (low == high and arr[low] != x)): return 0; # If there's only a single element # which is equal to x if (low == high and arr[low] == x): return 1; # Divide the array into two parts and # then find the count of occurrences # of x in both the parts return count(arr, low, (low + high) // 2, x) +\ count(arr, 1 + (low + high) // 2, high, x); # Driver codeif __name__ == '__main__': arr = [ 30, 1, 42, 5, 56, 3, 56, 9]; n = len(arr); x = 56; print(count(arr, 0, n - 1, x)); # This code is contributed by PrinciRaj1992 // C# implrmrntation of the approachusing System; class GFG{ // Function to return the frequency of x // in the subarray arr[low...high] static int count(int []arr, int low, int high, int x) { // If the subarray is invalid or the // element is not found if ((low > high) || (low == high && arr[low] != x)) return 0; // If there's only a single element // which is equal to x if (low == high && arr[low] == x) return 1; // Divide the array into two parts and // then find the count of occurrences // of x in both the parts return count(arr, low, (low + high) / 2, x) + count(arr, 1 + (low + high) / 2, high, x); } // Driver code public static void Main() { int []arr = { 30, 1, 42, 5, 56, 3, 56, 9 }; int n = arr.Length; int x = 56; Console.Write(count(arr, 0, n - 1, x)); }} // This code is contributed by AnkitRai01 <script>// Javascript implrmrntation of the approach// Function to return the frequency of x// in the subarray arr[low...high] function count(arr, low, high, x) { // If the subarray is invalid or the // element is not found if ((low > high) || (low == high && arr[low] != x)) return 0; // If there's only a single element // which is equal to x if (low == high && arr[low] == x) return 1; // Divide the array into two parts and // then find the count of occurrences // of x in both the parts return count(arr, low, Math.floor((low + high) / 2), x) + count(arr, 1 + Math.floor((low + high) / 2), high, x);} // Driver code let arr = [30, 1, 42, 5, 56, 3, 56, 9];let n = arr.length;let x = 56; document.write(count(arr, 0, n - 1, x)); // This code is contributed by _saurabh_jaiswal</script> 2 Time Complexity: O(NlogN) ankthon princiraj1992 uttamsingh1 santradibbo _saurabh_jaiswal Arrays Divide and Conquer Recursion Arrays Recursion Divide and Conquer Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Window Sliding Technique Trapping Rain Water Reversal algorithm for array rotation Move all negative numbers to beginning and positive to end with constant extra space Program to find sum of elements in a given array Merge Sort QuickSort Binary Search Program for Tower of Hanoi Divide and Conquer Algorithm | Introduction
[ { "code": null, "e": 24822, "s": 24794, "text": "\n03 Jun, 2021" }, { "code": null, "e": 24968, "s": 24822, "text": "Given an unsorted array arr[] and an integer K, the task is to count the occurrences of K in the given array using the Divide and Conquer method." }, { "code": null, "e": 24979, "s": 24968, "text": "Examples: " }, { "code": null, "e": 25033, "s": 24979, "text": "Input: arr[] = {1, 1, 2, 2, 2, 2, 3}, K = 1 Output: 2" }, { "code": null, "e": 25087, "s": 25033, "text": "Input: arr[] = {1, 1, 2, 2, 2, 2, 3}, K = 4 Output: 0" }, { "code": null, "e": 25234, "s": 25087, "text": "Approach: The idea is to divide the array into two parts of equal size and count the number of occurrences of K in each half and then add them up." }, { "code": null, "e": 25317, "s": 25234, "text": "Divide the array into two parts until there is only one element left in the array." }, { "code": null, "e": 25412, "s": 25317, "text": "Check whether a single element in the array is K or not. If it is K then return 1 otherwise 0." }, { "code": null, "e": 25512, "s": 25412, "text": "Add up the returned values for each of the elements to find the occurrence of K in the whole array." }, { "code": null, "e": 25564, "s": 25512, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 25568, "s": 25564, "text": "C++" }, { "code": null, "e": 25573, "s": 25568, "text": "Java" }, { "code": null, "e": 25581, "s": 25573, "text": "Python3" }, { "code": null, "e": 25584, "s": 25581, "text": "C#" }, { "code": null, "e": 25595, "s": 25584, "text": "Javascript" }, { "code": "// C++ implrmrntation of the approach #include <iostream>using namespace std; // Function to return the frequency of x// in the subarray arr[low...high]int count(int arr[], int low, int high, int x){ // If the subarray is invalid or the // element is not found if ((low > high) || (low == high && arr[low] != x)) return 0; // If there's only a single element // which is equal to x if (low == high && arr[low] == x) return 1; // Divide the array into two parts and // then find the count of occurrences // of x in both the parts return count(arr, low, (low + high) / 2, x) + count(arr, 1 + (low + high) / 2, high, x);} // Driver codeint main(){ int arr[] = { 30, 1, 42, 5, 56, 3, 56, 9 }; int n = sizeof(arr) / sizeof(int); int x = 56; cout << count(arr, 0, n - 1, x); return 0;}", "e": 26490, "s": 25595, "text": null }, { "code": "// Java implrmrntation of the approach class GFG { // Function to return the frequency of x // in the subarray arr[low...high] static int count(int arr[], int low, int high, int x) { // If the subarray is invalid or the // element is not found if ((low > high) || (low == high && arr[low] != x)) return 0; // If there's only a single element // which is equal to x if (low == high && arr[low] == x) return 1; // Divide the array into two parts and // then find the count of occurrences // of x in both the parts return count(arr, low, (low + high) / 2, x) + count(arr, 1 + (low + high) / 2, high, x); } // Driver code public static void main(String args[]) { int arr[] = { 30, 1, 42, 5, 56, 3, 56, 9 }; int n = arr.length; int x = 56; System.out.print(count(arr, 0, n - 1, x)); }}", "e": 27504, "s": 26490, "text": null }, { "code": "# Python3 implrmrntation of the approach # Function to return the frequency of x# in the subarray arr[low...high]def count(arr, low, high, x): # If the subarray is invalid or the # element is not found if ((low > high) or (low == high and arr[low] != x)): return 0; # If there's only a single element # which is equal to x if (low == high and arr[low] == x): return 1; # Divide the array into two parts and # then find the count of occurrences # of x in both the parts return count(arr, low, (low + high) // 2, x) +\\ count(arr, 1 + (low + high) // 2, high, x); # Driver codeif __name__ == '__main__': arr = [ 30, 1, 42, 5, 56, 3, 56, 9]; n = len(arr); x = 56; print(count(arr, 0, n - 1, x)); # This code is contributed by PrinciRaj1992", "e": 28302, "s": 27504, "text": null }, { "code": "// C# implrmrntation of the approachusing System; class GFG{ // Function to return the frequency of x // in the subarray arr[low...high] static int count(int []arr, int low, int high, int x) { // If the subarray is invalid or the // element is not found if ((low > high) || (low == high && arr[low] != x)) return 0; // If there's only a single element // which is equal to x if (low == high && arr[low] == x) return 1; // Divide the array into two parts and // then find the count of occurrences // of x in both the parts return count(arr, low, (low + high) / 2, x) + count(arr, 1 + (low + high) / 2, high, x); } // Driver code public static void Main() { int []arr = { 30, 1, 42, 5, 56, 3, 56, 9 }; int n = arr.Length; int x = 56; Console.Write(count(arr, 0, n - 1, x)); }} // This code is contributed by AnkitRai01", "e": 29350, "s": 28302, "text": null }, { "code": "<script>// Javascript implrmrntation of the approach// Function to return the frequency of x// in the subarray arr[low...high] function count(arr, low, high, x) { // If the subarray is invalid or the // element is not found if ((low > high) || (low == high && arr[low] != x)) return 0; // If there's only a single element // which is equal to x if (low == high && arr[low] == x) return 1; // Divide the array into two parts and // then find the count of occurrences // of x in both the parts return count(arr, low, Math.floor((low + high) / 2), x) + count(arr, 1 + Math.floor((low + high) / 2), high, x);} // Driver code let arr = [30, 1, 42, 5, 56, 3, 56, 9];let n = arr.length;let x = 56; document.write(count(arr, 0, n - 1, x)); // This code is contributed by _saurabh_jaiswal</script>", "e": 30218, "s": 29350, "text": null }, { "code": null, "e": 30220, "s": 30218, "text": "2" }, { "code": null, "e": 30249, "s": 30222, "text": "Time Complexity: O(NlogN) " }, { "code": null, "e": 30257, "s": 30249, "text": "ankthon" }, { "code": null, "e": 30271, "s": 30257, "text": "princiraj1992" }, { "code": null, "e": 30283, "s": 30271, "text": "uttamsingh1" }, { "code": null, "e": 30295, "s": 30283, "text": "santradibbo" }, { "code": null, "e": 30312, "s": 30295, "text": "_saurabh_jaiswal" }, { "code": null, "e": 30319, "s": 30312, "text": "Arrays" }, { "code": null, "e": 30338, "s": 30319, "text": "Divide and Conquer" }, { "code": null, "e": 30348, "s": 30338, "text": "Recursion" }, { "code": null, "e": 30355, "s": 30348, "text": "Arrays" }, { "code": null, "e": 30365, "s": 30355, "text": "Recursion" }, { "code": null, "e": 30384, "s": 30365, "text": "Divide and Conquer" }, { "code": null, "e": 30482, "s": 30384, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30507, "s": 30482, "text": "Window Sliding Technique" }, { "code": null, "e": 30527, "s": 30507, "text": "Trapping Rain Water" }, { "code": null, "e": 30565, "s": 30527, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 30650, "s": 30565, "text": "Move all negative numbers to beginning and positive to end with constant extra space" }, { "code": null, "e": 30699, "s": 30650, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 30710, "s": 30699, "text": "Merge Sort" }, { "code": null, "e": 30720, "s": 30710, "text": "QuickSort" }, { "code": null, "e": 30734, "s": 30720, "text": "Binary Search" }, { "code": null, "e": 30761, "s": 30734, "text": "Program for Tower of Hanoi" } ]