title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Replace a string using StringBuilder
Set a String − StringBuilder str = new StringBuilder("Fitness is important"); Use the Replace() method to replace a string − str.Replace("important", "essential"); The following is the code to replace a string using StringBuilder − Live Demo using System; using System.Text; class Demo { static void Main() { // Initial String StringBuilder str = new StringBuilder("Fitness is important"); Console.WriteLine(str.ToString()); // Replace str.Replace("important", "essential"); // New String Console.WriteLine(str.ToString()); Console.ReadLine(); } } Fitness is important Fitness is essential
[ { "code": null, "e": 1077, "s": 1062, "text": "Set a String −" }, { "code": null, "e": 1140, "s": 1077, "text": "StringBuilder str = new StringBuilder(\"Fitness is important\");" }, { "code": null, "e": 1187, "s": 1140, "text": "Use the Replace() method to replace a string −" }, { "code": null, "e": 1226, "s": 1187, "text": "str.Replace(\"important\", \"essential\");" }, { "code": null, "e": 1294, "s": 1226, "text": "The following is the code to replace a string using StringBuilder −" }, { "code": null, "e": 1305, "s": 1294, "text": " Live Demo" }, { "code": null, "e": 1669, "s": 1305, "text": "using System;\nusing System.Text;\n\nclass Demo {\n static void Main() {\n\n // Initial String\n StringBuilder str = new StringBuilder(\"Fitness is important\");\n Console.WriteLine(str.ToString());\n\n // Replace\n str.Replace(\"important\", \"essential\");\n\n // New String\n Console.WriteLine(str.ToString());\n Console.ReadLine();\n }\n}" }, { "code": null, "e": 1711, "s": 1669, "text": "Fitness is important\nFitness is essential" } ]
How to print in same line in Python?
The print() method in Python automatically prints in the next line each time. The print() method by default takes the pointer to the next line. Live Demo for i in range(5): print(i) 0 1 2 3 4 The print method takes an extra parameter end=” “ to keep the pointer on the same line. The end parameter can take certain values such as a space or some sign in the double quotes to separate the elements printed in the same line. print(“.....” , end=” “) The end=” “ is used to print in the same line with space after each element. It prints a space after each element in the same line. Live Demo for i in range(5): print(i,end=" ") 0 1 2 3 4 The end=”” is used to print on same line without space. Keeping the doube quotes empty merge all the elements together in the same line. Live Demo for i in range(5): print(i,end="") 01234 The end=”,” is used to print in the same line with a comma after each element. We can use some other sign such as ‘.’ or ‘;’ inside the end parameter. Live Demo for i in range(5): print(i,end=",") print(i,end=".") 0,1,2,3,4, 0.1.2.3.4.
[ { "code": null, "e": 1206, "s": 1062, "text": "The print() method in Python automatically prints in the next line each time. The print() method by default takes the pointer to the next line." }, { "code": null, "e": 1217, "s": 1206, "text": " Live Demo" }, { "code": null, "e": 1248, "s": 1217, "text": "for i in range(5):\n print(i)" }, { "code": null, "e": 1258, "s": 1248, "text": "0\n1\n2\n3\n4" }, { "code": null, "e": 1346, "s": 1258, "text": "The print method takes an extra parameter end=” “ to keep the pointer on the same line." }, { "code": null, "e": 1489, "s": 1346, "text": "The end parameter can take certain values such as a space or some sign in the double quotes to separate the elements printed in the same line." }, { "code": null, "e": 1514, "s": 1489, "text": "print(“.....” , end=” “)" }, { "code": null, "e": 1646, "s": 1514, "text": "The end=” “ is used to print in the same line with space after each element. It prints a space after each element in the same line." }, { "code": null, "e": 1657, "s": 1646, "text": " Live Demo" }, { "code": null, "e": 1696, "s": 1657, "text": "for i in range(5):\n print(i,end=\" \")" }, { "code": null, "e": 1706, "s": 1696, "text": "0 1 2 3 4" }, { "code": null, "e": 1843, "s": 1706, "text": "The end=”” is used to print on same line without space. Keeping the doube quotes empty merge all the elements together in the same line." }, { "code": null, "e": 1854, "s": 1843, "text": " Live Demo" }, { "code": null, "e": 1892, "s": 1854, "text": "for i in range(5):\n print(i,end=\"\")" }, { "code": null, "e": 1898, "s": 1892, "text": "01234" }, { "code": null, "e": 2049, "s": 1898, "text": "The end=”,” is used to print in the same line with a comma after each element. We can use some other sign such as ‘.’ or ‘;’ inside the end parameter." }, { "code": null, "e": 2060, "s": 2049, "text": " Live Demo" }, { "code": null, "e": 2119, "s": 2060, "text": "for i in range(5):\n print(i,end=\",\")\n print(i,end=\".\")" }, { "code": null, "e": 2141, "s": 2119, "text": "0,1,2,3,4,\n0.1.2.3.4." } ]
AI with Python – Data Preparation
We have already studied supervised as well as unsupervised machine learning algorithms. These algorithms require formatted data to start the training process. We must prepare or format data in a certain way so that it can be supplied as an input to ML algorithms. This chapter focuses on data preparation for machine learning algorithms. In our daily life, we deal with lots of data but this data is in raw form. To provide the data as the input of machine learning algorithms, we need to convert it into a meaningful data. That is where data preprocessing comes into picture. In other simple words, we can say that before providing the data to the machine learning algorithms we need to preprocess the data. Follow these steps to preprocess the data in Python − Step 1 − Importing the useful packages − If we are using Python then this would be the first step for converting the data into a certain format, i.e., preprocessing. It can be done as follows − import numpy as np import sklearn.preprocessing Here we have used the following two packages − NumPy − Basically NumPy is a general purpose array-processing package designed to efficiently manipulate large multi-dimensional arrays of arbitrary records without sacrificing too much speed for small multi-dimensional arrays. NumPy − Basically NumPy is a general purpose array-processing package designed to efficiently manipulate large multi-dimensional arrays of arbitrary records without sacrificing too much speed for small multi-dimensional arrays. Sklearn.preprocessing − This package provides many common utility functions and transformer classes to change raw feature vectors into a representation that is more suitable for machine learning algorithms. Sklearn.preprocessing − This package provides many common utility functions and transformer classes to change raw feature vectors into a representation that is more suitable for machine learning algorithms. Step 2 − Defining sample data − After importing the packages, we need to define some sample data so that we can apply preprocessing techniques on that data. We will now define the following sample data − input_data = np.array([2.1, -1.9, 5.5], [-1.5, 2.4, 3.5], [0.5, -7.9, 5.6], [5.9, 2.3, -5.8]) Step3 − Applying preprocessing technique − In this step, we need to apply any of the preprocessing techniques. The following section describes the data preprocessing techniques. The techniques for data preprocessing are described below − This is the preprocessing technique which is used when we need to convert our numerical values into Boolean values. We can use an inbuilt method to binarize the input data say by using 0.5 as the threshold value in the following way − data_binarized = preprocessing.Binarizer(threshold = 0.5).transform(input_data) print("\nBinarized data:\n", data_binarized) Now, after running the above code we will get the following output, all the values above 0.5(threshold value) would be converted to 1 and all the values below 0.5 would be converted to 0. Binarized data [[ 1. 0. 1.] [ 0. 1. 1.] [ 0. 0. 1.] [ 1. 1. 0.]] It is another very common preprocessing technique that is used in machine learning. Basically it is used to eliminate the mean from feature vector so that every feature is centered on zero. We can also remove the bias from the features in the feature vector. For applying mean removal preprocessing technique on the sample data, we can write the Python code shown below. The code will display the Mean and Standard deviation of the input data − print("Mean = ", input_data.mean(axis = 0)) print("Std deviation = ", input_data.std(axis = 0)) We will get the following output after running the above lines of code − Mean = [ 1.75 -1.275 2.2] Std deviation = [ 2.71431391 4.20022321 4.69414529] Now, the code below will remove the Mean and Standard deviation of the input data − data_scaled = preprocessing.scale(input_data) print("Mean =", data_scaled.mean(axis=0)) print("Std deviation =", data_scaled.std(axis = 0)) We will get the following output after running the above lines of code − Mean = [ 1.11022302e-16 0.00000000e+00 0.00000000e+00] Std deviation = [ 1. 1. 1.] It is another data preprocessing technique that is used to scale the feature vectors. Scaling of feature vectors is needed because the values of every feature can vary between many random values. In other words we can say that scaling is important because we do not want any feature to be synthetically large or small. With the help of the following Python code, we can do the scaling of our input data, i.e., feature vector − # Min max scaling data_scaler_minmax = preprocessing.MinMaxScaler(feature_range=(0,1)) data_scaled_minmax = data_scaler_minmax.fit_transform(input_data) print ("\nMin max scaled data:\n", data_scaled_minmax) We will get the following output after running the above lines of code − Min max scaled data [ [ 0.48648649 0.58252427 0.99122807] [ 0. 1. 0.81578947] [ 0.27027027 0. 1. ] [ 1. 0. 99029126 0. ]] It is another data preprocessing technique that is used to modify the feature vectors. Such kind of modification is necessary to measure the feature vectors on a common scale. Followings are two types of normalization which can be used in machine learning − L1 Normalization It is also referred to as Least Absolute Deviations. This kind of normalization modifies the values so that the sum of the absolute values is always up to 1 in each row. It can be implemented on the input data with the help of the following Python code − # Normalize data data_normalized_l1 = preprocessing.normalize(input_data, norm = 'l1') print("\nL1 normalized data:\n", data_normalized_l1) The above line of code generates the following output &miuns; L1 normalized data: [[ 0.22105263 -0.2 0.57894737] [ -0.2027027 0.32432432 0.47297297] [ 0.03571429 -0.56428571 0.4 ] [ 0.42142857 0.16428571 -0.41428571]] L2 Normalization It is also referred to as least squares. This kind of normalization modifies the values so that the sum of the squares is always up to 1 in each row. It can be implemented on the input data with the help of the following Python code − # Normalize data data_normalized_l2 = preprocessing.normalize(input_data, norm = 'l2') print("\nL2 normalized data:\n", data_normalized_l2) The above line of code will generate the following output − L2 normalized data: [[ 0.33946114 -0.30713151 0.88906489] [ -0.33325106 0.53320169 0.7775858 ] [ 0.05156558 -0.81473612 0.57753446] [ 0.68706914 0.26784051 -0.6754239 ]] We already know that data in a certain format is necessary for machine learning algorithms. Another important requirement is that the data must be labelled properly before sending it as the input of machine learning algorithms. For example, if we talk about classification, there are lot of labels on the data. Those labels are in the form of words, numbers, etc. Functions related to machine learning in sklearn expect that the data must have number labels. Hence, if the data is in other form then it must be converted to numbers. This process of transforming the word labels into numerical form is called label encoding. Follow these steps for encoding the data labels in Python − Step1 − Importing the useful packages If we are using Python then this would be first step for converting the data into certain format, i.e., preprocessing. It can be done as follows − import numpy as np from sklearn import preprocessing Step 2 − Defining sample labels After importing the packages, we need to define some sample labels so that we can create and train the label encoder. We will now define the following sample labels − # Sample input labels input_labels = ['red','black','red','green','black','yellow','white'] Step 3 − Creating & training of label encoder object In this step, we need to create the label encoder and train it. The following Python code will help in doing this − # Creating the label encoder encoder = preprocessing.LabelEncoder() encoder.fit(input_labels) Following would be the output after running the above Python code − LabelEncoder() Step4 − Checking the performance by encoding random ordered list This step can be used to check the performance by encoding the random ordered list. Following Python code can be written to do the same − # encoding a set of labels test_labels = ['green','red','black'] encoded_values = encoder.transform(test_labels) print("\nLabels =", test_labels) The labels would get printed as follows − Labels = ['green', 'red', 'black'] Now, we can get the list of encoded values i.e. word labels converted to numbers as follows − print("Encoded values =", list(encoded_values)) The encoded values would get printed as follows − Encoded values = [1, 2, 0] Step 5 − Checking the performance by decoding a random set of numbers − This step can be used to check the performance by decoding the random set of numbers. Following Python code can be written to do the same − # decoding a set of values encoded_values = [3,0,4,1] decoded_list = encoder.inverse_transform(encoded_values) print("\nEncoded values =", encoded_values) Now, Encoded values would get printed as follows − Encoded values = [3, 0, 4, 1] print("\nDecoded labels =", list(decoded_list)) Now, decoded values would get printed as follows − Decoded labels = ['white', 'black', 'yellow', 'green'] Unlabeled data mainly consists of the samples of natural or human-created object that can easily be obtained from the world. They include, audio, video, photos, news articles, etc. On the other hand, labeled data takes a set of unlabeled data and augments each piece of that unlabeled data with some tag or label or class that is meaningful. For example, if we have a photo then the label can be put based on the content of the photo, i.e., it is photo of a boy or girl or animal or anything else. Labeling the data needs human expertise or judgment about a given piece of unlabeled data. There are many scenarios where unlabeled data is plentiful and easily obtained but labeled data often requires a human/expert to annotate. Semi-supervised learning attempts to combine labeled and unlabeled data to build better models. 78 Lectures 7 hours Arnab Chakraborty 87 Lectures 9.5 hours DigiFisk (Programming Is Fun) 10 Lectures 1 hours Nikoloz Sanakoevi 15 Lectures 54 mins Mukund Kumar Mishra 11 Lectures 1 hours Gilad James, PhD 20 Lectures 2 hours Gilad James, PhD Print Add Notes Bookmark this page
[ { "code": null, "e": 2469, "s": 2205, "text": "We have already studied supervised as well as unsupervised machine learning algorithms. These algorithms require formatted data to start the training process. We must prepare or format data in a certain way so that it can be supplied as an input to ML algorithms." }, { "code": null, "e": 2543, "s": 2469, "text": "This chapter focuses on data preparation for machine learning algorithms." }, { "code": null, "e": 2914, "s": 2543, "text": "In our daily life, we deal with lots of data but this data is in raw form. To provide the data as the input of machine learning algorithms, we need to convert it into a meaningful data. That is where data preprocessing comes into picture. In other simple words, we can say that before providing the data to the machine learning algorithms we need to preprocess the data." }, { "code": null, "e": 2968, "s": 2914, "text": "Follow these steps to preprocess the data in Python −" }, { "code": null, "e": 3162, "s": 2968, "text": "Step 1 − Importing the useful packages − If we are using Python then this would be the first step for converting the data into a certain format, i.e., preprocessing. It can be done as follows −" }, { "code": null, "e": 3211, "s": 3162, "text": "import numpy as np\nimport sklearn.preprocessing\n" }, { "code": null, "e": 3258, "s": 3211, "text": "Here we have used the following two packages −" }, { "code": null, "e": 3486, "s": 3258, "text": "NumPy − Basically NumPy is a general purpose array-processing package designed to efficiently manipulate large multi-dimensional arrays of arbitrary records without sacrificing too much speed for small multi-dimensional arrays." }, { "code": null, "e": 3714, "s": 3486, "text": "NumPy − Basically NumPy is a general purpose array-processing package designed to efficiently manipulate large multi-dimensional arrays of arbitrary records without sacrificing too much speed for small multi-dimensional arrays." }, { "code": null, "e": 3921, "s": 3714, "text": "Sklearn.preprocessing − This package provides many common utility functions and transformer classes to change raw feature vectors into a representation that is more suitable for machine learning algorithms." }, { "code": null, "e": 4128, "s": 3921, "text": "Sklearn.preprocessing − This package provides many common utility functions and transformer classes to change raw feature vectors into a representation that is more suitable for machine learning algorithms." }, { "code": null, "e": 4332, "s": 4128, "text": "Step 2 − Defining sample data − After importing the packages, we need to define some sample data so that we can apply preprocessing techniques on that data. We will now define the following sample data −" }, { "code": null, "e": 4492, "s": 4332, "text": "input_data = np.array([2.1, -1.9, 5.5],\n [-1.5, 2.4, 3.5],\n [0.5, -7.9, 5.6],\n [5.9, 2.3, -5.8])" }, { "code": null, "e": 4603, "s": 4492, "text": "Step3 − Applying preprocessing technique − In this step, we need to apply any of the preprocessing techniques." }, { "code": null, "e": 4670, "s": 4603, "text": "The following section describes the data preprocessing techniques." }, { "code": null, "e": 4730, "s": 4670, "text": "The techniques for data preprocessing are described below −" }, { "code": null, "e": 4965, "s": 4730, "text": "This is the preprocessing technique which is used when we need to convert our numerical values into Boolean values. We can use an inbuilt method to binarize the input data say by using 0.5 as the threshold value in the following way −" }, { "code": null, "e": 5090, "s": 4965, "text": "data_binarized = preprocessing.Binarizer(threshold = 0.5).transform(input_data)\nprint(\"\\nBinarized data:\\n\", data_binarized)" }, { "code": null, "e": 5278, "s": 5090, "text": "Now, after running the above code we will get the following output, all the values above 0.5(threshold value) would be converted to 1 and all the values below 0.5 would be converted to 0." }, { "code": null, "e": 5293, "s": 5278, "text": "Binarized data" }, { "code": null, "e": 5344, "s": 5293, "text": "[[ 1. 0. 1.]\n[ 0. 1. 1.]\n[ 0. 0. 1.]\n[ 1. 1. 0.]]\n" }, { "code": null, "e": 5789, "s": 5344, "text": "It is another very common preprocessing technique that is used in machine learning. Basically it is used to eliminate the mean from feature vector so that every feature is centered on zero. We can also remove the bias from the features in the feature vector. For applying mean removal preprocessing technique on the sample data, we can write the Python code shown below. The code will display the Mean and Standard deviation of the input data −" }, { "code": null, "e": 5886, "s": 5789, "text": "print(\"Mean = \", input_data.mean(axis = 0))\nprint(\"Std deviation = \", input_data.std(axis = 0))\n" }, { "code": null, "e": 5959, "s": 5886, "text": "We will get the following output after running the above lines of code −" }, { "code": null, "e": 6061, "s": 5959, "text": " Mean = [ 1.75 -1.275 2.2]\nStd deviation = [ 2.71431391 4.20022321 4.69414529]\n" }, { "code": null, "e": 6145, "s": 6061, "text": "Now, the code below will remove the Mean and Standard deviation of the input data −" }, { "code": null, "e": 6285, "s": 6145, "text": "data_scaled = preprocessing.scale(input_data)\nprint(\"Mean =\", data_scaled.mean(axis=0))\nprint(\"Std deviation =\", data_scaled.std(axis = 0))" }, { "code": null, "e": 6358, "s": 6285, "text": "We will get the following output after running the above lines of code −" }, { "code": null, "e": 6475, "s": 6358, "text": " Mean = [ 1.11022302e-16 0.00000000e+00 0.00000000e+00]\nStd deviation = [ 1. 1. 1.]\n" }, { "code": null, "e": 6902, "s": 6475, "text": "It is another data preprocessing technique that is used to scale the feature vectors. Scaling of feature vectors is needed because the values of every feature can vary between many random values. In other words we can say that scaling is important because we do not want any feature to be synthetically large or small. With the help of the following Python code, we can do the scaling of our input data, i.e., feature vector −" }, { "code": null, "e": 6920, "s": 6902, "text": "# Min max scaling" }, { "code": null, "e": 7110, "s": 6920, "text": "data_scaler_minmax = preprocessing.MinMaxScaler(feature_range=(0,1))\ndata_scaled_minmax = data_scaler_minmax.fit_transform(input_data)\nprint (\"\\nMin max scaled data:\\n\", data_scaled_minmax)" }, { "code": null, "e": 7183, "s": 7110, "text": "We will get the following output after running the above lines of code −" }, { "code": null, "e": 7203, "s": 7183, "text": "Min max scaled data" }, { "code": null, "e": 7368, "s": 7203, "text": "[ [ 0.48648649 0.58252427 0.99122807]\n[ 0. 1. 0.81578947]\n[ 0.27027027 0. 1. ]\n[ 1. 0. 99029126 0. ]]" }, { "code": null, "e": 7626, "s": 7368, "text": "It is another data preprocessing technique that is used to modify the feature vectors. Such kind of modification is necessary to measure the feature vectors on a common scale. Followings are two types of normalization which can be used in machine learning −" }, { "code": null, "e": 7643, "s": 7626, "text": "L1 Normalization" }, { "code": null, "e": 7898, "s": 7643, "text": "It is also referred to as Least Absolute Deviations. This kind of normalization modifies the values so that the sum of the absolute values is always up to 1 in each row. It can be implemented on the input data with the help of the following Python code −" }, { "code": null, "e": 8039, "s": 7898, "text": "# Normalize data\ndata_normalized_l1 = preprocessing.normalize(input_data, norm = 'l1')\nprint(\"\\nL1 normalized data:\\n\", data_normalized_l1)\n" }, { "code": null, "e": 8101, "s": 8039, "text": "The above line of code generates the following output &miuns;" }, { "code": null, "e": 8287, "s": 8101, "text": "L1 normalized data:\n[[ 0.22105263 -0.2 0.57894737]\n[ -0.2027027 0.32432432 0.47297297]\n[ 0.03571429 -0.56428571 0.4 ]\n[ 0.42142857 0.16428571 -0.41428571]]\n" }, { "code": null, "e": 8304, "s": 8287, "text": "L2 Normalization" }, { "code": null, "e": 8539, "s": 8304, "text": "It is also referred to as least squares. This kind of normalization modifies the values so that the sum of the squares is always up to 1 in each row. It can be implemented on the input data with the help of the following Python code −" }, { "code": null, "e": 8680, "s": 8539, "text": "# Normalize data\ndata_normalized_l2 = preprocessing.normalize(input_data, norm = 'l2')\nprint(\"\\nL2 normalized data:\\n\", data_normalized_l2)\n" }, { "code": null, "e": 8740, "s": 8680, "text": "The above line of code will generate the following output −" }, { "code": null, "e": 8926, "s": 8740, "text": "L2 normalized data:\n[[ 0.33946114 -0.30713151 0.88906489]\n[ -0.33325106 0.53320169 0.7775858 ]\n[ 0.05156558 -0.81473612 0.57753446]\n[ 0.68706914 0.26784051 -0.6754239 ]]\n" }, { "code": null, "e": 9550, "s": 8926, "text": "We already know that data in a certain format is necessary for machine learning algorithms. Another important requirement is that the data must be labelled properly before sending it as the input of machine learning algorithms. For example, if we talk about classification, there are lot of labels on the data. Those labels are in the form of words, numbers, etc. Functions related to machine learning in sklearn expect that the data must have number labels. Hence, if the data is in other form then it must be converted to numbers. This process of transforming the word labels into numerical form is called label encoding." }, { "code": null, "e": 9610, "s": 9550, "text": "Follow these steps for encoding the data labels in Python −" }, { "code": null, "e": 9648, "s": 9610, "text": "Step1 − Importing the useful packages" }, { "code": null, "e": 9795, "s": 9648, "text": "If we are using Python then this would be first step for converting the data into certain format, i.e., preprocessing. It can be done as follows −" }, { "code": null, "e": 9848, "s": 9795, "text": "import numpy as np\nfrom sklearn import preprocessing" }, { "code": null, "e": 9880, "s": 9848, "text": "Step 2 − Defining sample labels" }, { "code": null, "e": 10047, "s": 9880, "text": "After importing the packages, we need to define some sample labels so that we can create and train the label encoder. We will now define the following sample labels −" }, { "code": null, "e": 10139, "s": 10047, "text": "# Sample input labels\ninput_labels = ['red','black','red','green','black','yellow','white']" }, { "code": null, "e": 10192, "s": 10139, "text": "Step 3 − Creating & training of label encoder object" }, { "code": null, "e": 10308, "s": 10192, "text": "In this step, we need to create the label encoder and train it. The following Python code will help in doing this −" }, { "code": null, "e": 10403, "s": 10308, "text": "# Creating the label encoder\nencoder = preprocessing.LabelEncoder()\nencoder.fit(input_labels)\n" }, { "code": null, "e": 10471, "s": 10403, "text": "Following would be the output after running the above Python code −" }, { "code": null, "e": 10487, "s": 10471, "text": "LabelEncoder()\n" }, { "code": null, "e": 10552, "s": 10487, "text": "Step4 − Checking the performance by encoding random ordered list" }, { "code": null, "e": 10690, "s": 10552, "text": "This step can be used to check the performance by encoding the random ordered list. Following Python code can be written to do the same −" }, { "code": null, "e": 10837, "s": 10690, "text": "# encoding a set of labels\ntest_labels = ['green','red','black']\nencoded_values = encoder.transform(test_labels)\nprint(\"\\nLabels =\", test_labels)\n" }, { "code": null, "e": 10879, "s": 10837, "text": "The labels would get printed as follows −" }, { "code": null, "e": 10914, "s": 10879, "text": "Labels = ['green', 'red', 'black']" }, { "code": null, "e": 11008, "s": 10914, "text": "Now, we can get the list of encoded values i.e. word labels converted to numbers as follows −" }, { "code": null, "e": 11056, "s": 11008, "text": "print(\"Encoded values =\", list(encoded_values))" }, { "code": null, "e": 11106, "s": 11056, "text": "The encoded values would get printed as follows −" }, { "code": null, "e": 11133, "s": 11106, "text": "Encoded values = [1, 2, 0]" }, { "code": null, "e": 11205, "s": 11133, "text": "Step 5 − Checking the performance by decoding a random set of numbers −" }, { "code": null, "e": 11345, "s": 11205, "text": "This step can be used to check the performance by decoding the random set of numbers. Following Python code can be written to do the same −" }, { "code": null, "e": 11501, "s": 11345, "text": "# decoding a set of values\nencoded_values = [3,0,4,1]\ndecoded_list = encoder.inverse_transform(encoded_values)\nprint(\"\\nEncoded values =\", encoded_values)\n" }, { "code": null, "e": 11552, "s": 11501, "text": "Now, Encoded values would get printed as follows −" }, { "code": null, "e": 11630, "s": 11552, "text": "Encoded values = [3, 0, 4, 1]\nprint(\"\\nDecoded labels =\", list(decoded_list))" }, { "code": null, "e": 11681, "s": 11630, "text": "Now, decoded values would get printed as follows −" }, { "code": null, "e": 11736, "s": 11681, "text": "Decoded labels = ['white', 'black', 'yellow', 'green']" }, { "code": null, "e": 11917, "s": 11736, "text": "Unlabeled data mainly consists of the samples of natural or human-created object that can easily be obtained from the world. They include, audio, video, photos, news articles, etc." }, { "code": null, "e": 12325, "s": 11917, "text": "On the other hand, labeled data takes a set of unlabeled data and augments each piece of that unlabeled data with some tag or label or class that is meaningful. For example, if we have a photo then the label can be put based on the content of the photo, i.e., it is photo of a boy or girl or animal or anything else. Labeling the data needs human expertise or judgment about a given piece of unlabeled data." }, { "code": null, "e": 12560, "s": 12325, "text": "There are many scenarios where unlabeled data is plentiful and easily obtained but labeled data often requires a human/expert to annotate. Semi-supervised learning attempts to combine labeled and unlabeled data to build better models." }, { "code": null, "e": 12593, "s": 12560, "text": "\n 78 Lectures \n 7 hours \n" }, { "code": null, "e": 12612, "s": 12593, "text": " Arnab Chakraborty" }, { "code": null, "e": 12647, "s": 12612, "text": "\n 87 Lectures \n 9.5 hours \n" }, { "code": null, "e": 12678, "s": 12647, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 12711, "s": 12678, "text": "\n 10 Lectures \n 1 hours \n" }, { "code": null, "e": 12730, "s": 12711, "text": " Nikoloz Sanakoevi" }, { "code": null, "e": 12762, "s": 12730, "text": "\n 15 Lectures \n 54 mins\n" }, { "code": null, "e": 12783, "s": 12762, "text": " Mukund Kumar Mishra" }, { "code": null, "e": 12816, "s": 12783, "text": "\n 11 Lectures \n 1 hours \n" }, { "code": null, "e": 12834, "s": 12816, "text": " Gilad James, PhD" }, { "code": null, "e": 12867, "s": 12834, "text": "\n 20 Lectures \n 2 hours \n" }, { "code": null, "e": 12885, "s": 12867, "text": " Gilad James, PhD" }, { "code": null, "e": 12892, "s": 12885, "text": " Print" }, { "code": null, "e": 12903, "s": 12892, "text": " Add Notes" } ]
Disable a list item in a Bootstrap list group
Use the .disabled class in Bootstrap to disable a list item in a list group in Bootstrap. You can try to run the following code to disable a list item − Live Demo <!DOCTYPE html> <html> <head> <title>Bootstrap Example</title> <link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet"> <script src = "/scripts/jquery.min.js"></script> <script src = "/bootstrap/js/bootstrap.min.js"></script> </head> <body> <div class = "container"> <h2>Beverages</h2> <div class = "list-group"> <a href = "#" class = "list-group-item">Gatorade</a> <a href = "#" class = "list-group-item">Coca Cola</a> <a href = "#" class = "list-group-item">Pepsi</a> <a href = "#" class =" list-group-item disabled">Sting</a> </div> </div> </body> </html>
[ { "code": null, "e": 1152, "s": 1062, "text": "Use the .disabled class in Bootstrap to disable a list item in a list group in Bootstrap." }, { "code": null, "e": 1215, "s": 1152, "text": "You can try to run the following code to disable a list item −" }, { "code": null, "e": 1225, "s": 1215, "text": "Live Demo" }, { "code": null, "e": 1918, "s": 1225, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Example</title>\n <link href = \"/bootstrap/css/bootstrap.min.css\" rel = \"stylesheet\">\n <script src = \"/scripts/jquery.min.js\"></script>\n <script src = \"/bootstrap/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <div class = \"container\">\n <h2>Beverages</h2>\n <div class = \"list-group\">\n <a href = \"#\" class = \"list-group-item\">Gatorade</a>\n <a href = \"#\" class = \"list-group-item\">Coca Cola</a>\n <a href = \"#\" class = \"list-group-item\">Pepsi</a>\n <a href = \"#\" class =\" list-group-item disabled\">Sting</a>\n </div>\n </div>\n </body>\n</html>" } ]
How to create Database Connection in Perl?
Assuming we are going to work with MySQL database with Perl. Before connecting to a database make sure of the followings. You can take help of our MySQL tutorial in case you are not aware about how to create database and tables in MySQL database. You have created a database with a name TESTDB. You have created a table with a name TEST_TABLE in TESTDB. This table is having fields FIRST_NAME, LAST_NAME, AGE, SEX and INCOME. User ID "testuser" and password "test123" are set to access TESTDB. Perl Module DBI is installed properly on your machine. You have gone through MySQL tutorial to understand MySQL Basics. Following is the example of connecting with MySQL database "TESTDB" − #!/usr/bin/perl use DBI use strict; my $driver = "mysql"; my $database = "TESTDB"; my $dsn = "DBI:$driver:database=$database"; my $userid = "testuser"; my $password = "test123"; my $dbh = DBI->connect($dsn, $userid, $password ) or die $DBI::errstr; If a connection is established with the datasource then a Database Handle is returned and saved into dbhforfurtheruseotherwisedbh is set to undef value and $DBI::errstr returns an error string. To disconnect Database connection, use disconnect API as follows − $rc = $dbh->disconnect or warn $dbh->errstr; The transaction behaviour of the disconnect method is, sadly, undefined. Some database systems (such as Oracle and Ingres) will automatically commit any outstanding changes, but others (such as Informix) will rollback any outstanding changes. Applications not using AutoCommit should explicitly call commit or rollback before calling disconnect.
[ { "code": null, "e": 1309, "s": 1062, "text": "Assuming we are going to work with MySQL database with Perl. Before connecting to a database make sure of the followings. You can take help of our MySQL tutorial in case you are not aware about how to create database and tables in MySQL database." }, { "code": null, "e": 1357, "s": 1309, "text": "You have created a database with a name TESTDB." }, { "code": null, "e": 1416, "s": 1357, "text": "You have created a table with a name TEST_TABLE in TESTDB." }, { "code": null, "e": 1488, "s": 1416, "text": "This table is having fields FIRST_NAME, LAST_NAME, AGE, SEX and INCOME." }, { "code": null, "e": 1556, "s": 1488, "text": "User ID \"testuser\" and password \"test123\" are set to access TESTDB." }, { "code": null, "e": 1611, "s": 1556, "text": "Perl Module DBI is installed properly on your machine." }, { "code": null, "e": 1676, "s": 1611, "text": "You have gone through MySQL tutorial to understand MySQL Basics." }, { "code": null, "e": 1746, "s": 1676, "text": "Following is the example of connecting with MySQL database \"TESTDB\" −" }, { "code": null, "e": 1995, "s": 1746, "text": "#!/usr/bin/perl\nuse DBI\nuse strict;\nmy $driver = \"mysql\";\nmy $database = \"TESTDB\";\nmy $dsn = \"DBI:$driver:database=$database\";\nmy $userid = \"testuser\";\nmy $password = \"test123\";\nmy $dbh = DBI->connect($dsn, $userid, $password ) or die $DBI::errstr;" }, { "code": null, "e": 2189, "s": 1995, "text": "If a connection is established with the datasource then a Database Handle is returned and saved into dbhforfurtheruseotherwisedbh is set to undef value and $DBI::errstr returns an error string." }, { "code": null, "e": 2256, "s": 2189, "text": "To disconnect Database connection, use disconnect API as follows −" }, { "code": null, "e": 2301, "s": 2256, "text": "$rc = $dbh->disconnect or warn $dbh->errstr;" }, { "code": null, "e": 2647, "s": 2301, "text": "The transaction behaviour of the disconnect method is, sadly, undefined. Some database systems (such as Oracle and Ingres) will automatically commit any outstanding changes, but others (such as Informix) will rollback any outstanding changes. Applications not using AutoCommit should explicitly call commit or rollback before calling disconnect." } ]
CURDATE() Function in MySQL - GeeksforGeeks
23 Nov, 2020 CURDATE() function :This function in MySQL is used to return the current date. The date is returned to the format of “YYYY-MM-DD” (string) or as YYYYMMDD (numeric). This function equals the CURRENT_DATE() function. Syntax : CURDATE() Parameter : This method does not accept any parameter. Returns : It returns the current date. Example-1 : Getting the current date in the format of “YYYY-MM-DD” (string). SELECT CURDATE(); Output : 2020-11-19 Example-2 : Getting the date 1 day later than the current date in the format of YYYYMMDD (numeric). SELECT CURDATE() + 1; Output : 20201120 Example-3 : Getting the date of 5 days before of current date in the format of YYYYMMDD (numeric). SELECT CURDATE() + 5; Output : 20201114 Application : This function is used to get the current date or the specified number of days before or after the current date in the two different formats of “YYYY-MM-DD” (string) or as YYYYMMDD (numeric). DBMS-SQL mysql SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Update Multiple Columns in Single Update Statement in SQL? What is Temporary Table in SQL? SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter SQL using Python SQL | Subquery How to Write a SQL Query For a Specific Date Range and Date Time? SQL Query to Convert VARCHAR to INT SQL Query to Delete Duplicate Rows SQL Query to Compare Two Dates Window functions in SQL
[ { "code": null, "e": 23877, "s": 23849, "text": "\n23 Nov, 2020" }, { "code": null, "e": 24092, "s": 23877, "text": "CURDATE() function :This function in MySQL is used to return the current date. The date is returned to the format of “YYYY-MM-DD” (string) or as YYYYMMDD (numeric). This function equals the CURRENT_DATE() function." }, { "code": null, "e": 24101, "s": 24092, "text": "Syntax :" }, { "code": null, "e": 24112, "s": 24101, "text": "CURDATE()\n" }, { "code": null, "e": 24124, "s": 24112, "text": "Parameter :" }, { "code": null, "e": 24167, "s": 24124, "text": "This method does not accept any parameter." }, { "code": null, "e": 24177, "s": 24167, "text": "Returns :" }, { "code": null, "e": 24206, "s": 24177, "text": "It returns the current date." }, { "code": null, "e": 24218, "s": 24206, "text": "Example-1 :" }, { "code": null, "e": 24283, "s": 24218, "text": "Getting the current date in the format of “YYYY-MM-DD” (string)." }, { "code": null, "e": 24302, "s": 24283, "text": "SELECT CURDATE();\n" }, { "code": null, "e": 24311, "s": 24302, "text": "Output :" }, { "code": null, "e": 24323, "s": 24311, "text": "2020-11-19\n" }, { "code": null, "e": 24335, "s": 24323, "text": "Example-2 :" }, { "code": null, "e": 24423, "s": 24335, "text": "Getting the date 1 day later than the current date in the format of YYYYMMDD (numeric)." }, { "code": null, "e": 24446, "s": 24423, "text": "SELECT CURDATE() + 1;\n" }, { "code": null, "e": 24455, "s": 24446, "text": "Output :" }, { "code": null, "e": 24465, "s": 24455, "text": "20201120\n" }, { "code": null, "e": 24477, "s": 24465, "text": "Example-3 :" }, { "code": null, "e": 24564, "s": 24477, "text": "Getting the date of 5 days before of current date in the format of YYYYMMDD (numeric)." }, { "code": null, "e": 24587, "s": 24564, "text": "SELECT CURDATE() + 5;\n" }, { "code": null, "e": 24596, "s": 24587, "text": "Output :" }, { "code": null, "e": 24606, "s": 24596, "text": "20201114\n" }, { "code": null, "e": 24621, "s": 24606, "text": "Application : " }, { "code": null, "e": 24813, "s": 24621, "text": "This function is used to get the current date or the specified number of days before or after the current date in the two different formats of “YYYY-MM-DD” (string) or as YYYYMMDD (numeric). " }, { "code": null, "e": 24822, "s": 24813, "text": "DBMS-SQL" }, { "code": null, "e": 24828, "s": 24822, "text": "mysql" }, { "code": null, "e": 24832, "s": 24828, "text": "SQL" }, { "code": null, "e": 24836, "s": 24832, "text": "SQL" }, { "code": null, "e": 24934, "s": 24836, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 24943, "s": 24934, "text": "Comments" }, { "code": null, "e": 24956, "s": 24943, "text": "Old Comments" }, { "code": null, "e": 25022, "s": 24956, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 25054, "s": 25022, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 25132, "s": 25054, "text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter" }, { "code": null, "e": 25149, "s": 25132, "text": "SQL using Python" }, { "code": null, "e": 25164, "s": 25149, "text": "SQL | Subquery" }, { "code": null, "e": 25230, "s": 25164, "text": "How to Write a SQL Query For a Specific Date Range and Date Time?" }, { "code": null, "e": 25266, "s": 25230, "text": "SQL Query to Convert VARCHAR to INT" }, { "code": null, "e": 25301, "s": 25266, "text": "SQL Query to Delete Duplicate Rows" }, { "code": null, "e": 25332, "s": 25301, "text": "SQL Query to Compare Two Dates" } ]
How to make surfaceview transparent in an Android App?
This example demonstrates how to make surfaceview transparent in an Android App. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns: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"> <SurfaceView android:id="@+id/cameraSurface" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <ImageView android:id="@+id/IV_MASK" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/mask" android:background="@android:color/transparent"/> </RelativeLayout> Step 3 − Add the following code to src/MainActivity.java package com.app.sample; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } } Step 4 − Add the following code to Manifests/AndroidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.app.sample"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen − Click here to download the project code.
[ { "code": null, "e": 1143, "s": 1062, "text": "This example demonstrates how to make surfaceview transparent in an Android App." }, { "code": null, "e": 1272, "s": 1143, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1337, "s": 1272, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2050, "s": 1337, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:app=\"http://schemas.android.com/apk/res-auto\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <SurfaceView\n android:id=\"@+id/cameraSurface\"\n android:layout_width=\"fill_parent\"\n android:layout_height=\"wrap_content\" />\n <ImageView\n android:id=\"@+id/IV_MASK\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:src=\"@drawable/mask\"\n android:background=\"@android:color/transparent\"/>\n</RelativeLayout>" }, { "code": null, "e": 2107, "s": 2050, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 2424, "s": 2107, "text": "package com.app.sample;\nimport androidx.appcompat.app.AppCompatActivity;\nimport android.os.Bundle;\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n }\n}" }, { "code": null, "e": 2489, "s": 2424, "text": "Step 4 − Add the following code to Manifests/AndroidManifest.xml" }, { "code": null, "e": 3159, "s": 2489, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"com.app.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 3510, "s": 3159, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −" }, { "code": null, "e": 3551, "s": 3510, "text": "Click here to download the project code." } ]
How to count distinct values in MySQL?
To count distinct values, you can use distinct in aggregate function count(). The syntax is as follows − select count(distinct yourColumnName) as anyVariableName from yourTableName; To understand the above concept, let us create a table. The following is the query to create a table − mysql> create table DistinctDemo −> ( −> Name varchar(200) −> ); Query OK, 0 rows affected (0.58 sec) For our example, let us insert duplicate records in the table. The query to insert records is as follows − mysql> insert into DistinctDemo values('John'); Query OK, 1 row affected (0.15 sec) mysql> insert into DistinctDemo values('Sam'); Query OK, 1 row affected (0.17 sec) mysql> insert into DistinctDemo values('John'); Query OK, 1 row affected (0.12 sec) mysql> insert into DistinctDemo values('Johnson'); Query OK, 1 row affected (0.13 sec) mysql> insert into DistinctDemo values('John'); Query OK, 1 row affected (0.10 sec) mysql> insert into DistinctDemo values('Johnson'); Query OK, 1 row affected (0.12 sec) mysql> insert into DistinctDemo values('Sam'); Query OK, 1 row affected (0.14 sec) mysql> insert into DistinctDemo values('Johnson'); Query OK, 1 row affected (0.10 sec) Display all records with the help of select statement. The query to display all records is as follows − mysql> select *from DistinctDemo; The following is the output displaying some duplicate records − +---------+ | Name | +---------+ | John | | Sam | | John | | Johnson | | John | | Johnson | | Sam | | Johnson | +---------+ 8 rows in set (0.00 sec) Here is the query that can be used to count distinct values from the table − mysql> select count(distinct Name) as DistinctValues from DistinctDemo; The following is the output − +----------------+ | DistinctValues | +----------------+ | 3 | +----------------+ 1 row in set (0.01 sec) The result i3 tells that we have 3 distinct values in the table.
[ { "code": null, "e": 1140, "s": 1062, "text": "To count distinct values, you can use distinct in aggregate function count()." }, { "code": null, "e": 1167, "s": 1140, "text": "The syntax is as follows −" }, { "code": null, "e": 1244, "s": 1167, "text": "select count(distinct yourColumnName) as anyVariableName from yourTableName;" }, { "code": null, "e": 1347, "s": 1244, "text": "To understand the above concept, let us create a table. The following is the query to create a table −" }, { "code": null, "e": 1458, "s": 1347, "text": "mysql> create table DistinctDemo\n −> (\n −> Name varchar(200)\n −> );\nQuery OK, 0 rows affected (0.58 sec)" }, { "code": null, "e": 1565, "s": 1458, "text": "For our example, let us insert duplicate records in the table. The query to insert records is as follows −" }, { "code": null, "e": 2251, "s": 1565, "text": "mysql> insert into DistinctDemo values('John');\nQuery OK, 1 row affected (0.15 sec)\n\nmysql> insert into DistinctDemo values('Sam');\nQuery OK, 1 row affected (0.17 sec)\n\nmysql> insert into DistinctDemo values('John');\nQuery OK, 1 row affected (0.12 sec)\n\nmysql> insert into DistinctDemo values('Johnson');\nQuery OK, 1 row affected (0.13 sec)\n\nmysql> insert into DistinctDemo values('John');\nQuery OK, 1 row affected (0.10 sec)\n\nmysql> insert into DistinctDemo values('Johnson');\nQuery OK, 1 row affected (0.12 sec)\n\nmysql> insert into DistinctDemo values('Sam');\nQuery OK, 1 row affected (0.14 sec)\n\nmysql> insert into DistinctDemo values('Johnson');\nQuery OK, 1 row affected (0.10 sec)" }, { "code": null, "e": 2355, "s": 2251, "text": "Display all records with the help of select statement. The query to display all records is as follows −" }, { "code": null, "e": 2389, "s": 2355, "text": "mysql> select *from DistinctDemo;" }, { "code": null, "e": 2453, "s": 2389, "text": "The following is the output displaying some duplicate records −" }, { "code": null, "e": 2622, "s": 2453, "text": "+---------+\n| Name |\n+---------+\n| John |\n| Sam |\n| John |\n| Johnson |\n| John |\n| Johnson |\n| Sam |\n| Johnson |\n+---------+\n8 rows in set (0.00 sec)" }, { "code": null, "e": 2699, "s": 2622, "text": "Here is the query that can be used to count distinct values from the table −" }, { "code": null, "e": 2771, "s": 2699, "text": "mysql> select count(distinct Name) as DistinctValues from DistinctDemo;" }, { "code": null, "e": 2801, "s": 2771, "text": "The following is the output −" }, { "code": null, "e": 2920, "s": 2801, "text": "+----------------+\n| DistinctValues |\n+----------------+\n| 3 |\n+----------------+\n1 row in set (0.01 sec)" }, { "code": null, "e": 2985, "s": 2920, "text": "The result i3 tells that we have 3 distinct values in the table." } ]
Find the length of the median of a Triangle if length of sides are given - GeeksforGeeks
16 Jul, 2021 Given the length of all three sides of a triangle as a, b and c. The task is to calculate the length of the median of the triangle. A median of a triangle is a line segment joining a vertex to the midpoint of the opposite side, thus bisecting that side. Examples: Input: a = 8, b = 10, c = 13 Output: 10.89Input: a = 4, b = 3, c = 5 Output: 3.61 Approach: The idea is to use Apollonius’s theorem to solve this problem. Apollonius’s Theorem states that “the sum of the squares of any two sides of a triangle equals twice the square on half the third side and twice the square on the median bisecting the third side”. From the above figure, According to Apollonius’s Theorem we have: where a, b, and c are the length of sides of the triangle and m is the length of median of the triangle on side 2*a Therefore, the length of the median of a triangle from the above equation is given by: Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to find the length of the// median using sides of the triangle#include<bits/stdc++.h>using namespace std; // Function to return the length of// the median using sides of trianglefloat median(int a, int b, int c){ float n = sqrt(2 * b * b + 2 * c * c - a * a) / 2; return n;} // Driver codeint main(){ int a, b, c; a = 4; b = 3; c = 5; // Function call float ans = median(a, b, c); // Print final answer with 2 // digits after decimal cout << fixed << setprecision(2) << ans; return 0;} // This code is contributed by himanshu77 // Java program to find the length of the// median using sides of the triangleimport java.util.*; class GFG{ // Function to return the length of// the median using sides of trianglepublic static float median(int a, int b, int c){ float n = (float)(Math.sqrt(2 * b * b + 2 * c * c - a * a) / 2); return n;} // Driver codepublic static void main(String[] args){ int a, b, c; a = 4; b = 3; c = 5; // Function call float ans = median(a, b, c); // Print final answer with 2 // digits after decimal System.out.println(String.format("%.2f", ans));}} // This code is contributed by divyeshrabadiya07 # Python3 implementation to Find the# length of the median using sides# of the triangle import math # Function to return the length of# the median using sides of triangle.def median(a, b, c): n = (1 / 2)*math.sqrt(2*(b**2) + 2*(c**2) - a**2) return n # Driver Codea = 4b = 3c = 5 # Function Callans = median(a, b, c) # Print the final answerprint(round(ans, 2)) // C# program to find the length of the// median using sides of the triangleusing System; class GFG{ // Function to return the length of// the median using sides of trianglepublic static float median(int a, int b, int c){ float n = (float)(Math.Sqrt(2 * b * b + 2 * c * c - a * a) / 2); return n;} // Driver codepublic static void Main(String[] args){ int a, b, c; a = 4; b = 3; c = 5; // Function call float ans = median(a, b, c); // Print readonly answer with 2 // digits after decimal Console.WriteLine(String.Format("{0:F2}", ans));}} // This code is contributed by gauravrajput1 <script> // JavaScript program to find the length of the// median using sides of the triangle // Function to return the length of// the median using sides of trianglefunction median(a, b, c){ let n = (Math.sqrt(2 * b * b + 2 * c * c - a * a) / 2); return n;} // Driver Code let a, b, c; a = 4; b = 3; c = 5; // Function call let ans = median(a, b, c); // Print final answer with 2 // digits after decimal document.write(ans, 2); </script> 3.61 Time Complexity: O(1) Space Complexity: O(1) himanshu77 divyeshrabadiya07 GauravRajput1 splevel62 rajeev0719singh median-finding triangle Geometric Mathematical Mathematical Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Convex Hull using Divide and Conquer Algorithm Equation of circle when three points on the circle are given Orientation of 3 ordered points Circle and Lattice Points Program to find slope of a line 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": 25378, "s": 25350, "text": "\n16 Jul, 2021" }, { "code": null, "e": 25511, "s": 25378, "text": "Given the length of all three sides of a triangle as a, b and c. The task is to calculate the length of the median of the triangle. " }, { "code": null, "e": 25635, "s": 25511, "text": "A median of a triangle is a line segment joining a vertex to the midpoint of the opposite side, thus bisecting that side. " }, { "code": null, "e": 25647, "s": 25635, "text": "Examples: " }, { "code": null, "e": 25731, "s": 25647, "text": "Input: a = 8, b = 10, c = 13 Output: 10.89Input: a = 4, b = 3, c = 5 Output: 3.61 " }, { "code": null, "e": 25805, "s": 25731, "text": "Approach: The idea is to use Apollonius’s theorem to solve this problem. " }, { "code": null, "e": 26003, "s": 25805, "text": "Apollonius’s Theorem states that “the sum of the squares of any two sides of a triangle equals twice the square on half the third side and twice the square on the median bisecting the third side”. " }, { "code": null, "e": 26071, "s": 26003, "text": "From the above figure, According to Apollonius’s Theorem we have: " }, { "code": null, "e": 26191, "s": 26073, "text": "where a, b, and c are the length of sides of the triangle and m is the length of median of the triangle on side 2*a " }, { "code": null, "e": 26282, "s": 26193, "text": "Therefore, the length of the median of a triangle from the above equation is given by: " }, { "code": null, "e": 26335, "s": 26282, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 26339, "s": 26335, "text": "C++" }, { "code": null, "e": 26344, "s": 26339, "text": "Java" }, { "code": null, "e": 26352, "s": 26344, "text": "Python3" }, { "code": null, "e": 26355, "s": 26352, "text": "C#" }, { "code": null, "e": 26366, "s": 26355, "text": "Javascript" }, { "code": "// C++ program to find the length of the// median using sides of the triangle#include<bits/stdc++.h>using namespace std; // Function to return the length of// the median using sides of trianglefloat median(int a, int b, int c){ float n = sqrt(2 * b * b + 2 * c * c - a * a) / 2; return n;} // Driver codeint main(){ int a, b, c; a = 4; b = 3; c = 5; // Function call float ans = median(a, b, c); // Print final answer with 2 // digits after decimal cout << fixed << setprecision(2) << ans; return 0;} // This code is contributed by himanshu77", "e": 26965, "s": 26366, "text": null }, { "code": "// Java program to find the length of the// median using sides of the triangleimport java.util.*; class GFG{ // Function to return the length of// the median using sides of trianglepublic static float median(int a, int b, int c){ float n = (float)(Math.sqrt(2 * b * b + 2 * c * c - a * a) / 2); return n;} // Driver codepublic static void main(String[] args){ int a, b, c; a = 4; b = 3; c = 5; // Function call float ans = median(a, b, c); // Print final answer with 2 // digits after decimal System.out.println(String.format(\"%.2f\", ans));}} // This code is contributed by divyeshrabadiya07", "e": 27658, "s": 26965, "text": null }, { "code": "# Python3 implementation to Find the# length of the median using sides# of the triangle import math # Function to return the length of# the median using sides of triangle.def median(a, b, c): n = (1 / 2)*math.sqrt(2*(b**2) + 2*(c**2) - a**2) return n # Driver Codea = 4b = 3c = 5 # Function Callans = median(a, b, c) # Print the final answerprint(round(ans, 2))", "e": 28032, "s": 27658, "text": null }, { "code": "// C# program to find the length of the// median using sides of the triangleusing System; class GFG{ // Function to return the length of// the median using sides of trianglepublic static float median(int a, int b, int c){ float n = (float)(Math.Sqrt(2 * b * b + 2 * c * c - a * a) / 2); return n;} // Driver codepublic static void Main(String[] args){ int a, b, c; a = 4; b = 3; c = 5; // Function call float ans = median(a, b, c); // Print readonly answer with 2 // digits after decimal Console.WriteLine(String.Format(\"{0:F2}\", ans));}} // This code is contributed by gauravrajput1", "e": 28717, "s": 28032, "text": null }, { "code": "<script> // JavaScript program to find the length of the// median using sides of the triangle // Function to return the length of// the median using sides of trianglefunction median(a, b, c){ let n = (Math.sqrt(2 * b * b + 2 * c * c - a * a) / 2); return n;} // Driver Code let a, b, c; a = 4; b = 3; c = 5; // Function call let ans = median(a, b, c); // Print final answer with 2 // digits after decimal document.write(ans, 2); </script>", "e": 29273, "s": 28717, "text": null }, { "code": null, "e": 29278, "s": 29273, "text": "3.61" }, { "code": null, "e": 29327, "s": 29280, "text": "Time Complexity: O(1) Space Complexity: O(1) " }, { "code": null, "e": 29338, "s": 29327, "text": "himanshu77" }, { "code": null, "e": 29356, "s": 29338, "text": "divyeshrabadiya07" }, { "code": null, "e": 29370, "s": 29356, "text": "GauravRajput1" }, { "code": null, "e": 29380, "s": 29370, "text": "splevel62" }, { "code": null, "e": 29396, "s": 29380, "text": "rajeev0719singh" }, { "code": null, "e": 29411, "s": 29396, "text": "median-finding" }, { "code": null, "e": 29420, "s": 29411, "text": "triangle" }, { "code": null, "e": 29430, "s": 29420, "text": "Geometric" }, { "code": null, "e": 29443, "s": 29430, "text": "Mathematical" }, { "code": null, "e": 29456, "s": 29443, "text": "Mathematical" }, { "code": null, "e": 29466, "s": 29456, "text": "Geometric" }, { "code": null, "e": 29564, "s": 29466, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29611, "s": 29564, "text": "Convex Hull using Divide and Conquer Algorithm" }, { "code": null, "e": 29672, "s": 29611, "text": "Equation of circle when three points on the circle are given" }, { "code": null, "e": 29704, "s": 29672, "text": "Orientation of 3 ordered points" }, { "code": null, "e": 29730, "s": 29704, "text": "Circle and Lattice Points" }, { "code": null, "e": 29762, "s": 29730, "text": "Program to find slope of a line" }, { "code": null, "e": 29792, "s": 29762, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 29852, "s": 29792, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 29867, "s": 29852, "text": "C++ Data Types" }, { "code": null, "e": 29910, "s": 29867, "text": "Set in C++ Standard Template Library (STL)" } ]
EmberJS - Router
This is the core feature of the Ember.js. The router used for to translate URL into the series of templates and also it represents the state of an application. The Ember.js uses the HashChange event that helps to know change of route; this can be done by implementing HashLocation object. As an application grows in complexity, the logging route keeps track of the router. ENV.APP.LOG_TRANSITIONS = true; The above code translates transition events to the log modifier. If the Ember.js domains have the multiple web application, In that case you need to specify the root URL to indicate the router. Ember.Router.extend({ rootURL: 'Path' }); The above code describes how to specify the root URL. The 'path' is root URL path. The router matches the current URL with routes which is responsible for displaying template, loading data and setting up an application state. The map method router is used for to define the URL mapping which passes a function that takes parameter as an object to create the routes. The {{ link-to }} helper navigates the router. Router.map(function() { this.route('link-page', { path: '/PathTolinkpage' }); . . this.route('link-page', { path: '/PathTolinkpage' }); }); The above code describes how to link the different pages by using the router map. It takes linkpage name and path as an argument. <!DOCTYPE html> <html> <head> <title>Emberjs Router</title> <!-- CDN's--> <script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/3.0.1/handlebars.min.js"></script> <script src="https://code.jquery.com/jquery-2.1.3.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/ember.js/1.10.0/ember.min.js"></script> <script src="https://builds.emberjs.com/tags/v1.10.0-beta.3/ember-template-compiler.js"></script> <script src="https://builds.emberjs.com/release/ember.debug.js"></script> <script src="https://builds.emberjs.com/beta/ember-data.js"></script> </head> <body> <script type="text/x-handlebars" data-template-name="application"> <!-- link-to for navigation between the routes --> <p>{{#link-to 'authors'}}Click for AuthorInfo{{/link-to}}</p> <p>{{#link-to 'books'}}Click for BookInfo{{/link-to}}</p> {{outlet}} </script> <script type="text/x-handlebars" data-template-name="authors"> <h2>Authors Page </h2> <ul> <li>Herbert Schildt</li> <li>Robert Lafore</li> </ul> </script> <script type="text/x-handlebars" data-template-name="books"> <h2>Books Page</h2> <ul> <li>Java</li> <li>C++</li> </ul> </script> <script type="text/javascript"> App = Ember.Application.create(); App.Router.map(function() { //refers to the authors template and path refers within page this.route('authors', { path: '/' }); //refers to the books template this.route('books'); }); </script> </body> </html> Let's carry out the following steps to see how above code works − Save above code in routing.htm file Save above code in routing.htm file Open this HTML file in a browser. Open this HTML file in a browser. The following table shows properties of the router − Nested Routes This shows how to define the nested routes. Dynamic Segments The dynamic segment is part of an URL. Wildcard/Globbing Routes Wildcard routes used for matching the multiple routes. If you have not define Route, Controller, View, and Template classes objects, then Ember.js will automatically generates these objects into your application. The Ember.js will automatically generate the route if you are not defined in your application. The Ember.js will automatically generate the controller for the appropriate route, if it is not defined in your application. The Ember.js will automatically generate the view if it is not defined in your application. The template is nothing but outlet. If you have not declare the outlet then Ember.js will automatically generates {{outlet}} within template. To specify a routes model, you need to define the template name in the route which is same name as the data-template and implement its model hook. Ember.Route.extend({ model: function() { return { //value-1 },{ //value-2 },{..},{ //value-n }; } }); In the above code, value-1 to value-n variables is used to store the values which are being called in the template. <!DOCTYPE html> <html> <head> <title>Emberjs Specifying a Route's Model</title> <!-- CDN's--> <script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/3.0.1/handlebars.min.js"></script> <script src="https://code.jquery.com/jquery-2.1.3.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/ember.js/1.10.0/ember.min.js"></script> <script src="https://builds.emberjs.com/tags/v1.10.0-beta.3/ember-template-compiler.js"></script> <script src="https://builds.emberjs.com/release/ember.debug.js"></script> <script src="https://builds.emberjs.com/beta/ember-data.js"></script> </head> <body> <script type="text/x-handlebars" data-template-name="books"> <h2> {{title}} </h2> <ul> <li><p>Java</p></li> <li><p>DBMS</p></li> </ul> </script> <script type="text/javascript"> App = Ember.Application.create(); App.Router.map(function(){ //refers to the books template this.route('books'); }); App.BooksRoute = Ember.Route.extend({ //model is redering title of the page model: function() { return { title: 'Redirecting to Books Page.....' } } }); App.IndexRoute = Ember.Route.extend({ redirect: function() { //redirects to books page this.transitionTo('books'); } }); </script> </body> </html> Let's carry out the following steps to see how above code works − Save above code in routing_spfng_rout_model.htm file Save above code in routing_spfng_rout_model.htm file Open this HTML file in a browser. Open this HTML file in a browser. The following table shows how to specify the router models − In Ember.js it is necessary to set up the controller that helps the template to display the retrieved information. Ember.js supports two built-in controllers Ember.ObjectController and Ember.ArrayController. These are presents a model's properties to a template, along with any additional display-specific properties. Set up the model property to know which model to present, this can be done by using the route handler's setupController hook. The setupController hook gets first argument as a route handler's associated controller. You can also set the route's controllerName property other than default. Ember.Route.extend({ setupController: function(controller, model) { controller.set('model', model); } }); In the above code, sets the model property in the route handler's setupController hook. <!DOCTYPE html> <html> <head> <title>Emberjs Setting up a Controller</title> <!-- CDN's--> <script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/3.0.1/handlebars.min.js"></script> <script src="https://code.jquery.com/jquery-2.1.3.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/ember.js/1.10.0/ember.min.js"></script> <script src="https://builds.emberjs.com/tags/v1.10.0-beta.3/ember-template-compiler.js"></script> <script src="https://builds.emberjs.com/release/ember.debug.js"></script> <script src="https://builds.emberjs.com/beta/ember-data.js"></script> </head> <body> <script type="text/x-handlebars" data-template-name="application"> {{outlet}} </script> <script type="text/x-handlebars" data-template-name="index"> <!--using the default controller as index> <b>Employee Details</b> {{#each}} <p>{{index}}. {{empDetails}}</p> {{/each}} </script> <script type="text/javascript"> App = Ember.Application.create({}); App.IndexRoute = Ember.Route.extend({ //Setting up the model property model: function(){ //declaring the array values return [ {firstName: 'Mack', lastName: 'KK'}, {firstName: 'Micky', lastName: 'SK'}, {firstName: 'Smith', lastName: 'KD'} ]; } }); App.IndexController = Ember.ArrayController.extend({ //define name of the array controller itemController:'name' }); App.NameController = Ember.ObjectController.extend({ //Defining the computed property empDetails, that holds firstName and lastName as values empDetails: function(){ //returning the computed property values return this.get('firstName')+ ' . ' + this.get('lastName'); }.property('firstName', 'lastName'), //Defining the computed property index, that holds an array index values index: function(){ //defining the array index as target to get an index values of an array return this.get('target').indexOf(this); }.property('target.[]') }); </script> </body> </html> Let's carry out the following steps to see how above code works − Save above code in routing_cntrler.htm file Save above code in routing_cntrler.htm file Open this HTML file in a browser. Open this HTML file in a browser. The route are used to render the external template to the screen. This can be achieved by defining renderTemplate hook in the route handler. You can also use different controller other than the route handler controller by specifying the controller name in the controller option. Ember.Route.extend({ renderTemplate: function() { this.render('templateName'); } }); In the above code, route handler renders the template named as templateName by using the renderTemplatehook. <!DOCTYPE html> <html> <head> <title>Emberjs Rendering a Template</title> <!-- CDN's--> <script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/3.0.1/handlebars.min.js"></script> <script src="https://code.jquery.com/jquery-2.1.3.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/ember.js/1.10.0/ember.min.js"></script> <script src="https://builds.emberjs.com/tags/v1.10.0-beta.3/ember-template-compiler.js"></script> <script src="https://builds.emberjs.com/release/ember.debug.js"></script> <script src="https://builds.emberjs.com/beta/ember-data.js"></script> </head> <body> <h1>Rendering The Template</h1> <div id="divApp1"></div> <script type="text/x-handlebars" data-template-name="index"> <p>Rendering Latest News Template :</p> {{#link-to "details"}}Get The Latest News{{/link-to}} <hr/> <h2>HOME</h2> </script> <script type="text/x-handlebars" data-template-name="details"> {{outlet "NewsTempl"}} </script> <script type="text/x-handlebars" data-template-name="NewsTempl"> <hr/> <h2>Reporting The News...!</h2> </script> <script type="text/javascript"> //rootElement is parent element to all the other elements. App = Ember.Application.create({ rootElement: "#divApp1" }); App.Router.map(function () { this.route('index', { path: '/' }); //specifying the path for template this.route('details', { path: '/details' }); }); App.DetailsRoute = Ember.Route.extend({ renderTemplate: function () { //render the temlate which has outlets this._super(); //rendet the News in NewsTempl outlet this.render('NewsTempl', { outlet: 'NewsTempl' }); } }); </script> </body> </html> Let's carry out the following steps to see how above code works − Save above code in routing_rndr_templ.htm file Save above code in routing_rndr_templ.htm file Open this HTML file in a browser. Open this HTML file in a browser. This is an URL redirection or forwarding mechanism, that makes a web page available for more than one URL address. Ember.js defines transitionTo or transitionToRoute from a route and controller, this stops the currently running transition and start a new transition of a page. The transitionTo behaves like the link-to helper. The following table shows properties of the transitioning and redirecting: Before the Model is Known Redirect from one route to another. After the Model is Known Getting an information about the current model of redirection. Based on other Application State Conditionally transitioning based on some other application state. The router also uses the browser's history API to locate the pages that are used before. You can also disable the location API. Ember.Router.extend({ location: 'history' }); In the above code the Router uses the browser's history API. <!DOCTYPE html> <html> <head> <title>Emberjs Specifying the URL Type</title> <!-- CDN's--> <script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/3.0.1/handlebars.min.js"></script> <script src="https://code.jquery.com/jquery-2.1.3.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/ember.js/1.10.0/ember.min.js"></script> <script src="https://builds.emberjs.com/tags/v1.10.0-beta.3/ember-template-compiler.js"></script> <script src="https://builds.emberjs.com/release/ember.debug.js"></script> <script src="https://builds.emberjs.com/beta/ember-data.js"></script> </head> <body> <script type="text/x-handlebars" data-template-name="application"> //link-to for navigation between the routes {{#link-to 'authors'}}AuthorInfo{{/link-to}} {{#link-to 'books'}}BookInfo{{/link-to}} {{outlet}} </script> <script type="text/x-handlebars" data-template-name="authors"> <h2>Click for AuthorsInfo </h2> <ul> <li>Herbert Schildt</li> <li>Robert Lafore</li> </ul> </script> <script type="text/x-handlebars" data-template-name="books"> <h2>Click for BooksInfo</h2> <ul> <li>Java</li> <li>C++</li> </ul> </script> <script type="text/javascript"> App = Ember.Application.create(); App.Router.map(function() { //refers to the authors template and path refers within page this.route('authors', { path: '/' }); //refers to the books template this.route('books'); }); Ember.Router.extend({ //getting the history of the pages are searched before location: 'history' }); </script> </body> </html> Let's carry out the following steps to see how above code works − Save above code in routing_history.htm file Save above code in routing_history.htm file Open this HTML file in a browser. Open this HTML file in a browser. Query parameters appear to the right of the ? in a URL. It is represented as optional key-value pairs. For example URL http:.../articles?sort=ASC&page=2 has the two query parameter sort and page which contains values ASC and 2 respectively. The following table shows properties of the query parameters − Specifying Query Parameters Query parameters are specifiied on route-driven controllers. Opting Into a Full Transition When a controller query parameter property changes it opt into a full transition. Update URL with Replacestate Instead It prevents from adding an item to your browser's history. Map a Controller's Property to a Different Query Param Key Mapping a controller property to a different query param key. Default Values and Deserialization Specifying the default values to the query parameter. Sticky Query Param Values The query parameter are sticky so changes in the parameter will be preserved. The Ember.js router is capable for handling complex async logic within an application. The following table shows properties of the asynchronous routing: The Router Pauses for Promises The router considers a then method with any object, is defined to be a promise. When Promises Reject The promise rejects during a transition, the transition will be aborted. Recovering from Rejection Recovering from the aborted transition. The Ember.js overrides transitions for customizing asynchronization between the routes by making use of error and loading substates. The following table shows properties of the loading/error substates − loading Substates Ember.js has loading process that implements the loading substate behavior. error Substates The error handlers will looks for an error substate to be entered into an application. The transition.abort() and transition.retry() methods are called to abort and retry the transition respectively this cause because of failure of the transition object. The following table shows properties of the preventing and retrying transitions: Preventing Transitions Via willTransition This fires the willTransition action for currently active routes. Aborting Transitions Within model, beforeModel, afterModel The destination routes makes an attempted transitions to abort. Storing and Retrying a Transition You can also re-attempt on aborted transition. Print Add Notes Bookmark this page
[ { "code": null, "e": 2187, "s": 1898, "text": "This is the core feature of the Ember.js. The router used for to translate URL into the series of templates and also it represents the state of an application. The Ember.js uses the HashChange event that helps to know change of route; this can be done by implementing HashLocation object." }, { "code": null, "e": 2271, "s": 2187, "text": "As an application grows in complexity, the logging route keeps track of the router." }, { "code": null, "e": 2303, "s": 2271, "text": "ENV.APP.LOG_TRANSITIONS = true;" }, { "code": null, "e": 2368, "s": 2303, "text": "The above code translates transition events to the log modifier." }, { "code": null, "e": 2497, "s": 2368, "text": "If the Ember.js domains have the multiple web application, In that case you need to specify the root URL to indicate the router." }, { "code": null, "e": 2542, "s": 2497, "text": "Ember.Router.extend({\n rootURL: 'Path'\n});" }, { "code": null, "e": 2625, "s": 2542, "text": "The above code describes how to specify the root URL. The 'path' is root URL path." }, { "code": null, "e": 2955, "s": 2625, "text": "The router matches the current URL with routes which is responsible for displaying template, loading data and setting up an application state. The map method router is used for to define the URL mapping which passes a function that takes parameter as an object to create the routes. The {{ link-to }} helper navigates the router." }, { "code": null, "e": 3107, "s": 2955, "text": "Router.map(function() {\n this.route('link-page', { path: '/PathTolinkpage' });\n .\n .\n this.route('link-page', { path: '/PathTolinkpage' });\n});" }, { "code": null, "e": 3237, "s": 3107, "text": "The above code describes how to link the different pages by using the router map. It takes linkpage name and path as an argument." }, { "code": null, "e": 4971, "s": 3237, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Emberjs Router</title>\n <!-- CDN's-->\n <script src=\"https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/3.0.1/handlebars.min.js\"></script>\n <script src=\"https://code.jquery.com/jquery-2.1.3.min.js\"></script>\n <script src=\"https://cdnjs.cloudflare.com/ajax/libs/ember.js/1.10.0/ember.min.js\"></script>\n <script src=\"https://builds.emberjs.com/tags/v1.10.0-beta.3/ember-template-compiler.js\"></script>\n <script src=\"https://builds.emberjs.com/release/ember.debug.js\"></script>\n <script src=\"https://builds.emberjs.com/beta/ember-data.js\"></script>\n </head>\n <body>\n <script type=\"text/x-handlebars\" data-template-name=\"application\">\n <!-- link-to for navigation between the routes -->\n <p>{{#link-to 'authors'}}Click for AuthorInfo{{/link-to}}</p>\n <p>{{#link-to 'books'}}Click for BookInfo{{/link-to}}</p>\n {{outlet}}\n </script>\n\n <script type=\"text/x-handlebars\" data-template-name=\"authors\">\n <h2>Authors Page </h2>\n <ul>\n <li>Herbert Schildt</li>\n <li>Robert Lafore</li>\n </ul>\n </script>\n\n <script type=\"text/x-handlebars\" data-template-name=\"books\">\n <h2>Books Page</h2>\n <ul>\n <li>Java</li>\n <li>C++</li>\n </ul>\n </script>\n\n <script type=\"text/javascript\">\n App = Ember.Application.create();\n\n App.Router.map(function() {\n //refers to the authors template and path refers within page\n this.route('authors', { path: '/' });\n //refers to the books template\n this.route('books');\n });\n </script>\n </body>\n</html>" }, { "code": null, "e": 5037, "s": 4971, "text": "Let's carry out the following steps to see how above code works −" }, { "code": null, "e": 5073, "s": 5037, "text": "Save above code in routing.htm file" }, { "code": null, "e": 5109, "s": 5073, "text": "Save above code in routing.htm file" }, { "code": null, "e": 5144, "s": 5109, "text": "Open this HTML file in a browser." }, { "code": null, "e": 5179, "s": 5144, "text": "Open this HTML file in a browser." }, { "code": null, "e": 5232, "s": 5179, "text": "The following table shows properties of the router −" }, { "code": null, "e": 5246, "s": 5232, "text": "Nested Routes" }, { "code": null, "e": 5290, "s": 5246, "text": "This shows how to define the nested routes." }, { "code": null, "e": 5307, "s": 5290, "text": "Dynamic Segments" }, { "code": null, "e": 5346, "s": 5307, "text": "The dynamic segment is part of an URL." }, { "code": null, "e": 5371, "s": 5346, "text": "Wildcard/Globbing Routes" }, { "code": null, "e": 5426, "s": 5371, "text": "Wildcard routes used for matching the multiple routes." }, { "code": null, "e": 5584, "s": 5426, "text": "If you have not define Route, Controller, View, and Template classes objects, then Ember.js will automatically generates these objects into your application." }, { "code": null, "e": 5679, "s": 5584, "text": "The Ember.js will automatically generate the route if you are not defined in your application." }, { "code": null, "e": 5804, "s": 5679, "text": "The Ember.js will automatically generate the controller for the appropriate route, if it is not defined in your application." }, { "code": null, "e": 6038, "s": 5804, "text": "The Ember.js will automatically generate the view if it is not defined in your application. The template is nothing but outlet. If you have not declare the outlet then Ember.js will automatically generates {{outlet}} within template." }, { "code": null, "e": 6185, "s": 6038, "text": "To specify a routes model, you need to define the template name in the route which is same name as the data-template and implement its model hook." }, { "code": null, "e": 6299, "s": 6185, "text": "Ember.Route.extend({\n model: function() {\n return { //value-1 },{ //value-2 },{..},{ //value-n };\n }\n});" }, { "code": null, "e": 6415, "s": 6299, "text": "In the above code, value-1 to value-n variables is used to store the values which are being called in the template." }, { "code": null, "e": 7952, "s": 6415, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Emberjs Specifying a Route's Model</title>\n <!-- CDN's-->\n <script src=\"https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/3.0.1/handlebars.min.js\"></script>\n <script src=\"https://code.jquery.com/jquery-2.1.3.min.js\"></script>\n <script src=\"https://cdnjs.cloudflare.com/ajax/libs/ember.js/1.10.0/ember.min.js\"></script>\n <script src=\"https://builds.emberjs.com/tags/v1.10.0-beta.3/ember-template-compiler.js\"></script>\n <script src=\"https://builds.emberjs.com/release/ember.debug.js\"></script>\n <script src=\"https://builds.emberjs.com/beta/ember-data.js\"></script>\n </head>\n <body>\n <script type=\"text/x-handlebars\" data-template-name=\"books\">\n <h2> {{title}} </h2>\n <ul>\n <li><p>Java</p></li>\n <li><p>DBMS</p></li>\n </ul>\n </script>\n\n <script type=\"text/javascript\">\n App = Ember.Application.create();\n\n App.Router.map(function(){\n //refers to the books template\n this.route('books');\n });\n\n App.BooksRoute = Ember.Route.extend({\n //model is redering title of the page\n model: function() {\n return { title: 'Redirecting to Books Page.....' }\n }\n });\n\n App.IndexRoute = Ember.Route.extend({\n redirect: function() {\n //redirects to books page\n this.transitionTo('books');\n }\n });\n </script>\n </body>\n</html>" }, { "code": null, "e": 8018, "s": 7952, "text": "Let's carry out the following steps to see how above code works −" }, { "code": null, "e": 8071, "s": 8018, "text": "Save above code in routing_spfng_rout_model.htm file" }, { "code": null, "e": 8124, "s": 8071, "text": "Save above code in routing_spfng_rout_model.htm file" }, { "code": null, "e": 8159, "s": 8124, "text": "Open this HTML file in a browser." }, { "code": null, "e": 8194, "s": 8159, "text": "Open this HTML file in a browser." }, { "code": null, "e": 8255, "s": 8194, "text": "The following table shows how to specify the router models −" }, { "code": null, "e": 8573, "s": 8255, "text": "In Ember.js it is necessary to set up the controller that helps the template to display the retrieved information. Ember.js supports two built-in controllers Ember.ObjectController and Ember.ArrayController. These are presents a model's properties to a template, along with any additional display-specific properties." }, { "code": null, "e": 8861, "s": 8573, "text": "Set up the model property to know which model to present, this can be done by using the route handler's setupController hook. The setupController hook gets first argument as a route handler's associated controller. You can also set the route's controllerName property other than default." }, { "code": null, "e": 8979, "s": 8861, "text": "Ember.Route.extend({\n setupController: function(controller, model) {\n controller.set('model', model);\n }\n});" }, { "code": null, "e": 9067, "s": 8979, "text": "In the above code, sets the model property in the route handler's setupController hook." }, { "code": null, "e": 11464, "s": 9067, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Emberjs Setting up a Controller</title>\n <!-- CDN's-->\n <script src=\"https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/3.0.1/handlebars.min.js\"></script>\n <script src=\"https://code.jquery.com/jquery-2.1.3.min.js\"></script>\n <script src=\"https://cdnjs.cloudflare.com/ajax/libs/ember.js/1.10.0/ember.min.js\"></script>\n <script src=\"https://builds.emberjs.com/tags/v1.10.0-beta.3/ember-template-compiler.js\"></script>\n <script src=\"https://builds.emberjs.com/release/ember.debug.js\"></script>\n <script src=\"https://builds.emberjs.com/beta/ember-data.js\"></script>\n </head>\n <body>\n <script type=\"text/x-handlebars\" data-template-name=\"application\">\n {{outlet}}\n </script>\n\n <script type=\"text/x-handlebars\" data-template-name=\"index\">\n <!--using the default controller as index>\n <b>Employee Details</b>\n {{#each}}\n <p>{{index}}. {{empDetails}}</p>\n {{/each}}\n </script>\n\n <script type=\"text/javascript\">\n App = Ember.Application.create({});\n\n App.IndexRoute = Ember.Route.extend({\n //Setting up the model property\n model: function(){\n //declaring the array values\n return [\n {firstName: 'Mack', lastName: 'KK'},\n {firstName: 'Micky', lastName: 'SK'},\n {firstName: 'Smith', lastName: 'KD'}\n ];\n }\n });\n\n App.IndexController = Ember.ArrayController.extend({\n //define name of the array controller\n itemController:'name'\n });\n\n App.NameController = Ember.ObjectController.extend({\n //Defining the computed property empDetails, that holds firstName and lastName as values\n empDetails: function(){\n //returning the computed property values\n return this.get('firstName')+ ' . ' + this.get('lastName');\n }.property('firstName', 'lastName'),\n\n //Defining the computed property index, that holds an array index values\n index: function(){\n //defining the array index as target to get an index values of an array\n return this.get('target').indexOf(this);\n }.property('target.[]')\n });\n </script>\n </body>\n</html>" }, { "code": null, "e": 11530, "s": 11464, "text": "Let's carry out the following steps to see how above code works −" }, { "code": null, "e": 11574, "s": 11530, "text": "Save above code in routing_cntrler.htm file" }, { "code": null, "e": 11618, "s": 11574, "text": "Save above code in routing_cntrler.htm file" }, { "code": null, "e": 11653, "s": 11618, "text": "Open this HTML file in a browser." }, { "code": null, "e": 11688, "s": 11653, "text": "Open this HTML file in a browser." }, { "code": null, "e": 11967, "s": 11688, "text": "The route are used to render the external template to the screen. This can be achieved by defining renderTemplate hook in the route handler. You can also use different controller other than the route handler controller by specifying the controller name in the controller option." }, { "code": null, "e": 12064, "s": 11967, "text": "Ember.Route.extend({\n renderTemplate: function() {\n this.render('templateName');\n }\n});" }, { "code": null, "e": 12173, "s": 12064, "text": "In the above code, route handler renders the template named as templateName by using the renderTemplatehook." }, { "code": null, "e": 14139, "s": 12173, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Emberjs Rendering a Template</title>\n <!-- CDN's-->\n <script src=\"https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/3.0.1/handlebars.min.js\"></script>\n <script src=\"https://code.jquery.com/jquery-2.1.3.min.js\"></script>\n <script src=\"https://cdnjs.cloudflare.com/ajax/libs/ember.js/1.10.0/ember.min.js\"></script>\n <script src=\"https://builds.emberjs.com/tags/v1.10.0-beta.3/ember-template-compiler.js\"></script>\n <script src=\"https://builds.emberjs.com/release/ember.debug.js\"></script>\n <script src=\"https://builds.emberjs.com/beta/ember-data.js\"></script>\n </head>\n <body>\n <h1>Rendering The Template</h1>\n <div id=\"divApp1\"></div>\n\n <script type=\"text/x-handlebars\" data-template-name=\"index\">\n <p>Rendering Latest News Template :</p>\n {{#link-to \"details\"}}Get The Latest News{{/link-to}}\n <hr/>\n <h2>HOME</h2>\n </script>\n\n <script type=\"text/x-handlebars\" data-template-name=\"details\">\n {{outlet \"NewsTempl\"}}\n </script>\n\n <script type=\"text/x-handlebars\" data-template-name=\"NewsTempl\">\n <hr/>\n <h2>Reporting The News...!</h2>\n </script>\n\n <script type=\"text/javascript\">\n //rootElement is parent element to all the other elements.\n App = Ember.Application.create({ rootElement: \"#divApp1\" });\n\n App.Router.map(function () {\n this.route('index', { path: '/' });\n //specifying the path for template\n this.route('details', { path: '/details' });\n });\n\n App.DetailsRoute = Ember.Route.extend({\n renderTemplate: function () {\n //render the temlate which has outlets\n this._super();\n //rendet the News in NewsTempl outlet\n this.render('NewsTempl', { outlet: 'NewsTempl' });\n }\n });\n </script>\n </body>\n</html>" }, { "code": null, "e": 14205, "s": 14139, "text": "Let's carry out the following steps to see how above code works −" }, { "code": null, "e": 14252, "s": 14205, "text": "Save above code in routing_rndr_templ.htm file" }, { "code": null, "e": 14299, "s": 14252, "text": "Save above code in routing_rndr_templ.htm file" }, { "code": null, "e": 14334, "s": 14299, "text": "Open this HTML file in a browser." }, { "code": null, "e": 14369, "s": 14334, "text": "Open this HTML file in a browser." }, { "code": null, "e": 14484, "s": 14369, "text": "This is an URL redirection or forwarding mechanism, that makes a web page available for more than one URL address." }, { "code": null, "e": 14696, "s": 14484, "text": "Ember.js defines transitionTo or transitionToRoute from a route and controller, this stops the currently running transition and start a new transition of a page. The transitionTo behaves like the link-to helper." }, { "code": null, "e": 14771, "s": 14696, "text": "The following table shows properties of the transitioning and redirecting:" }, { "code": null, "e": 14797, "s": 14771, "text": "Before the Model is Known" }, { "code": null, "e": 14833, "s": 14797, "text": "Redirect from one route to another." }, { "code": null, "e": 14858, "s": 14833, "text": "After the Model is Known" }, { "code": null, "e": 14921, "s": 14858, "text": "Getting an information about the current model of redirection." }, { "code": null, "e": 14954, "s": 14921, "text": "Based on other Application State" }, { "code": null, "e": 15021, "s": 14954, "text": "Conditionally transitioning based on some other application state." }, { "code": null, "e": 15149, "s": 15021, "text": "The router also uses the browser's history API to locate the pages that are used before. You can also disable the location API." }, { "code": null, "e": 15198, "s": 15149, "text": "Ember.Router.extend({\n location: 'history'\n});" }, { "code": null, "e": 15259, "s": 15198, "text": "In the above code the Router uses the browser's history API." }, { "code": null, "e": 17132, "s": 15259, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Emberjs Specifying the URL Type</title>\n <!-- CDN's-->\n <script src=\"https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/3.0.1/handlebars.min.js\"></script>\n <script src=\"https://code.jquery.com/jquery-2.1.3.min.js\"></script>\n <script src=\"https://cdnjs.cloudflare.com/ajax/libs/ember.js/1.10.0/ember.min.js\"></script>\n <script src=\"https://builds.emberjs.com/tags/v1.10.0-beta.3/ember-template-compiler.js\"></script>\n <script src=\"https://builds.emberjs.com/release/ember.debug.js\"></script>\n <script src=\"https://builds.emberjs.com/beta/ember-data.js\"></script>\n </head>\n <body>\n <script type=\"text/x-handlebars\" data-template-name=\"application\">\n //link-to for navigation between the routes\n {{#link-to 'authors'}}AuthorInfo{{/link-to}}\n {{#link-to 'books'}}BookInfo{{/link-to}}\n {{outlet}}\n </script>\n\n <script type=\"text/x-handlebars\" data-template-name=\"authors\">\n <h2>Click for AuthorsInfo </h2>\n <ul>\n <li>Herbert Schildt</li>\n <li>Robert Lafore</li>\n </ul>\n </script>\n\n <script type=\"text/x-handlebars\" data-template-name=\"books\">\n <h2>Click for BooksInfo</h2>\n <ul>\n <li>Java</li>\n <li>C++</li>\n </ul>\n </script>\n\n <script type=\"text/javascript\">\n App = Ember.Application.create();\n\n App.Router.map(function() {\n //refers to the authors template and path refers within page\n this.route('authors', { path: '/' });\n //refers to the books template\n this.route('books');\n });\n\n Ember.Router.extend({\n //getting the history of the pages are searched before\n location: 'history'\n });\n </script>\n </body>\n</html>" }, { "code": null, "e": 17198, "s": 17132, "text": "Let's carry out the following steps to see how above code works −" }, { "code": null, "e": 17242, "s": 17198, "text": "Save above code in routing_history.htm file" }, { "code": null, "e": 17286, "s": 17242, "text": "Save above code in routing_history.htm file" }, { "code": null, "e": 17321, "s": 17286, "text": "Open this HTML file in a browser." }, { "code": null, "e": 17356, "s": 17321, "text": "Open this HTML file in a browser." }, { "code": null, "e": 17599, "s": 17356, "text": "Query parameters appear to the right of the ? in a URL. It is represented as optional key-value pairs. For example URL http:.../articles?sort=ASC&page=2 has the two query parameter sort and page which contains values ASC and 2 respectively." }, { "code": null, "e": 17662, "s": 17599, "text": "The following table shows properties of the query parameters −" }, { "code": null, "e": 17690, "s": 17662, "text": "Specifying Query Parameters" }, { "code": null, "e": 17751, "s": 17690, "text": "Query parameters are specifiied on route-driven controllers." }, { "code": null, "e": 17781, "s": 17751, "text": "Opting Into a Full Transition" }, { "code": null, "e": 17863, "s": 17781, "text": "When a controller query parameter property changes it opt into a full transition." }, { "code": null, "e": 17900, "s": 17863, "text": "Update URL with Replacestate Instead" }, { "code": null, "e": 17959, "s": 17900, "text": "It prevents from adding an item to your browser's history." }, { "code": null, "e": 18018, "s": 17959, "text": "Map a Controller's Property to a Different Query Param Key" }, { "code": null, "e": 18080, "s": 18018, "text": "Mapping a controller property to a different query param key." }, { "code": null, "e": 18115, "s": 18080, "text": "Default Values and Deserialization" }, { "code": null, "e": 18169, "s": 18115, "text": "Specifying the default values to the query parameter." }, { "code": null, "e": 18195, "s": 18169, "text": "Sticky Query Param Values" }, { "code": null, "e": 18273, "s": 18195, "text": "The query parameter are sticky so changes in the parameter will be preserved." }, { "code": null, "e": 18360, "s": 18273, "text": "The Ember.js router is capable for handling complex async logic within an application." }, { "code": null, "e": 18426, "s": 18360, "text": "The following table shows properties of the asynchronous routing:" }, { "code": null, "e": 18457, "s": 18426, "text": "The Router Pauses for Promises" }, { "code": null, "e": 18537, "s": 18457, "text": "The router considers a then method with any object, is defined to be a promise." }, { "code": null, "e": 18558, "s": 18537, "text": "When Promises Reject" }, { "code": null, "e": 18631, "s": 18558, "text": "The promise rejects during a transition, the transition will be aborted." }, { "code": null, "e": 18657, "s": 18631, "text": "Recovering from Rejection" }, { "code": null, "e": 18697, "s": 18657, "text": "Recovering from the aborted transition." }, { "code": null, "e": 18830, "s": 18697, "text": "The Ember.js overrides transitions for customizing asynchronization between the routes by making use of error and loading substates." }, { "code": null, "e": 18900, "s": 18830, "text": "The following table shows properties of the loading/error substates −" }, { "code": null, "e": 18918, "s": 18900, "text": "loading Substates" }, { "code": null, "e": 18994, "s": 18918, "text": "Ember.js has loading process that implements the loading substate behavior." }, { "code": null, "e": 19010, "s": 18994, "text": "error Substates" }, { "code": null, "e": 19097, "s": 19010, "text": "The error handlers will looks for an error substate to be entered into an application." }, { "code": null, "e": 19265, "s": 19097, "text": "The transition.abort() and transition.retry() methods are called to abort and retry the transition respectively this cause because of failure of the transition object." }, { "code": null, "e": 19346, "s": 19265, "text": "The following table shows properties of the preventing and retrying transitions:" }, { "code": null, "e": 19388, "s": 19346, "text": "Preventing Transitions Via willTransition" }, { "code": null, "e": 19454, "s": 19388, "text": "This fires the willTransition action for currently active routes." }, { "code": null, "e": 19513, "s": 19454, "text": "Aborting Transitions Within model, beforeModel, afterModel" }, { "code": null, "e": 19577, "s": 19513, "text": "The destination routes makes an attempted transitions to abort." }, { "code": null, "e": 19611, "s": 19577, "text": "Storing and Retrying a Transition" }, { "code": null, "e": 19658, "s": 19611, "text": "You can also re-attempt on aborted transition." }, { "code": null, "e": 19665, "s": 19658, "text": " Print" }, { "code": null, "e": 19676, "s": 19665, "text": " Add Notes" } ]
How to clear screen in python? - GeeksforGeeks
05 Apr, 2018 Most of the time, while working with python interactive shell/terminal (not a console), we end up with a messy output and want to clear the screen for some reason.In an interactive shell/terminal, we can simply use ctrl+l But, what if we want to clear the screen while running a python script.Unfortunately, there’s no built-in keyword or function/method to clear the screen. So, we do it on our own. We can use ANSI escape sequence but these are not portable and might not produce desired output. print(chr(27)+'[2j')print('\033c')print('\x1bc') So, here’s what we’re going to do in our script: From os import system.Define a function.Make a system call with ‘clear’ in Linux and ‘cls’ in Windows as an argument.Store the returned value in an underscore or whatever variable you want (an underscore is used because python shell always stores its last output in an underscore).Call the function we defined. From os import system. Define a function. Make a system call with ‘clear’ in Linux and ‘cls’ in Windows as an argument. Store the returned value in an underscore or whatever variable you want (an underscore is used because python shell always stores its last output in an underscore). Call the function we defined. # import only system from osfrom os import system, name # import sleep to show output for some time periodfrom time import sleep # define our clear functiondef clear(): # for windows if name == 'nt': _ = system('cls') # for mac and linux(here, os.name is 'posix') else: _ = system('clear') # print out some textprint('hello geeks\n'*10) # sleep for 2 seconds after printing outputsleep(2) # now call function we defined aboveclear() NOTE: You can also only “import os” instead of “from os import system” but with that, you have to change system(‘clear’) to os.system(‘clear’). Another way to accomplish this is using subprocess module. # import call method from subprocess modulefrom subprocess import call # import sleep to show output for some time periodfrom time import sleep # define clear functiondef clear(): # check and make call for specific operating system _ = call('clear' if os.name =='posix' else 'cls') print('hello geeks\n'*10) # sleep for 2 seconds after printing outputsleep(2) # now call function we defined aboveclear() python-modules Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace() Create a Pandas DataFrame from Lists Python program to convert a list to string Reading and Writing to text files in Python sum() function in Python
[ { "code": null, "e": 24144, "s": 24116, "text": "\n05 Apr, 2018" }, { "code": null, "e": 24359, "s": 24144, "text": "Most of the time, while working with python interactive shell/terminal (not a console), we end up with a messy output and want to clear the screen for some reason.In an interactive shell/terminal, we can simply use" }, { "code": null, "e": 24366, "s": 24359, "text": "ctrl+l" }, { "code": null, "e": 24545, "s": 24366, "text": "But, what if we want to clear the screen while running a python script.Unfortunately, there’s no built-in keyword or function/method to clear the screen. So, we do it on our own." }, { "code": null, "e": 24642, "s": 24545, "text": "We can use ANSI escape sequence but these are not portable and might not produce desired output." }, { "code": null, "e": 24691, "s": 24642, "text": "print(chr(27)+'[2j')print('\\033c')print('\\x1bc')" }, { "code": null, "e": 24740, "s": 24691, "text": "So, here’s what we’re going to do in our script:" }, { "code": null, "e": 25051, "s": 24740, "text": "From os import system.Define a function.Make a system call with ‘clear’ in Linux and ‘cls’ in Windows as an argument.Store the returned value in an underscore or whatever variable you want (an underscore is used because python shell always stores its last output in an underscore).Call the function we defined." }, { "code": null, "e": 25074, "s": 25051, "text": "From os import system." }, { "code": null, "e": 25093, "s": 25074, "text": "Define a function." }, { "code": null, "e": 25171, "s": 25093, "text": "Make a system call with ‘clear’ in Linux and ‘cls’ in Windows as an argument." }, { "code": null, "e": 25336, "s": 25171, "text": "Store the returned value in an underscore or whatever variable you want (an underscore is used because python shell always stores its last output in an underscore)." }, { "code": null, "e": 25366, "s": 25336, "text": "Call the function we defined." }, { "code": "# import only system from osfrom os import system, name # import sleep to show output for some time periodfrom time import sleep # define our clear functiondef clear(): # for windows if name == 'nt': _ = system('cls') # for mac and linux(here, os.name is 'posix') else: _ = system('clear') # print out some textprint('hello geeks\\n'*10) # sleep for 2 seconds after printing outputsleep(2) # now call function we defined aboveclear()", "e": 25834, "s": 25366, "text": null }, { "code": null, "e": 25978, "s": 25834, "text": "NOTE: You can also only “import os” instead of “from os import system” but with that, you have to change system(‘clear’) to os.system(‘clear’)." }, { "code": null, "e": 26037, "s": 25978, "text": "Another way to accomplish this is using subprocess module." }, { "code": "# import call method from subprocess modulefrom subprocess import call # import sleep to show output for some time periodfrom time import sleep # define clear functiondef clear(): # check and make call for specific operating system _ = call('clear' if os.name =='posix' else 'cls') print('hello geeks\\n'*10) # sleep for 2 seconds after printing outputsleep(2) # now call function we defined aboveclear()", "e": 26452, "s": 26037, "text": null }, { "code": null, "e": 26467, "s": 26452, "text": "python-modules" }, { "code": null, "e": 26474, "s": 26467, "text": "Python" }, { "code": null, "e": 26493, "s": 26474, "text": "Technical Scripter" }, { "code": null, "e": 26591, "s": 26493, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26626, "s": 26591, "text": "Read a file line by line in Python" }, { "code": null, "e": 26648, "s": 26626, "text": "Enumerate() in Python" }, { "code": null, "e": 26680, "s": 26648, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26710, "s": 26680, "text": "Iterate over a list in Python" }, { "code": null, "e": 26752, "s": 26710, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26778, "s": 26752, "text": "Python String | replace()" }, { "code": null, "e": 26815, "s": 26778, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 26858, "s": 26815, "text": "Python program to convert a list to string" }, { "code": null, "e": 26902, "s": 26858, "text": "Reading and Writing to text files in Python" } ]
How to clear the canvas using clearRect in HTML ?
27 Jan, 2022 The clearRect() method of the Canvas 2D API which is used to erase the pixel in a rectangular area by setting the pixel color to transparent black (rgba(0, 0, 0, 0)).Syntax: abc.clearRect(x, y, width, height); Parameters: x, y: These parameter represents the top-left coordinate of the rectangular box. width: It is used to set the width of the rectangular box height: It is used to set the of the rectangular box Example 1: In the following example the clearRect() method is used to clear the pixel of a rectangle of size (200×300) from (50, 20). html <!DOCTYPE html><html lang="en"> <head> <title> How to clear the canvas using clearRect in HTML? </title></head> <body> <canvas id="canvas"></canvas> <script> const canvas = document.getElementById("canvas"); const abc = canvas.getContext('2d'); abc.beginPath(); abc.fillStyle = "red"; abc.fillRect(0, 0, 200, 300); abc.clearRect(50, 20, 100, 100); </script></body> </html> Output: Example 2: html <!DOCTYPE html><html lang="en"> <head> <title> How to clear the canvas using clearRect in HTML? </title></head> <body> <canvas id="canvas"></canvas> <script> const canvas = document.getElementById("canvas"); const abc = canvas.getContext('2d'); // Draws a rectangle of 200x300 abc.beginPath(); abc.fillStyle = "red"; abc.fillRect(0, 0, 200, 300); // Draws a triangle abc.beginPath(); abc.fillStyle = "green"; abc.moveTo(10, 10); abc.lineTo(150, 10); abc.lineTo(120, 120); abc.closePath(); abc.fill(); abc.clearRect(40, 25, 100, 70); </script></body> </html> Output: Example 3: In this example we will erase whole canvas. html <!DOCTYPE html><html lang="en"> <head> <title> How to clear the canvas using clearRect in HTML? </title></head> <body> <canvas id="canvas"></canvas> <script> const canvas = document.getElementById("canvas"); const abc = canvas.getContext('2d'); abc.beginPath(); abc.fillStyle = "red"; abc.fillRect(0, 0, 200, 300); // This line will erase whole canvas and // we will get an empty screen abc.clearRect(0, 0, canvas.width, canvas.height); </script></body> </html> Note: Be aware that clearRect() may cause unintended side effects if you’re not using paths properly. Make sure to call beginPath() before starting to draw new items after calling clearRect().Reference: https://www.geeksforgeeks.org/html-canvas-clearrect-method/ kk773572498 saurabh1990aror kk9826225 HTML-Canvas HTML-Misc Picked HTML JavaScript Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n27 Jan, 2022" }, { "code": null, "e": 203, "s": 28, "text": "The clearRect() method of the Canvas 2D API which is used to erase the pixel in a rectangular area by setting the pixel color to transparent black (rgba(0, 0, 0, 0)).Syntax: " }, { "code": null, "e": 239, "s": 203, "text": "abc.clearRect(x, y, width, height);" }, { "code": null, "e": 252, "s": 239, "text": "Parameters: " }, { "code": null, "e": 333, "s": 252, "text": "x, y: These parameter represents the top-left coordinate of the rectangular box." }, { "code": null, "e": 391, "s": 333, "text": "width: It is used to set the width of the rectangular box" }, { "code": null, "e": 444, "s": 391, "text": "height: It is used to set the of the rectangular box" }, { "code": null, "e": 578, "s": 444, "text": "Example 1: In the following example the clearRect() method is used to clear the pixel of a rectangle of size (200×300) from (50, 20)." }, { "code": null, "e": 583, "s": 578, "text": "html" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <title> How to clear the canvas using clearRect in HTML? </title></head> <body> <canvas id=\"canvas\"></canvas> <script> const canvas = document.getElementById(\"canvas\"); const abc = canvas.getContext('2d'); abc.beginPath(); abc.fillStyle = \"red\"; abc.fillRect(0, 0, 200, 300); abc.clearRect(50, 20, 100, 100); </script></body> </html>", "e": 1038, "s": 583, "text": null }, { "code": null, "e": 1047, "s": 1038, "text": "Output: " }, { "code": null, "e": 1059, "s": 1047, "text": "Example 2: " }, { "code": null, "e": 1064, "s": 1059, "text": "html" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <title> How to clear the canvas using clearRect in HTML? </title></head> <body> <canvas id=\"canvas\"></canvas> <script> const canvas = document.getElementById(\"canvas\"); const abc = canvas.getContext('2d'); // Draws a rectangle of 200x300 abc.beginPath(); abc.fillStyle = \"red\"; abc.fillRect(0, 0, 200, 300); // Draws a triangle abc.beginPath(); abc.fillStyle = \"green\"; abc.moveTo(10, 10); abc.lineTo(150, 10); abc.lineTo(120, 120); abc.closePath(); abc.fill(); abc.clearRect(40, 25, 100, 70); </script></body> </html>", "e": 1783, "s": 1064, "text": null }, { "code": null, "e": 1792, "s": 1783, "text": "Output: " }, { "code": null, "e": 1848, "s": 1792, "text": "Example 3: In this example we will erase whole canvas. " }, { "code": null, "e": 1853, "s": 1848, "text": "html" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <title> How to clear the canvas using clearRect in HTML? </title></head> <body> <canvas id=\"canvas\"></canvas> <script> const canvas = document.getElementById(\"canvas\"); const abc = canvas.getContext('2d'); abc.beginPath(); abc.fillStyle = \"red\"; abc.fillRect(0, 0, 200, 300); // This line will erase whole canvas and // we will get an empty screen abc.clearRect(0, 0, canvas.width, canvas.height); </script></body> </html>", "e": 2417, "s": 1853, "text": null }, { "code": null, "e": 2680, "s": 2417, "text": "Note: Be aware that clearRect() may cause unintended side effects if you’re not using paths properly. Make sure to call beginPath() before starting to draw new items after calling clearRect().Reference: https://www.geeksforgeeks.org/html-canvas-clearrect-method/" }, { "code": null, "e": 2692, "s": 2680, "text": "kk773572498" }, { "code": null, "e": 2708, "s": 2692, "text": "saurabh1990aror" }, { "code": null, "e": 2718, "s": 2708, "text": "kk9826225" }, { "code": null, "e": 2730, "s": 2718, "text": "HTML-Canvas" }, { "code": null, "e": 2740, "s": 2730, "text": "HTML-Misc" }, { "code": null, "e": 2747, "s": 2740, "text": "Picked" }, { "code": null, "e": 2752, "s": 2747, "text": "HTML" }, { "code": null, "e": 2763, "s": 2752, "text": "JavaScript" }, { "code": null, "e": 2780, "s": 2763, "text": "Web Technologies" }, { "code": null, "e": 2785, "s": 2780, "text": "HTML" } ]
p5.js | loadJSON() Function
26 Mar, 2020 The loadJSON() function is used to read the contents of a JSON file or URL and return it as an object. In case the file contains a JSON array, this function would still return it as an object with the index numbers specifying the different keys of the object. This method can support file sizes up to 64MB. This function is asynchronous, therefore it is recommended to be called in the preload() function to ensure that the function is executed before the other functions. Syntax: loadJSON(path, jsonpOptions, datatype, callback, errorCallback) or loadJSON(path, datatype, callback, errorCallback) or loadJSON(path, callback, errorCallback) Parameters: This function accepts five parameters as mentioned above and described below: path: This is a string which denotes the file path or URL from where the JSON has to be loaded. jsonpOptions: This is an object which has options for settings related to “jsonp” . It is an optional parameter. datatype: It is a string which specifies whether the json object is “json” or “jsonp”. It is an optional parameter. callback: This is a function which is called when this function executes successfully. The first argument for this function is the data loaded from the file. It is an optional parameter. errorCallback: This is a function which is called if there is any error in executing the function. The first argument for this function is the error response. It is an optional parameter. Return Value: It returns an object with the loaded JSON data. The examples below illustrate the loadJSON() function in p5.js: Example 1: let loadedJSON = null; function setup() { createCanvas(500, 400); textSize(22); text("Click on the button below to load JSON from file", 20, 20); // Create a button for loading the JSON loadBtn = createButton("Load JSON from file"); loadBtn.position(30, 50) loadBtn.mousePressed(loadJSONFile);} function loadJSONFile() { // Load the JSON from file loadedJSON = loadJSON('books.json', onFileload);} function onFileload() { text("File loaded successfully...", 30, 100); for (let i = 0; i < 3; i++) { text("Name: " + loadedJSON[i]["name"], 30, 140 + i * 80); text("Author: " + loadedJSON[i]["author"], 30, 160 + i * 80); text("Price: " + loadedJSON[i]["price"], 30, 180 + i * 80); }} Output: Example 2: let loadedJSON = null; function setup() { createCanvas(600, 300); textSize(22); text("Click on the button below to load JSON from URL", 20, 20); // Create a button for loading the JSON loadBtn = createButton("Load JSON from URL"); loadBtn.position(30, 50) loadBtn.mousePressed(loadURL);} function loadURL() { // Load the JSON from API loadedJSON = loadJSON("https://jsonplaceholder.typicode.com/users/5", onURLload);} function onURLload() { text("ID: " + loadedJSON["id"], 30, 100); text("Name: " + loadedJSON["name"], 30, 120); text("Username: " + loadedJSON["username"], 30, 140); text("Email: " + loadedJSON["email"], 30, 160); text("Address City: " + loadedJSON["address"]["city"], 30, 200); text("Address Zipcode: " + loadedJSON["address"]["zipcode"], 30, 220);} Output: Online editor: https://editor.p5js.org/ Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/ Reference: https://p5js.org/reference/#/p5/loadJSON JavaScript-p5.js JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. File uploading in React.js How to Open URL in New Tab using JavaScript ? Node.js | fs.writeFileSync() Method Hide or show elements in HTML using display property How do you run JavaScript script through the Terminal? How to insert spaces/tabs in text using HTML/CSS? Installation of Node.js on Linux How to set the default value for an HTML <select> element ? How to set space between the flexbox ? How to position a div at the bottom of its container using CSS?
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Mar, 2020" }, { "code": null, "e": 335, "s": 28, "text": "The loadJSON() function is used to read the contents of a JSON file or URL and return it as an object. In case the file contains a JSON array, this function would still return it as an object with the index numbers specifying the different keys of the object. This method can support file sizes up to 64MB." }, { "code": null, "e": 501, "s": 335, "text": "This function is asynchronous, therefore it is recommended to be called in the preload() function to ensure that the function is executed before the other functions." }, { "code": null, "e": 509, "s": 501, "text": "Syntax:" }, { "code": null, "e": 573, "s": 509, "text": "loadJSON(path, jsonpOptions, datatype, callback, errorCallback)" }, { "code": null, "e": 576, "s": 573, "text": "or" }, { "code": null, "e": 626, "s": 576, "text": "loadJSON(path, datatype, callback, errorCallback)" }, { "code": null, "e": 629, "s": 626, "text": "or" }, { "code": null, "e": 669, "s": 629, "text": "loadJSON(path, callback, errorCallback)" }, { "code": null, "e": 759, "s": 669, "text": "Parameters: This function accepts five parameters as mentioned above and described below:" }, { "code": null, "e": 855, "s": 759, "text": "path: This is a string which denotes the file path or URL from where the JSON has to be loaded." }, { "code": null, "e": 968, "s": 855, "text": "jsonpOptions: This is an object which has options for settings related to “jsonp” . It is an optional parameter." }, { "code": null, "e": 1084, "s": 968, "text": "datatype: It is a string which specifies whether the json object is “json” or “jsonp”. It is an optional parameter." }, { "code": null, "e": 1271, "s": 1084, "text": "callback: This is a function which is called when this function executes successfully. The first argument for this function is the data loaded from the file. It is an optional parameter." }, { "code": null, "e": 1459, "s": 1271, "text": "errorCallback: This is a function which is called if there is any error in executing the function. The first argument for this function is the error response. It is an optional parameter." }, { "code": null, "e": 1521, "s": 1459, "text": "Return Value: It returns an object with the loaded JSON data." }, { "code": null, "e": 1585, "s": 1521, "text": "The examples below illustrate the loadJSON() function in p5.js:" }, { "code": null, "e": 1596, "s": 1585, "text": "Example 1:" }, { "code": "let loadedJSON = null; function setup() { createCanvas(500, 400); textSize(22); text(\"Click on the button below to load JSON from file\", 20, 20); // Create a button for loading the JSON loadBtn = createButton(\"Load JSON from file\"); loadBtn.position(30, 50) loadBtn.mousePressed(loadJSONFile);} function loadJSONFile() { // Load the JSON from file loadedJSON = loadJSON('books.json', onFileload);} function onFileload() { text(\"File loaded successfully...\", 30, 100); for (let i = 0; i < 3; i++) { text(\"Name: \" + loadedJSON[i][\"name\"], 30, 140 + i * 80); text(\"Author: \" + loadedJSON[i][\"author\"], 30, 160 + i * 80); text(\"Price: \" + loadedJSON[i][\"price\"], 30, 180 + i * 80); }}", "e": 2305, "s": 1596, "text": null }, { "code": null, "e": 2313, "s": 2305, "text": "Output:" }, { "code": null, "e": 2324, "s": 2313, "text": "Example 2:" }, { "code": "let loadedJSON = null; function setup() { createCanvas(600, 300); textSize(22); text(\"Click on the button below to load JSON from URL\", 20, 20); // Create a button for loading the JSON loadBtn = createButton(\"Load JSON from URL\"); loadBtn.position(30, 50) loadBtn.mousePressed(loadURL);} function loadURL() { // Load the JSON from API loadedJSON = loadJSON(\"https://jsonplaceholder.typicode.com/users/5\", onURLload);} function onURLload() { text(\"ID: \" + loadedJSON[\"id\"], 30, 100); text(\"Name: \" + loadedJSON[\"name\"], 30, 120); text(\"Username: \" + loadedJSON[\"username\"], 30, 140); text(\"Email: \" + loadedJSON[\"email\"], 30, 160); text(\"Address City: \" + loadedJSON[\"address\"][\"city\"], 30, 200); text(\"Address Zipcode: \" + loadedJSON[\"address\"][\"zipcode\"], 30, 220);}", "e": 3118, "s": 2324, "text": null }, { "code": null, "e": 3126, "s": 3118, "text": "Output:" }, { "code": null, "e": 3166, "s": 3126, "text": "Online editor: https://editor.p5js.org/" }, { "code": null, "e": 3264, "s": 3166, "text": "Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/" }, { "code": null, "e": 3316, "s": 3264, "text": "Reference: https://p5js.org/reference/#/p5/loadJSON" }, { "code": null, "e": 3333, "s": 3316, "text": "JavaScript-p5.js" }, { "code": null, "e": 3344, "s": 3333, "text": "JavaScript" }, { "code": null, "e": 3361, "s": 3344, "text": "Web Technologies" }, { "code": null, "e": 3459, "s": 3361, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3486, "s": 3459, "text": "File uploading in React.js" }, { "code": null, "e": 3532, "s": 3486, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 3568, "s": 3532, "text": "Node.js | fs.writeFileSync() Method" }, { "code": null, "e": 3621, "s": 3568, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 3676, "s": 3621, "text": "How do you run JavaScript script through the Terminal?" }, { "code": null, "e": 3726, "s": 3676, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 3759, "s": 3726, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 3819, "s": 3759, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 3858, "s": 3819, "text": "How to set space between the flexbox ?" } ]
Implement Stack and Queue using Deque
23 Jun, 2022 Deque also known as double ended queue, as name suggests is a special kind of queue in which insertions and deletions can be done at the last as well as at the beginning. A link-list representation of deque is such that each node points to the next node as well as the previous node. So that insertion and deletions take constant time at both the beginning and the last. Now, deque can be used to implement a stack and queue. One simply needs to understand how deque can made to work as a stack or a queue. The functions of deque to tweak them to work as stack and queue are list below. Examples: Stack Input : Stack : 1 2 3 Push(4) Output : Stack : 1 2 3 4 Input : Stack : 1 2 3 Pop() Output : Stack : 1 2 Examples: Queue Input: Queue : 1 2 3 Enqueue(4) Output: Queue : 1 2 3 4 Input: Queue : 1 2 3 Dequeue() Output: Queue : 2 3 C++ Java C# Javascript // C++ Program to implement stack and queue using Deque#include <bits/stdc++.h>using namespace std; // structure for a node of dequestruct DQueNode { int value; DQueNode* next; DQueNode* prev;}; // Implementation of deque classclass Deque {private: // pointers to head and tail of deque DQueNode* head; DQueNode* tail; public: // constructor Deque() { head = tail = NULL; } // if list is empty bool isEmpty() { if (head == NULL) return true; return false; } // count the number of nodes in list int size() { // if list is not empty if (!isEmpty()) { DQueNode* temp = head; int len = 0; while (temp != NULL) { len++; temp = temp->next; } return len; } return 0; } // insert at the first position void insert_first(int element) { // allocating node of DQueNode type DQueNode* temp = new DQueNode[sizeof(DQueNode)]; temp->value = element; // if the element is first element if (head == NULL) { head = tail = temp; temp->next = temp->prev = NULL; } else { head->prev = temp; temp->next = head; temp->prev = NULL; head = temp; } } // insert at last position of deque void insert_last(int element) { // allocating node of DQueNode type DQueNode* temp = new DQueNode[sizeof(DQueNode)]; temp->value = element; // if element is the first element if (head == NULL) { head = tail = temp; temp->next = temp->prev = NULL; } else { tail->next = temp; temp->next = NULL; temp->prev = tail; tail = temp; } } // remove element at the first position void remove_first() { // if list is not empty if (!isEmpty()) { DQueNode* temp = head; head = head->next; if(head) head->prev = NULL; delete temp; if(head == NULL) tail = NULL; return; } cout << "List is Empty" << endl; } // remove element at the last position void remove_last() { // if list is not empty if (!isEmpty()) { DQueNode* temp = tail; tail = tail->prev; if(tail) tail->next = NULL; delete temp; if(tail == NULL) head = NULL; return; } cout << "List is Empty" << endl; } // displays the elements in deque void display() { // if list is not empty if (!isEmpty()) { DQueNode* temp = head; while (temp != NULL) { cout << temp->value << " "; temp = temp->next; } cout << endl; return; } cout << "List is Empty" << endl; }}; // Class to implement stack using Dequeclass Stack : public Deque {public: // push to push element at top of stack // using insert at last function of deque void push(int element) { insert_last(element); } // pop to remove element at top of stack // using remove at last function of deque void pop() { remove_last(); }}; // class to implement queue using dequeclass Queue : public Deque {public: // enqueue to insert element at last // using insert at last function of deque void enqueue(int element) { insert_last(element); } // dequeue to remove element from first // using remove at first function of deque void dequeue() { remove_first(); }}; // Driver Codeint main(){ // object of Stack Stack stk; // push 7 and 8 at top of stack stk.push(7); stk.push(8); cout << "Stack: "; stk.display(); // pop an element stk.pop(); cout << "Stack: "; stk.display(); // object of Queue Queue que; // insert 12 and 13 in queue que.enqueue(12); que.enqueue(13); cout << "Queue: "; que.display(); // delete an element from queue que.dequeue(); cout << "Queue: "; que.display(); cout << "Size of Stack is " << stk.size() << endl; cout << "Size of Queue is " << que.size() << endl; return 0;} // Java program to implement stack and// queue using Dequeclass GFG{ // Class for a node of dequestatic class DQueNode{ int value; DQueNode next; DQueNode prev;} // Implementation of deque classstatic class deque{ // Pointers to head and tail of deque private DQueNode head; private DQueNode tail; // Constructor public deque() { head = tail = null; } // If list is empty boolean isEmpty() { if (head == null) return true; return false; } // count the number of nodes in list int size() { // If list is not empty if (!isEmpty()) { DQueNode temp = head; int len = 0; while (temp != null) { len++; temp = temp.next; } return len; } return 0; } // Insert at the first position void insert_first(int element) { // Allocating node of DQueNode type DQueNode temp = new DQueNode(); temp.value = element; // If the element is first element if (head == null) { head = tail = temp; temp.next = temp.prev = null; } else { head.prev = temp; temp.next = head; temp.prev = null; head = temp; } } // Insert at last position of deque void insert_last(int element) { // Allocating node of DQueNode type DQueNode temp = new DQueNode(); temp.value = element; // If element is the first element if (head == null) { head = tail = temp; temp.next = temp.prev = null; } else { tail.next = temp; temp.next = null; temp.prev = tail; tail = temp; } } // Remove element at the first position void remove_first() { // If list is not empty if (!isEmpty()) { DQueNode temp = head; head = head.next; head.prev = null; return; } System.out.print("List is Empty"); } // Remove element at the last position void remove_last() { // If list is not empty if (!isEmpty()) { DQueNode temp = tail; tail = tail.prev; tail.next = null; return; } System.out.print("List is Empty"); } // Displays the elements in deque void display() { // If list is not empty if (!isEmpty()) { DQueNode temp = head; while (temp != null) { System.out.print(temp.value + " "); temp = temp.next; } return; } System.out.print("List is Empty"); }} // Class to implement stack using Dequestatic class Stack{ deque d = new deque(); // push to push element at top of stack // using insert at last function of deque public void push(int element) { d.insert_last(element); } // Returns size public int size() { return d.size(); } // pop to remove element at top of stack // using remove at last function of deque public void pop() { d.remove_last(); } // Display public void display() { d.display(); }} // Class to implement queue using dequestatic class Queue{ deque d = new deque(); // enqueue to insert element at last // using insert at last function of deque public void enqueue(int element) { d.insert_last(element); } // dequeue to remove element from first // using remove at first function of deque public void dequeue() { d.remove_first(); } // display public void display() { d.display(); } // size public int size() { return d.size(); }} // Driver Codepublic static void main(String[] args){ // Object of Stack Stack stk = new Stack(); // push 7 and 8 at top of stack stk.push(7); stk.push(8); System.out.print("Stack: "); stk.display(); // For new line System.out.println(); // pop an element stk.pop(); System.out.print("Stack: "); stk.display(); // For new line System.out.println(); // Object of Queue Queue que = new Queue(); // Insert 12 and 13 in queue que.enqueue(12); que.enqueue(13); System.out.print("Queue: "); que.display(); // New line System.out.println(); // Delete an element from queue que.dequeue(); System.out.print("Queue: "); que.display(); // New line System.out.println(); System.out.println("Size of stack is " + stk.size()); System.out.println("Size of queue is " + que.size());}} // This code is contributed by sujitmeshram // C# program to implement stack and// queue using Dequeusing System;class GFG{ // Class for a node of deque public class DQueNode { public int value; public DQueNode next; public DQueNode prev; } // Implementation of deque class public class deque { // Pointers to head and tail of deque private DQueNode head; private DQueNode tail; // Constructor public deque() { head = tail = null; } // If list is empty public bool isEmpty() { if (head == null) return true; return false; } // count the number of nodes in list public int size() { // If list is not empty if (!isEmpty()) { DQueNode temp = head; int len = 0; while (temp != null) { len++; temp = temp.next; } return len; } return 0; } // Insert at the first position public void insert_first(int element) { // Allocating node of DQueNode type DQueNode temp = new DQueNode(); temp.value = element; // If the element is first element if (head == null) { head = tail = temp; temp.next = temp.prev = null; } else { head.prev = temp; temp.next = head; temp.prev = null; head = temp; } } // Insert at last position of deque public void insert_last(int element) { // Allocating node of DQueNode type DQueNode temp = new DQueNode(); temp.value = element; // If element is the first element if (head == null) { head = tail = temp; temp.next = temp.prev = null; } else { tail.next = temp; temp.next = null; temp.prev = tail; tail = temp; } } // Remove element at the first position public void remove_first() { // If list is not empty if (!isEmpty()) { head = head.next; head.prev = null; return; } Console.Write("List is Empty"); } // Remove element at the last position public void remove_last() { // If list is not empty if (!isEmpty()) { tail = tail.prev; tail.next = null; return; } Console.Write("List is Empty"); } // Displays the elements in deque public void display() { // If list is not empty if (!isEmpty()) { DQueNode temp = head; while (temp != null) { Console.Write(temp.value + " "); temp = temp.next; } return; } Console.Write("List is Empty"); } } // Class to implement stack using Deque public class Stack { deque d = new deque(); // push to push element at top of stack // using insert at last function of deque public void push(int element) { d.insert_last(element); } // Returns size public int size() { return d.size(); } // pop to remove element at top of stack // using remove at last function of deque public void pop() { d.remove_last(); } // Display public void display() { d.display(); } } // Class to implement queue using deque class Queue { deque d = new deque(); // enqueue to insert element at last // using insert at last function of deque public void enqueue(int element) { d.insert_last(element); } // dequeue to remove element from first // using remove at first function of deque public void dequeue() { d.remove_first(); } // display public void display() { d.display(); } // size public int size() { return d.size(); } } // Driver Code public static void Main(String[] args) { // Object of Stack Stack stk = new Stack(); // push 7 and 8 at top of stack stk.push(7); stk.push(8); Console.Write("Stack: "); stk.display(); // For new line Console.WriteLine(); // pop an element stk.pop(); Console.Write("Stack: "); stk.display(); // For new line Console.WriteLine(); // Object of Queue Queue que = new Queue(); // Insert 12 and 13 in queue que.enqueue(12); que.enqueue(13); Console.Write("Queue: "); que.display(); // New line Console.WriteLine(); // Delete an element from queue que.dequeue(); Console.Write("Queue: "); que.display(); // New line Console.WriteLine(); Console.WriteLine("Size of stack is " + stk.size()); Console.WriteLine("Size of queue is " + que.size()); }} // This code contributed by gauravrajput1 <script>// Javascript program to implement stack and// queue using Deque // Class for a node of dequeclass DQueNode{ constructor() { this.value = 0; this.next = null; this.prev = null; }} // Implementation of deque classclass deque{ // Constructor constructor() { this.head = this.tail=null; } // If list is empty isEmpty() { if (this.head == null) return true; return false; } // count the number of nodes in list size() { // If list is not empty if (!this.isEmpty()) { let temp = this.head; let len = 0; while (temp != null) { len++; temp = temp.next; } return len; } return 0; } // Insert at the first position insert_first(element) { // Allocating node of DQueNode type let temp = new DQueNode(); temp.value = element; // If the element is first element if (this.head == null) { this.head = this.tail = temp; temp.next = temp.prev = null; } else { this.head.prev = temp; temp.next = this.head; temp.prev = null; this.head = temp; } } // Insert at last position of deque insert_last(element) { // Allocating node of DQueNode type let temp = new DQueNode(); temp.value = element; // If element is the first element if (this.head == null) { this.head = this.tail = temp; temp.next = temp.prev = null; } else { this.tail.next = temp; temp.next = null; temp.prev = this.tail; this.tail = temp; } } // Remove element at the first position remove_first() { // If list is not empty if (!this.isEmpty()) { let temp = this.head; this.head = this.head.next; this.head.prev = null; return; } document.write("List is Empty"); } // Remove element at the last position remove_last() { // If list is not empty if (!this.isEmpty()) { let temp = this.tail; this.tail = this.tail.prev; this.tail.next = null; return; } document.write("List is Empty"); } // Displays the elements in deque display() { // If list is not empty if (!this.isEmpty()) { let temp = this.head; while (temp != null) { document.write(temp.value + " "); temp = temp.next; } return; } document.write("List is Empty"); }} // Class to implement stack using Dequeclass Stack{ constructor() { this.d= new deque(); } // push to push element at top of stack // using insert at last function of deque push(element) { this.d.insert_last(element); } // Returns size size() { return this.d.size(); } // pop to remove element at top of stack // using remove at last function of deque pop() { this.d.remove_last(); } // Display display() { this.d.display(); }} // Class to implement queue using dequeclass Queue{ constructor() { this.d = new deque(); } // enqueue to insert element at last // using insert at last function of deque enqueue(element) { this.d.insert_last(element); } // dequeue to remove element from first // using remove at first function of deque dequeue() { this.d.remove_first(); } // display display() { this.d.display(); } // size size() { return this.d.size(); }} // Driver Code// Object of Stacklet stk = new Stack(); // push 7 and 8 at top of stackstk.push(7);stk.push(8);document.write("Stack: ");stk.display(); // For new linedocument.write("<br>"); // pop an elementstk.pop();document.write("Stack: ");stk.display(); // For new linedocument.write("<br>"); // Object of Queuelet que = new Queue(); // Insert 12 and 13 in queueque.enqueue(12);que.enqueue(13);document.write("Queue: ");que.display(); // New linedocument.write("<br>"); // Delete an element from queueque.dequeue();document.write("Queue: ");que.display(); // New linedocument.write("<br>");document.write("Size of stack is " + stk.size()+"<br>");document.write("Size of queue is " + que.size()+"<br>"); // This code is contributed by patel2127</script> Output: Stack: 7 8 Stack: 7 Queue: 12 13 Queue: 13 Size of Stack is 1 Size of Queue is 1 sujitmeshram GauravRajput1 adnanirshad158 saurabh1990aror Edith_3000 patel2127 gabaa406 tasneemsyed2002 deque Queue Stack Stack Queue Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n23 Jun, 2022" }, { "code": null, "e": 223, "s": 52, "text": "Deque also known as double ended queue, as name suggests is a special kind of queue in which insertions and deletions can be done at the last as well as at the beginning." }, { "code": null, "e": 423, "s": 223, "text": "A link-list representation of deque is such that each node points to the next node as well as the previous node. So that insertion and deletions take constant time at both the beginning and the last." }, { "code": null, "e": 559, "s": 423, "text": "Now, deque can be used to implement a stack and queue. One simply needs to understand how deque can made to work as a stack or a queue." }, { "code": null, "e": 640, "s": 559, "text": "The functions of deque to tweak them to work as stack and queue are list below. " }, { "code": null, "e": 657, "s": 640, "text": "Examples: Stack " }, { "code": null, "e": 778, "s": 657, "text": "Input : Stack : 1 2 3\n Push(4)\nOutput : Stack : 1 2 3 4\n\nInput : Stack : 1 2 3\n Pop()\nOutput : Stack : 1 2" }, { "code": null, "e": 795, "s": 778, "text": "Examples: Queue " }, { "code": null, "e": 917, "s": 795, "text": "Input: Queue : 1 2 3\n Enqueue(4)\nOutput: Queue : 1 2 3 4\n\nInput: Queue : 1 2 3\n Dequeue()\nOutput: Queue : 2 3" }, { "code": null, "e": 921, "s": 917, "text": "C++" }, { "code": null, "e": 926, "s": 921, "text": "Java" }, { "code": null, "e": 929, "s": 926, "text": "C#" }, { "code": null, "e": 940, "s": 929, "text": "Javascript" }, { "code": "// C++ Program to implement stack and queue using Deque#include <bits/stdc++.h>using namespace std; // structure for a node of dequestruct DQueNode { int value; DQueNode* next; DQueNode* prev;}; // Implementation of deque classclass Deque {private: // pointers to head and tail of deque DQueNode* head; DQueNode* tail; public: // constructor Deque() { head = tail = NULL; } // if list is empty bool isEmpty() { if (head == NULL) return true; return false; } // count the number of nodes in list int size() { // if list is not empty if (!isEmpty()) { DQueNode* temp = head; int len = 0; while (temp != NULL) { len++; temp = temp->next; } return len; } return 0; } // insert at the first position void insert_first(int element) { // allocating node of DQueNode type DQueNode* temp = new DQueNode[sizeof(DQueNode)]; temp->value = element; // if the element is first element if (head == NULL) { head = tail = temp; temp->next = temp->prev = NULL; } else { head->prev = temp; temp->next = head; temp->prev = NULL; head = temp; } } // insert at last position of deque void insert_last(int element) { // allocating node of DQueNode type DQueNode* temp = new DQueNode[sizeof(DQueNode)]; temp->value = element; // if element is the first element if (head == NULL) { head = tail = temp; temp->next = temp->prev = NULL; } else { tail->next = temp; temp->next = NULL; temp->prev = tail; tail = temp; } } // remove element at the first position void remove_first() { // if list is not empty if (!isEmpty()) { DQueNode* temp = head; head = head->next; if(head) head->prev = NULL; delete temp; if(head == NULL) tail = NULL; return; } cout << \"List is Empty\" << endl; } // remove element at the last position void remove_last() { // if list is not empty if (!isEmpty()) { DQueNode* temp = tail; tail = tail->prev; if(tail) tail->next = NULL; delete temp; if(tail == NULL) head = NULL; return; } cout << \"List is Empty\" << endl; } // displays the elements in deque void display() { // if list is not empty if (!isEmpty()) { DQueNode* temp = head; while (temp != NULL) { cout << temp->value << \" \"; temp = temp->next; } cout << endl; return; } cout << \"List is Empty\" << endl; }}; // Class to implement stack using Dequeclass Stack : public Deque {public: // push to push element at top of stack // using insert at last function of deque void push(int element) { insert_last(element); } // pop to remove element at top of stack // using remove at last function of deque void pop() { remove_last(); }}; // class to implement queue using dequeclass Queue : public Deque {public: // enqueue to insert element at last // using insert at last function of deque void enqueue(int element) { insert_last(element); } // dequeue to remove element from first // using remove at first function of deque void dequeue() { remove_first(); }}; // Driver Codeint main(){ // object of Stack Stack stk; // push 7 and 8 at top of stack stk.push(7); stk.push(8); cout << \"Stack: \"; stk.display(); // pop an element stk.pop(); cout << \"Stack: \"; stk.display(); // object of Queue Queue que; // insert 12 and 13 in queue que.enqueue(12); que.enqueue(13); cout << \"Queue: \"; que.display(); // delete an element from queue que.dequeue(); cout << \"Queue: \"; que.display(); cout << \"Size of Stack is \" << stk.size() << endl; cout << \"Size of Queue is \" << que.size() << endl; return 0;}", "e": 5267, "s": 940, "text": null }, { "code": "// Java program to implement stack and// queue using Dequeclass GFG{ // Class for a node of dequestatic class DQueNode{ int value; DQueNode next; DQueNode prev;} // Implementation of deque classstatic class deque{ // Pointers to head and tail of deque private DQueNode head; private DQueNode tail; // Constructor public deque() { head = tail = null; } // If list is empty boolean isEmpty() { if (head == null) return true; return false; } // count the number of nodes in list int size() { // If list is not empty if (!isEmpty()) { DQueNode temp = head; int len = 0; while (temp != null) { len++; temp = temp.next; } return len; } return 0; } // Insert at the first position void insert_first(int element) { // Allocating node of DQueNode type DQueNode temp = new DQueNode(); temp.value = element; // If the element is first element if (head == null) { head = tail = temp; temp.next = temp.prev = null; } else { head.prev = temp; temp.next = head; temp.prev = null; head = temp; } } // Insert at last position of deque void insert_last(int element) { // Allocating node of DQueNode type DQueNode temp = new DQueNode(); temp.value = element; // If element is the first element if (head == null) { head = tail = temp; temp.next = temp.prev = null; } else { tail.next = temp; temp.next = null; temp.prev = tail; tail = temp; } } // Remove element at the first position void remove_first() { // If list is not empty if (!isEmpty()) { DQueNode temp = head; head = head.next; head.prev = null; return; } System.out.print(\"List is Empty\"); } // Remove element at the last position void remove_last() { // If list is not empty if (!isEmpty()) { DQueNode temp = tail; tail = tail.prev; tail.next = null; return; } System.out.print(\"List is Empty\"); } // Displays the elements in deque void display() { // If list is not empty if (!isEmpty()) { DQueNode temp = head; while (temp != null) { System.out.print(temp.value + \" \"); temp = temp.next; } return; } System.out.print(\"List is Empty\"); }} // Class to implement stack using Dequestatic class Stack{ deque d = new deque(); // push to push element at top of stack // using insert at last function of deque public void push(int element) { d.insert_last(element); } // Returns size public int size() { return d.size(); } // pop to remove element at top of stack // using remove at last function of deque public void pop() { d.remove_last(); } // Display public void display() { d.display(); }} // Class to implement queue using dequestatic class Queue{ deque d = new deque(); // enqueue to insert element at last // using insert at last function of deque public void enqueue(int element) { d.insert_last(element); } // dequeue to remove element from first // using remove at first function of deque public void dequeue() { d.remove_first(); } // display public void display() { d.display(); } // size public int size() { return d.size(); }} // Driver Codepublic static void main(String[] args){ // Object of Stack Stack stk = new Stack(); // push 7 and 8 at top of stack stk.push(7); stk.push(8); System.out.print(\"Stack: \"); stk.display(); // For new line System.out.println(); // pop an element stk.pop(); System.out.print(\"Stack: \"); stk.display(); // For new line System.out.println(); // Object of Queue Queue que = new Queue(); // Insert 12 and 13 in queue que.enqueue(12); que.enqueue(13); System.out.print(\"Queue: \"); que.display(); // New line System.out.println(); // Delete an element from queue que.dequeue(); System.out.print(\"Queue: \"); que.display(); // New line System.out.println(); System.out.println(\"Size of stack is \" + stk.size()); System.out.println(\"Size of queue is \" + que.size());}} // This code is contributed by sujitmeshram", "e": 10254, "s": 5267, "text": null }, { "code": "// C# program to implement stack and// queue using Dequeusing System;class GFG{ // Class for a node of deque public class DQueNode { public int value; public DQueNode next; public DQueNode prev; } // Implementation of deque class public class deque { // Pointers to head and tail of deque private DQueNode head; private DQueNode tail; // Constructor public deque() { head = tail = null; } // If list is empty public bool isEmpty() { if (head == null) return true; return false; } // count the number of nodes in list public int size() { // If list is not empty if (!isEmpty()) { DQueNode temp = head; int len = 0; while (temp != null) { len++; temp = temp.next; } return len; } return 0; } // Insert at the first position public void insert_first(int element) { // Allocating node of DQueNode type DQueNode temp = new DQueNode(); temp.value = element; // If the element is first element if (head == null) { head = tail = temp; temp.next = temp.prev = null; } else { head.prev = temp; temp.next = head; temp.prev = null; head = temp; } } // Insert at last position of deque public void insert_last(int element) { // Allocating node of DQueNode type DQueNode temp = new DQueNode(); temp.value = element; // If element is the first element if (head == null) { head = tail = temp; temp.next = temp.prev = null; } else { tail.next = temp; temp.next = null; temp.prev = tail; tail = temp; } } // Remove element at the first position public void remove_first() { // If list is not empty if (!isEmpty()) { head = head.next; head.prev = null; return; } Console.Write(\"List is Empty\"); } // Remove element at the last position public void remove_last() { // If list is not empty if (!isEmpty()) { tail = tail.prev; tail.next = null; return; } Console.Write(\"List is Empty\"); } // Displays the elements in deque public void display() { // If list is not empty if (!isEmpty()) { DQueNode temp = head; while (temp != null) { Console.Write(temp.value + \" \"); temp = temp.next; } return; } Console.Write(\"List is Empty\"); } } // Class to implement stack using Deque public class Stack { deque d = new deque(); // push to push element at top of stack // using insert at last function of deque public void push(int element) { d.insert_last(element); } // Returns size public int size() { return d.size(); } // pop to remove element at top of stack // using remove at last function of deque public void pop() { d.remove_last(); } // Display public void display() { d.display(); } } // Class to implement queue using deque class Queue { deque d = new deque(); // enqueue to insert element at last // using insert at last function of deque public void enqueue(int element) { d.insert_last(element); } // dequeue to remove element from first // using remove at first function of deque public void dequeue() { d.remove_first(); } // display public void display() { d.display(); } // size public int size() { return d.size(); } } // Driver Code public static void Main(String[] args) { // Object of Stack Stack stk = new Stack(); // push 7 and 8 at top of stack stk.push(7); stk.push(8); Console.Write(\"Stack: \"); stk.display(); // For new line Console.WriteLine(); // pop an element stk.pop(); Console.Write(\"Stack: \"); stk.display(); // For new line Console.WriteLine(); // Object of Queue Queue que = new Queue(); // Insert 12 and 13 in queue que.enqueue(12); que.enqueue(13); Console.Write(\"Queue: \"); que.display(); // New line Console.WriteLine(); // Delete an element from queue que.dequeue(); Console.Write(\"Queue: \"); que.display(); // New line Console.WriteLine(); Console.WriteLine(\"Size of stack is \" + stk.size()); Console.WriteLine(\"Size of queue is \" + que.size()); }} // This code contributed by gauravrajput1", "e": 15804, "s": 10254, "text": null }, { "code": "<script>// Javascript program to implement stack and// queue using Deque // Class for a node of dequeclass DQueNode{ constructor() { this.value = 0; this.next = null; this.prev = null; }} // Implementation of deque classclass deque{ // Constructor constructor() { this.head = this.tail=null; } // If list is empty isEmpty() { if (this.head == null) return true; return false; } // count the number of nodes in list size() { // If list is not empty if (!this.isEmpty()) { let temp = this.head; let len = 0; while (temp != null) { len++; temp = temp.next; } return len; } return 0; } // Insert at the first position insert_first(element) { // Allocating node of DQueNode type let temp = new DQueNode(); temp.value = element; // If the element is first element if (this.head == null) { this.head = this.tail = temp; temp.next = temp.prev = null; } else { this.head.prev = temp; temp.next = this.head; temp.prev = null; this.head = temp; } } // Insert at last position of deque insert_last(element) { // Allocating node of DQueNode type let temp = new DQueNode(); temp.value = element; // If element is the first element if (this.head == null) { this.head = this.tail = temp; temp.next = temp.prev = null; } else { this.tail.next = temp; temp.next = null; temp.prev = this.tail; this.tail = temp; } } // Remove element at the first position remove_first() { // If list is not empty if (!this.isEmpty()) { let temp = this.head; this.head = this.head.next; this.head.prev = null; return; } document.write(\"List is Empty\"); } // Remove element at the last position remove_last() { // If list is not empty if (!this.isEmpty()) { let temp = this.tail; this.tail = this.tail.prev; this.tail.next = null; return; } document.write(\"List is Empty\"); } // Displays the elements in deque display() { // If list is not empty if (!this.isEmpty()) { let temp = this.head; while (temp != null) { document.write(temp.value + \" \"); temp = temp.next; } return; } document.write(\"List is Empty\"); }} // Class to implement stack using Dequeclass Stack{ constructor() { this.d= new deque(); } // push to push element at top of stack // using insert at last function of deque push(element) { this.d.insert_last(element); } // Returns size size() { return this.d.size(); } // pop to remove element at top of stack // using remove at last function of deque pop() { this.d.remove_last(); } // Display display() { this.d.display(); }} // Class to implement queue using dequeclass Queue{ constructor() { this.d = new deque(); } // enqueue to insert element at last // using insert at last function of deque enqueue(element) { this.d.insert_last(element); } // dequeue to remove element from first // using remove at first function of deque dequeue() { this.d.remove_first(); } // display display() { this.d.display(); } // size size() { return this.d.size(); }} // Driver Code// Object of Stacklet stk = new Stack(); // push 7 and 8 at top of stackstk.push(7);stk.push(8);document.write(\"Stack: \");stk.display(); // For new linedocument.write(\"<br>\"); // pop an elementstk.pop();document.write(\"Stack: \");stk.display(); // For new linedocument.write(\"<br>\"); // Object of Queuelet que = new Queue(); // Insert 12 and 13 in queueque.enqueue(12);que.enqueue(13);document.write(\"Queue: \");que.display(); // New linedocument.write(\"<br>\"); // Delete an element from queueque.dequeue();document.write(\"Queue: \");que.display(); // New linedocument.write(\"<br>\");document.write(\"Size of stack is \" + stk.size()+\"<br>\");document.write(\"Size of queue is \" + que.size()+\"<br>\"); // This code is contributed by patel2127</script>", "e": 20605, "s": 15804, "text": null }, { "code": null, "e": 20614, "s": 20605, "text": "Output: " }, { "code": null, "e": 20695, "s": 20614, "text": "Stack: 7 8\nStack: 7\nQueue: 12 13\nQueue: 13\nSize of Stack is 1\nSize of Queue is 1" }, { "code": null, "e": 20710, "s": 20697, "text": "sujitmeshram" }, { "code": null, "e": 20724, "s": 20710, "text": "GauravRajput1" }, { "code": null, "e": 20739, "s": 20724, "text": "adnanirshad158" }, { "code": null, "e": 20755, "s": 20739, "text": "saurabh1990aror" }, { "code": null, "e": 20766, "s": 20755, "text": "Edith_3000" }, { "code": null, "e": 20776, "s": 20766, "text": "patel2127" }, { "code": null, "e": 20785, "s": 20776, "text": "gabaa406" }, { "code": null, "e": 20801, "s": 20785, "text": "tasneemsyed2002" }, { "code": null, "e": 20807, "s": 20801, "text": "deque" }, { "code": null, "e": 20813, "s": 20807, "text": "Queue" }, { "code": null, "e": 20819, "s": 20813, "text": "Stack" }, { "code": null, "e": 20825, "s": 20819, "text": "Stack" }, { "code": null, "e": 20831, "s": 20825, "text": "Queue" } ]
Program to Convert HashMap to TreeMap in Java
01 Oct, 2021 HashMap is a part of Java’s collection since Java 1.2. It provides the basic implementation of Map interface of Java which stores the data in (Key, Value) pairs. To access a value in HashMap, one must know its key. HashMap is known as HashMap because it uses a technique Hashing for storage of data. The TreeMap in Java is used to implement Map interface and NavigableMap along with the Abstract Class. The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used. This proves to be an efficient way of sorting and storing the key-value pairs. Below are methods to convert HashMap to TreeMap in Java in such a way that the resultant TreeMap should contain all mappings of the HashMap, sorted by their natural ordering of keys. Examples: Input: HashMap: {1=Geeks, 2=forGeeks, 3=A computer Portal} Output: TreeMap: {1=Geeks, 2=forGeeks, 3=A computer Portal} Input: HashMap: {1=1, 2=2, 3=3} Output: TreeMap: {1=1, 2=2, 3=3} Below are methods to convert HashMap to TreeMap in Java: 1. In Java 8: This method includes converting the HashMap to a Stream and collects elements of a stream in a TreeMap using Stream.collect() method which accepts a collector. Algorithm: Get the HashMap to be converted.Get the entries from the hashMapConvert the map entries into streamUsing Collectors, collect the entries and convert it into TreeMapNow collect the TreeMapReturn the formed TreeMap Get the HashMap to be converted. Get the entries from the hashMap Convert the map entries into stream Using Collectors, collect the entries and convert it into TreeMap Now collect the TreeMap Return the formed TreeMap Program: Java // Java Program to convert// HashMap to TreeMap in Java 8 import java.util.*;import java.util.stream.*; class GFG { // Generic function to construct a new // TreeMap from HashMap public static <K, V> Map<K, V> convertToTreeMap(Map<K, V> hashMap) { Map<K, V> treeMap = hashMap // Get the entries from the hashMap .entrySet() // Convert the map into stream .stream() // Now collect the returned TreeMap .collect( Collectors // Using Collectors, collect the entries // and convert it into TreeMap .toMap( Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> newValue, TreeMap::new)); // Return the TreeMap return treeMap; } public static void main(String args[]) { // Create a HashMap Map<String, String> hashMap = new HashMap<>(); // Add entries to the HashMap hashMap.put("1", "Geeks"); hashMap.put("2", "forGeeks"); hashMap.put("3", "A computer Portal"); // Print the HashMap System.out.println("HashMap: " + hashMap); // construct a new TreeMap from HashMap Map<String, String> treeMap = convertToTreeMap(hashMap); // Print the TreeMap System.out.println("TreeMap: " + treeMap); }} Output: HashMap: {1=Geeks, 2=forGeeks, 3=A computer Portal} TreeMap: {1=Geeks, 2=forGeeks, 3=A computer Portal} 2. Using Plain Java: In this method, either pass HashMap instance to the TreeMap constructor or to putAll() method. This will directly create the TreeMap from the HashMap. Algorithm: Get the HashMap to be converted.Create a new TreeMapPass the hashMap to putAll() method of treeMapReturn the formed TreeMap Get the HashMap to be converted. Create a new TreeMap Pass the hashMap to putAll() method of treeMap Return the formed TreeMap Program: Java // Java Program to convert// HashMap to TreeMap in Java 8 import java.util.*;import java.util.stream.*; class GFG { // Generic function to construct a // new TreeMap from HashMap public static <K, V> Map<K, V> convertToTreeMap(Map<K, V> hashMap) { // Create a new TreeMap Map<K, V> treeMap = new TreeMap<>(); // Pass the hashMap to putAll() method treeMap.putAll(hashMap); // Return the TreeMap return treeMap; } public static void main(String args[]) { // Create a HashMap Map<String, String> hashMap = new HashMap<>(); // Add entries to the HashMap hashMap.put("1", "Geeks"); hashMap.put("2", "forGeeks"); hashMap.put("3", "A computer Portal"); // Print the HashMap System.out.println("HashMap: " + hashMap); // construct a new TreeMap from HashMap Map<String, String> treeMap = convertToTreeMap(hashMap); // Print the TreeMap System.out.println("TreeMap: " + treeMap); }} Output: HashMap: {1=Geeks, 2=forGeeks, 3=A computer Portal} TreeMap: {1=Geeks, 2=forGeeks, 3=A computer Portal} 3. Using Google’s Guava library: Guava also provides a TreeMap implementation which can be used to create an empty TreeMap instance. Algorithm: Get the HashMap to be converted.Create a new TreeMap using Maps.newTreeMap() of Guava libraryPass the hashMap to putAll() method of treeMapReturn the formed TreeMap Get the HashMap to be converted. Create a new TreeMap using Maps.newTreeMap() of Guava library Pass the hashMap to putAll() method of treeMap Return the formed TreeMap Program: Java // Java Program to convert// HashMap to TreeMap in Java 8 import com.google.common.collect.*;import java.util.*;import java.util.stream.*; class GFG { // Generic function to construct a // new TreeMap from HashMap public static <K extends Comparable, V> Map<K, V> convertToTreeMap(Map<K, V> hashMap) { // Create a new TreeMap Map<K, V> treeMap = Maps.newTreeMap(); // Pass the hashMap to putAll() method treeMap.putAll(hashMap); // Return the TreeMap return treeMap; } public static void main(String args[]) { // Create a HashMap Map<String, String> hashMap = new HashMap<>(); // Add entries to the HashMap hashMap.put("1", "Geeks"); hashMap.put("2", "forGeeks"); hashMap.put("3", "A computer Portal"); // Print the HashMap System.out.println("HashMap: " + hashMap); // construct a new TreeMap from HashMap Map<String, String> treeMap = convertToTreeMap(hashMap); // Print the TreeMap System.out.println("TreeMap: " + treeMap); }} Output: HashMap: {1=Geeks, 2=forGeeks, 3=A computer Portal} TreeMap: {1=Geeks, 2=forGeeks, 3=A computer Portal} 4. Conversion between incompatible types: This method can be used if the required TreeMap is of the different type than the HashMap. In this, the conversion needs to be done manually. Algorithm: Get the HashMap to be converted.Create a new TreeMapFor each entry of the hashMap: Convert the Key and the Value into the desired type by castingInsert the converted pair by put() method of treeMapReturn the formed TreeMap Get the HashMap to be converted. Create a new TreeMap For each entry of the hashMap: Convert the Key and the Value into the desired type by castingInsert the converted pair by put() method of treeMap Convert the Key and the Value into the desired type by casting Insert the converted pair by put() method of treeMap Return the formed TreeMap Program: Java // Java Program to convert// HashMap to TreeMap in Java 8 import java.util.*;import java.util.stream.*; class GFG { // Function to construct a new TreeMap from HashMap public static Map<Integer, String> convertToTreeMap(Map<String, String> hashMap) { // Create a new TreeMap Map<Integer, String> treeMap = new TreeMap<>(); // Convert the HashMap to TreeMap manually for (Map.Entry<String, String> e : hashMap.entrySet()) { treeMap.put(Integer.parseInt(e.getKey()), e.getValue()); } // Return the TreeMap return treeMap; } public static void main(String args[]) { // Create a HashMap Map<String, String> hashMap = new HashMap<>(); // Add entries to the HashMap hashMap.put("1", "Geeks"); hashMap.put("2", "forGeeks"); hashMap.put("3", "A computer Portal"); // Print the HashMap System.out.println("HashMap: " + hashMap); // construct a new TreeMap<Integer, String> // from HashMap<String, String> Map<Integer, String> treeMap = convertToTreeMap(hashMap); // Print the TreeMap System.out.println("TreeMap: " + treeMap); }} Output: HashMap: {1=Geeks, 2=forGeeks, 3=A computer Portal} TreeMap: {1=Geeks, 2=forGeeks, 3=A computer Portal} kashishsoda Java - util package Java-HashMap Java-Map-Programs java-TreeMap Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Introduction to Java Constructors in Java Exceptions in Java Generics in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class Factory method design pattern in Java Java Program to Remove Duplicate Elements From the Array
[ { "code": null, "e": 52, "s": 24, "text": "\n01 Oct, 2021" }, { "code": null, "e": 352, "s": 52, "text": "HashMap is a part of Java’s collection since Java 1.2. It provides the basic implementation of Map interface of Java which stores the data in (Key, Value) pairs. To access a value in HashMap, one must know its key. HashMap is known as HashMap because it uses a technique Hashing for storage of data." }, { "code": null, "e": 690, "s": 352, "text": "The TreeMap in Java is used to implement Map interface and NavigableMap along with the Abstract Class. The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used. This proves to be an efficient way of sorting and storing the key-value pairs. " }, { "code": null, "e": 873, "s": 690, "text": "Below are methods to convert HashMap to TreeMap in Java in such a way that the resultant TreeMap should contain all mappings of the HashMap, sorted by their natural ordering of keys." }, { "code": null, "e": 885, "s": 873, "text": "Examples: " }, { "code": null, "e": 1004, "s": 885, "text": "Input: HashMap: {1=Geeks, 2=forGeeks, 3=A computer Portal} Output: TreeMap: {1=Geeks, 2=forGeeks, 3=A computer Portal}" }, { "code": null, "e": 1071, "s": 1004, "text": "Input: HashMap: {1=1, 2=2, 3=3} Output: TreeMap: {1=1, 2=2, 3=3} " }, { "code": null, "e": 1129, "s": 1071, "text": "Below are methods to convert HashMap to TreeMap in Java: " }, { "code": null, "e": 1303, "s": 1129, "text": "1. In Java 8: This method includes converting the HashMap to a Stream and collects elements of a stream in a TreeMap using Stream.collect() method which accepts a collector." }, { "code": null, "e": 1315, "s": 1303, "text": "Algorithm: " }, { "code": null, "e": 1528, "s": 1315, "text": "Get the HashMap to be converted.Get the entries from the hashMapConvert the map entries into streamUsing Collectors, collect the entries and convert it into TreeMapNow collect the TreeMapReturn the formed TreeMap" }, { "code": null, "e": 1561, "s": 1528, "text": "Get the HashMap to be converted." }, { "code": null, "e": 1594, "s": 1561, "text": "Get the entries from the hashMap" }, { "code": null, "e": 1630, "s": 1594, "text": "Convert the map entries into stream" }, { "code": null, "e": 1696, "s": 1630, "text": "Using Collectors, collect the entries and convert it into TreeMap" }, { "code": null, "e": 1720, "s": 1696, "text": "Now collect the TreeMap" }, { "code": null, "e": 1746, "s": 1720, "text": "Return the formed TreeMap" }, { "code": null, "e": 1755, "s": 1746, "text": "Program:" }, { "code": null, "e": 1760, "s": 1755, "text": "Java" }, { "code": "// Java Program to convert// HashMap to TreeMap in Java 8 import java.util.*;import java.util.stream.*; class GFG { // Generic function to construct a new // TreeMap from HashMap public static <K, V> Map<K, V> convertToTreeMap(Map<K, V> hashMap) { Map<K, V> treeMap = hashMap // Get the entries from the hashMap .entrySet() // Convert the map into stream .stream() // Now collect the returned TreeMap .collect( Collectors // Using Collectors, collect the entries // and convert it into TreeMap .toMap( Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> newValue, TreeMap::new)); // Return the TreeMap return treeMap; } public static void main(String args[]) { // Create a HashMap Map<String, String> hashMap = new HashMap<>(); // Add entries to the HashMap hashMap.put(\"1\", \"Geeks\"); hashMap.put(\"2\", \"forGeeks\"); hashMap.put(\"3\", \"A computer Portal\"); // Print the HashMap System.out.println(\"HashMap: \" + hashMap); // construct a new TreeMap from HashMap Map<String, String> treeMap = convertToTreeMap(hashMap); // Print the TreeMap System.out.println(\"TreeMap: \" + treeMap); }}", "e": 3534, "s": 1760, "text": null }, { "code": null, "e": 3542, "s": 3534, "text": "Output:" }, { "code": null, "e": 3646, "s": 3542, "text": "HashMap: {1=Geeks, 2=forGeeks, 3=A computer Portal}\nTreeMap: {1=Geeks, 2=forGeeks, 3=A computer Portal}" }, { "code": null, "e": 3818, "s": 3646, "text": "2. Using Plain Java: In this method, either pass HashMap instance to the TreeMap constructor or to putAll() method. This will directly create the TreeMap from the HashMap." }, { "code": null, "e": 3830, "s": 3818, "text": "Algorithm: " }, { "code": null, "e": 3954, "s": 3830, "text": "Get the HashMap to be converted.Create a new TreeMapPass the hashMap to putAll() method of treeMapReturn the formed TreeMap" }, { "code": null, "e": 3987, "s": 3954, "text": "Get the HashMap to be converted." }, { "code": null, "e": 4008, "s": 3987, "text": "Create a new TreeMap" }, { "code": null, "e": 4055, "s": 4008, "text": "Pass the hashMap to putAll() method of treeMap" }, { "code": null, "e": 4081, "s": 4055, "text": "Return the formed TreeMap" }, { "code": null, "e": 4090, "s": 4081, "text": "Program:" }, { "code": null, "e": 4095, "s": 4090, "text": "Java" }, { "code": "// Java Program to convert// HashMap to TreeMap in Java 8 import java.util.*;import java.util.stream.*; class GFG { // Generic function to construct a // new TreeMap from HashMap public static <K, V> Map<K, V> convertToTreeMap(Map<K, V> hashMap) { // Create a new TreeMap Map<K, V> treeMap = new TreeMap<>(); // Pass the hashMap to putAll() method treeMap.putAll(hashMap); // Return the TreeMap return treeMap; } public static void main(String args[]) { // Create a HashMap Map<String, String> hashMap = new HashMap<>(); // Add entries to the HashMap hashMap.put(\"1\", \"Geeks\"); hashMap.put(\"2\", \"forGeeks\"); hashMap.put(\"3\", \"A computer Portal\"); // Print the HashMap System.out.println(\"HashMap: \" + hashMap); // construct a new TreeMap from HashMap Map<String, String> treeMap = convertToTreeMap(hashMap); // Print the TreeMap System.out.println(\"TreeMap: \" + treeMap); }}", "e": 5149, "s": 4095, "text": null }, { "code": null, "e": 5157, "s": 5149, "text": "Output:" }, { "code": null, "e": 5261, "s": 5157, "text": "HashMap: {1=Geeks, 2=forGeeks, 3=A computer Portal}\nTreeMap: {1=Geeks, 2=forGeeks, 3=A computer Portal}" }, { "code": null, "e": 5394, "s": 5261, "text": "3. Using Google’s Guava library: Guava also provides a TreeMap implementation which can be used to create an empty TreeMap instance." }, { "code": null, "e": 5405, "s": 5394, "text": "Algorithm:" }, { "code": null, "e": 5570, "s": 5405, "text": "Get the HashMap to be converted.Create a new TreeMap using Maps.newTreeMap() of Guava libraryPass the hashMap to putAll() method of treeMapReturn the formed TreeMap" }, { "code": null, "e": 5603, "s": 5570, "text": "Get the HashMap to be converted." }, { "code": null, "e": 5665, "s": 5603, "text": "Create a new TreeMap using Maps.newTreeMap() of Guava library" }, { "code": null, "e": 5712, "s": 5665, "text": "Pass the hashMap to putAll() method of treeMap" }, { "code": null, "e": 5738, "s": 5712, "text": "Return the formed TreeMap" }, { "code": null, "e": 5747, "s": 5738, "text": "Program:" }, { "code": null, "e": 5752, "s": 5747, "text": "Java" }, { "code": "// Java Program to convert// HashMap to TreeMap in Java 8 import com.google.common.collect.*;import java.util.*;import java.util.stream.*; class GFG { // Generic function to construct a // new TreeMap from HashMap public static <K extends Comparable, V> Map<K, V> convertToTreeMap(Map<K, V> hashMap) { // Create a new TreeMap Map<K, V> treeMap = Maps.newTreeMap(); // Pass the hashMap to putAll() method treeMap.putAll(hashMap); // Return the TreeMap return treeMap; } public static void main(String args[]) { // Create a HashMap Map<String, String> hashMap = new HashMap<>(); // Add entries to the HashMap hashMap.put(\"1\", \"Geeks\"); hashMap.put(\"2\", \"forGeeks\"); hashMap.put(\"3\", \"A computer Portal\"); // Print the HashMap System.out.println(\"HashMap: \" + hashMap); // construct a new TreeMap from HashMap Map<String, String> treeMap = convertToTreeMap(hashMap); // Print the TreeMap System.out.println(\"TreeMap: \" + treeMap); }}", "e": 6884, "s": 5752, "text": null }, { "code": null, "e": 6892, "s": 6884, "text": "Output:" }, { "code": null, "e": 6996, "s": 6892, "text": "HashMap: {1=Geeks, 2=forGeeks, 3=A computer Portal}\nTreeMap: {1=Geeks, 2=forGeeks, 3=A computer Portal}" }, { "code": null, "e": 7180, "s": 6996, "text": "4. Conversion between incompatible types: This method can be used if the required TreeMap is of the different type than the HashMap. In this, the conversion needs to be done manually." }, { "code": null, "e": 7192, "s": 7180, "text": "Algorithm: " }, { "code": null, "e": 7415, "s": 7192, "text": "Get the HashMap to be converted.Create a new TreeMapFor each entry of the hashMap: Convert the Key and the Value into the desired type by castingInsert the converted pair by put() method of treeMapReturn the formed TreeMap" }, { "code": null, "e": 7448, "s": 7415, "text": "Get the HashMap to be converted." }, { "code": null, "e": 7469, "s": 7448, "text": "Create a new TreeMap" }, { "code": null, "e": 7615, "s": 7469, "text": "For each entry of the hashMap: Convert the Key and the Value into the desired type by castingInsert the converted pair by put() method of treeMap" }, { "code": null, "e": 7678, "s": 7615, "text": "Convert the Key and the Value into the desired type by casting" }, { "code": null, "e": 7731, "s": 7678, "text": "Insert the converted pair by put() method of treeMap" }, { "code": null, "e": 7757, "s": 7731, "text": "Return the formed TreeMap" }, { "code": null, "e": 7766, "s": 7757, "text": "Program:" }, { "code": null, "e": 7771, "s": 7766, "text": "Java" }, { "code": "// Java Program to convert// HashMap to TreeMap in Java 8 import java.util.*;import java.util.stream.*; class GFG { // Function to construct a new TreeMap from HashMap public static Map<Integer, String> convertToTreeMap(Map<String, String> hashMap) { // Create a new TreeMap Map<Integer, String> treeMap = new TreeMap<>(); // Convert the HashMap to TreeMap manually for (Map.Entry<String, String> e : hashMap.entrySet()) { treeMap.put(Integer.parseInt(e.getKey()), e.getValue()); } // Return the TreeMap return treeMap; } public static void main(String args[]) { // Create a HashMap Map<String, String> hashMap = new HashMap<>(); // Add entries to the HashMap hashMap.put(\"1\", \"Geeks\"); hashMap.put(\"2\", \"forGeeks\"); hashMap.put(\"3\", \"A computer Portal\"); // Print the HashMap System.out.println(\"HashMap: \" + hashMap); // construct a new TreeMap<Integer, String> // from HashMap<String, String> Map<Integer, String> treeMap = convertToTreeMap(hashMap); // Print the TreeMap System.out.println(\"TreeMap: \" + treeMap); }}", "e": 9007, "s": 7771, "text": null }, { "code": null, "e": 9015, "s": 9007, "text": "Output:" }, { "code": null, "e": 9119, "s": 9015, "text": "HashMap: {1=Geeks, 2=forGeeks, 3=A computer Portal}\nTreeMap: {1=Geeks, 2=forGeeks, 3=A computer Portal}" }, { "code": null, "e": 9133, "s": 9121, "text": "kashishsoda" }, { "code": null, "e": 9153, "s": 9133, "text": "Java - util package" }, { "code": null, "e": 9166, "s": 9153, "text": "Java-HashMap" }, { "code": null, "e": 9184, "s": 9166, "text": "Java-Map-Programs" }, { "code": null, "e": 9197, "s": 9184, "text": "java-TreeMap" }, { "code": null, "e": 9202, "s": 9197, "text": "Java" }, { "code": null, "e": 9216, "s": 9202, "text": "Java Programs" }, { "code": null, "e": 9221, "s": 9216, "text": "Java" }, { "code": null, "e": 9319, "s": 9221, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9334, "s": 9319, "text": "Stream In Java" }, { "code": null, "e": 9355, "s": 9334, "text": "Introduction to Java" }, { "code": null, "e": 9376, "s": 9355, "text": "Constructors in Java" }, { "code": null, "e": 9395, "s": 9376, "text": "Exceptions in Java" }, { "code": null, "e": 9412, "s": 9395, "text": "Generics in Java" }, { "code": null, "e": 9438, "s": 9412, "text": "Java Programming Examples" }, { "code": null, "e": 9472, "s": 9438, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 9519, "s": 9472, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 9557, "s": 9519, "text": "Factory method design pattern in Java" } ]
How to Run Your First Spring Boot Application in Eclipse IDE?
16 Dec, 2021 Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and setup. Spring Boot is a microservice-based framework and making a production-ready application in it takes very little time. Following are some of the features of Spring Boot: It allows avoiding heavy configuration of XML which is present in spring It provides easy maintenance and creation of REST endpoints It includes embedded Tomcat-server Deployment is very easy, war and jar files can be easily deployed in the tomcat server For more information please refer to this article: Introduction to Spring Boot. So in the article Create and Setup Spring Boot Project in Eclipse IDE we have explained how to create a simple spring boot project. In this article, we are going to create a simple “Hello World” application and run it inside our Eclipse IDE. Procedure Create and set up Spring Boot Project in IDE.Add the spring-web dependency in your pom.xml file.Create one package and name the package as “controller in the project.Run the Spring Boot application. Create and set up Spring Boot Project in IDE. Add the spring-web dependency in your pom.xml file. Create one package and name the package as “controller in the project. Run the Spring Boot application. Step 1: Create and Setup Spring Boot Project in Eclipse IDE You may refer to this article Create and Setup Spring Boot Project in Eclipse IDE and create your first Spring Boot Application in Eclipse IDE. Step 2: Add the spring-web dependency in your pom.xml file. Go to the pom.xml file inside your project and add the following spring-web dependency. XML <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId></dependency> Step 3: In your project create one package and name the package as “controller”. In the controller, the package creates a class and name it as DemoController. Example 1A Java // Java Program to Illustrate DemoController // Importing package to code modulepackage com.example.demo.controller;// Importing required classesimport org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody; // Annotation@Controller // Classpublic class DemoController { @RequestMapping("/hello") @ResponseBody // Method public String helloWorld() { // Print statement return "Hello World!"; }} We have used the below annotations in our controller layer. Here in this example, the URI path is /hello. @Controller: This is used to specify the controller. @RequestMapping: This is used to map to the Spring MVC controller method. @ResponseBody: Used to bind the HTTP response body with a domain object in the return type. Now, our controller is ready. Let’s run our application inside the DemoApplication.java file. There is no need to change anything inside the DemoApplication.java file. Example 1B Java // Java Program to Illustrate DemoApplication // Importing package module to codepackage com.example.demo;// Importing required classesimport org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication; // Annotation@SpringBootApplication // Main classpublic class DemoApplication { // Main driver method public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); }} Step 4: Run the Spring Boot Application To run the application click on the green icon as seen in the below image. After successfully running the application you can see the console as shown in the below image. Your Tomcat server started on port 8989. Try this Tomcat URL, which is running on http://localhost:8989/hello surinderdawra388 Java-Spring-Boot Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Introduction to Java Constructors in Java Exceptions in Java Generics in Java Functional Interfaces in Java Java Programming Examples Strings in Java Differences between JDK, JRE and JVM Abstraction in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Dec, 2021" }, { "code": null, "e": 502, "s": 28, "text": "Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and setup. Spring Boot is a microservice-based framework and making a production-ready application in it takes very little time. Following are some of the features of Spring Boot:" }, { "code": null, "e": 575, "s": 502, "text": "It allows avoiding heavy configuration of XML which is present in spring" }, { "code": null, "e": 635, "s": 575, "text": "It provides easy maintenance and creation of REST endpoints" }, { "code": null, "e": 670, "s": 635, "text": "It includes embedded Tomcat-server" }, { "code": null, "e": 757, "s": 670, "text": "Deployment is very easy, war and jar files can be easily deployed in the tomcat server" }, { "code": null, "e": 1079, "s": 757, "text": "For more information please refer to this article: Introduction to Spring Boot. So in the article Create and Setup Spring Boot Project in Eclipse IDE we have explained how to create a simple spring boot project. In this article, we are going to create a simple “Hello World” application and run it inside our Eclipse IDE." }, { "code": null, "e": 1089, "s": 1079, "text": "Procedure" }, { "code": null, "e": 1288, "s": 1089, "text": "Create and set up Spring Boot Project in IDE.Add the spring-web dependency in your pom.xml file.Create one package and name the package as “controller in the project.Run the Spring Boot application." }, { "code": null, "e": 1334, "s": 1288, "text": "Create and set up Spring Boot Project in IDE." }, { "code": null, "e": 1386, "s": 1334, "text": "Add the spring-web dependency in your pom.xml file." }, { "code": null, "e": 1457, "s": 1386, "text": "Create one package and name the package as “controller in the project." }, { "code": null, "e": 1490, "s": 1457, "text": "Run the Spring Boot application." }, { "code": null, "e": 1550, "s": 1490, "text": "Step 1: Create and Setup Spring Boot Project in Eclipse IDE" }, { "code": null, "e": 1695, "s": 1550, "text": "You may refer to this article Create and Setup Spring Boot Project in Eclipse IDE and create your first Spring Boot Application in Eclipse IDE. " }, { "code": null, "e": 1843, "s": 1695, "text": "Step 2: Add the spring-web dependency in your pom.xml file. Go to the pom.xml file inside your project and add the following spring-web dependency." }, { "code": null, "e": 1847, "s": 1843, "text": "XML" }, { "code": "<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId></dependency>", "e": 1972, "s": 1847, "text": null }, { "code": null, "e": 2132, "s": 1972, "text": " Step 3: In your project create one package and name the package as “controller”. In the controller, the package creates a class and name it as DemoController." }, { "code": null, "e": 2144, "s": 2132, "text": "Example 1A " }, { "code": null, "e": 2149, "s": 2144, "text": "Java" }, { "code": "// Java Program to Illustrate DemoController // Importing package to code modulepackage com.example.demo.controller;// Importing required classesimport org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody; // Annotation@Controller // Classpublic class DemoController { @RequestMapping(\"/hello\") @ResponseBody // Method public String helloWorld() { // Print statement return \"Hello World!\"; }}", "e": 2688, "s": 2149, "text": null }, { "code": null, "e": 2795, "s": 2688, "text": " We have used the below annotations in our controller layer. Here in this example, the URI path is /hello." }, { "code": null, "e": 2848, "s": 2795, "text": "@Controller: This is used to specify the controller." }, { "code": null, "e": 2922, "s": 2848, "text": "@RequestMapping: This is used to map to the Spring MVC controller method." }, { "code": null, "e": 3014, "s": 2922, "text": "@ResponseBody: Used to bind the HTTP response body with a domain object in the return type." }, { "code": null, "e": 3183, "s": 3014, "text": "Now, our controller is ready. Let’s run our application inside the DemoApplication.java file. There is no need to change anything inside the DemoApplication.java file. " }, { "code": null, "e": 3195, "s": 3183, "text": "Example 1B " }, { "code": null, "e": 3200, "s": 3195, "text": "Java" }, { "code": "// Java Program to Illustrate DemoApplication // Importing package module to codepackage com.example.demo;// Importing required classesimport org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication; // Annotation@SpringBootApplication // Main classpublic class DemoApplication { // Main driver method public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); }}", "e": 3672, "s": 3200, "text": null }, { "code": null, "e": 3713, "s": 3672, "text": " Step 4: Run the Spring Boot Application" }, { "code": null, "e": 3790, "s": 3713, "text": "To run the application click on the green icon as seen in the below image. " }, { "code": null, "e": 3928, "s": 3790, "text": "After successfully running the application you can see the console as shown in the below image. Your Tomcat server started on port 8989. " }, { "code": null, "e": 3997, "s": 3928, "text": "Try this Tomcat URL, which is running on http://localhost:8989/hello" }, { "code": null, "e": 4016, "s": 3999, "text": "surinderdawra388" }, { "code": null, "e": 4033, "s": 4016, "text": "Java-Spring-Boot" }, { "code": null, "e": 4038, "s": 4033, "text": "Java" }, { "code": null, "e": 4043, "s": 4038, "text": "Java" }, { "code": null, "e": 4141, "s": 4043, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4156, "s": 4141, "text": "Stream In Java" }, { "code": null, "e": 4177, "s": 4156, "text": "Introduction to Java" }, { "code": null, "e": 4198, "s": 4177, "text": "Constructors in Java" }, { "code": null, "e": 4217, "s": 4198, "text": "Exceptions in Java" }, { "code": null, "e": 4234, "s": 4217, "text": "Generics in Java" }, { "code": null, "e": 4264, "s": 4234, "text": "Functional Interfaces in Java" }, { "code": null, "e": 4290, "s": 4264, "text": "Java Programming Examples" }, { "code": null, "e": 4306, "s": 4290, "text": "Strings in Java" }, { "code": null, "e": 4343, "s": 4306, "text": "Differences between JDK, JRE and JVM" } ]
Matplotlib.pyplot.ylim() in Python
13 Apr, 2020 Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. The ylim() function in pyplot module of matplotlib library is used to get or set the y-limits of the current axes. Syntax: matplotlib.pyplot.ylim(*args, **kwargs) Parameters: This method accept the following parameters that are described below: bottom: This parameter is used to set the ylim to bottom. top: This parameter is used to set the ylim to top. **kwargs: This parameter is Text properties that is used to control the appearance of the labels. Returns: This returns the following: bottom, top :This returns the tuple of the new y-axis limits. Below examples illustrate the matplotlib.pyplot.ylim() function in matplotlib.pyplot: Example #1: # Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np ax = plt.subplot(111) t = np.arange(0.0, 5.0, 0.01)s = np.cos(2 * np.pi * t)line, = plt.plot(t, s, lw = 2) plt.annotate('local max', xy =(2, 1), xytext =(3, 1.5), arrowprops = dict(facecolor ='black', shrink = 0.05), ) plt.ylim(-2, 2)plt.title(" matplotlib.pyplot.ylim() Example")plt.show() Output: Example #2: # Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np np.random.seed(9680801) mu, sigma = 50, 13x = mu + sigma * np.random.randn(10000) # the histogram of the datan, bins, patches = plt.hist(x, 50, density = True, facecolor ='g', alpha = 0.75) plt.xlabel('No of Users in K')plt.title('Histogram of IQ')plt.text(50, .035, r'$\mu = 50,\\ \sigma = 13$') plt.xlim(-10, 110)plt.ylim(0, 0.04) plt.grid(True)plt.title(" matplotlib.pyplot.ylim() Example") plt.show() Output: Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Iterate over a list in Python Python Classes and Objects Convert integer to string in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n13 Apr, 2020" }, { "code": null, "e": 223, "s": 28, "text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface." }, { "code": null, "e": 338, "s": 223, "text": "The ylim() function in pyplot module of matplotlib library is used to get or set the y-limits of the current axes." }, { "code": null, "e": 386, "s": 338, "text": "Syntax: matplotlib.pyplot.ylim(*args, **kwargs)" }, { "code": null, "e": 468, "s": 386, "text": "Parameters: This method accept the following parameters that are described below:" }, { "code": null, "e": 526, "s": 468, "text": "bottom: This parameter is used to set the ylim to bottom." }, { "code": null, "e": 578, "s": 526, "text": "top: This parameter is used to set the ylim to top." }, { "code": null, "e": 676, "s": 578, "text": "**kwargs: This parameter is Text properties that is used to control the appearance of the labels." }, { "code": null, "e": 713, "s": 676, "text": "Returns: This returns the following:" }, { "code": null, "e": 775, "s": 713, "text": "bottom, top :This returns the tuple of the new y-axis limits." }, { "code": null, "e": 861, "s": 775, "text": "Below examples illustrate the matplotlib.pyplot.ylim() function in matplotlib.pyplot:" }, { "code": null, "e": 873, "s": 861, "text": "Example #1:" }, { "code": "# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np ax = plt.subplot(111) t = np.arange(0.0, 5.0, 0.01)s = np.cos(2 * np.pi * t)line, = plt.plot(t, s, lw = 2) plt.annotate('local max', xy =(2, 1), xytext =(3, 1.5), arrowprops = dict(facecolor ='black', shrink = 0.05), ) plt.ylim(-2, 2)plt.title(\" matplotlib.pyplot.ylim() Example\")plt.show()", "e": 1311, "s": 873, "text": null }, { "code": null, "e": 1319, "s": 1311, "text": "Output:" }, { "code": null, "e": 1331, "s": 1319, "text": "Example #2:" }, { "code": "# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np np.random.seed(9680801) mu, sigma = 50, 13x = mu + sigma * np.random.randn(10000) # the histogram of the datan, bins, patches = plt.hist(x, 50, density = True, facecolor ='g', alpha = 0.75) plt.xlabel('No of Users in K')plt.title('Histogram of IQ')plt.text(50, .035, r'$\\mu = 50,\\\\ \\sigma = 13$') plt.xlim(-10, 110)plt.ylim(0, 0.04) plt.grid(True)plt.title(\" matplotlib.pyplot.ylim() Example\") plt.show()", "e": 1916, "s": 1331, "text": null }, { "code": null, "e": 1924, "s": 1916, "text": "Output:" }, { "code": null, "e": 1942, "s": 1924, "text": "Python-matplotlib" }, { "code": null, "e": 1949, "s": 1942, "text": "Python" }, { "code": null, "e": 2047, "s": 1949, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2065, "s": 2047, "text": "Python Dictionary" }, { "code": null, "e": 2107, "s": 2065, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2129, "s": 2107, "text": "Enumerate() in Python" }, { "code": null, "e": 2164, "s": 2129, "text": "Read a file line by line in Python" }, { "code": null, "e": 2190, "s": 2164, "text": "Python String | replace()" }, { "code": null, "e": 2222, "s": 2190, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2251, "s": 2222, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2281, "s": 2251, "text": "Iterate over a list in Python" }, { "code": null, "e": 2308, "s": 2281, "text": "Python Classes and Objects" } ]
Top 10 Python Applications in Real World
22 Oct, 2021 We are living in a digital world that is completely driven by chunks of code. Every industry depends on software for its proper functioning be it healthcare, military, banking, research, and the list goes on. We have a huge list of programming languages that facilitate the software development process. One of these is Python which has emerged as the most lucrative and exciting programming language. As per a survey it is observed that python is the main coding language for more than 80% of developers. The main reason behind this is its extensive libraries and frameworks that fuel up the process. Python has been at the forefront of Machine learning, data science, and artificial intelligence innovation. Further, it provides ease in building a plethora of applications, web development processes, and a lot more. In this blog, we will discuss the top 10 Python applications in the real world in a detailed manner. So let’s get started: It is one of the most astonishing applications of Python. This is because Python comes up with a wide range of frameworks like Django, Flask, Bottle, and a lot more that provide ease to developers. Furthermore, Python has inbuilt libraries and tools which make the web development process completely effortless. Use of Python for web development also offers: Amazing visualization Convenience in development Enhanced security Fast development process Machine Learning and Artificial Intelligence are the hottest subjects right now. Python along with its inbuilt libraries and tools facilitate the development of AI and ML algorithms. Further, it offers simple, concise, and readable code which makes it easier for developers to write complex algorithms and provide a versatile flow. Some of the inbuilt libraries and tools that enhance AI and ML processes are: Numpy for complex data analysis Keras for Machine learning SciPy for technical computing Seaborn for data visualization Data science involves data collection, data sorting, data analysis, and data visualization. Python provides amazing functionality to tackle statistics and complex mathematical calculations. The presence of in-built libraries provides convenience to data science professionals. Some of the popular libraries that provide ease in the data science process are TensorFlow, Pandas, and Socket learning. These libraries provide an ecosystem for fine-tuning data models, data preprocessing, and performing complex data analysis. With the rapidly growing gaming industry Python has proved to be an exceptional option for game development. Popular games like Pirates of the Caribbean, Bridge commander, and Battlefield 2 use Python programming for a wide range of functionalities and addons. The presence of popular 2D and 3D gaming libraries like pygame, panda3D, and Cocos2D make the game development process completely effortless. Audio and video applications are undoubtedly the most amazing feature of Python. Python is equipped with a lot of tools and libraries to accomplish your task flawlessly. Applications that are coded in Python include popular ones like Netflix, Spotify, and YouTube. This can be handled by libraries like Dejavu Pyo Mingus SciPy OpenCV Python is just the perfect option for software development. Popular applications like Google, Netflix, and Reddit all use Python. This language offers amazing features like: Platform independence Inbuilt libraries and frameworks to provide ease of development. Enhanced code reusability and readability High compatibility Apart from these Python offers enhanced features to work with rapidly growing technologies like Machine learning and Artificial intelligence. All these embedded features make it a popular choice for software development. CAD refers to computer-aided design; it is the process of creating 3D and 2D models digitally. This application has replaced manual drift and is used by architects, product designers, and construction managers to design products with extremely high consistency. Python is embedded with amazing applications like Blender, FreeCAD, open cascade, and a lot more to efficiently design products. These provide enhanced features like technical drawing, dynamic system development, recordings, file export, and import. Python offers excellent security and scalability features that make it perfect for delivering high-performance business applications. It has inbuilt libraries and tools like: Odoo is business management software that provides you with an automated solution for your business process. Tryton is easy-to-use open-source business software. It has fully integrated features like financial accounting, sales, CRM, purchasing, shipping, and the list goes on. All these distinguishing features make it fit for creating business applications. Python is an interactive programming language that helps developers to create GUIs easily and efficiently. It has a huge list of inbuilt tools like PyQT, kivy, wxWidgets, and many other libraries like them to build a fully functional GUI in an extremely secure and efficient manner. Web scraping is an automated process used to extract information from websites in an easier and faster way. The information is used by researchers, organizations, and analysts for a wide variety of tasks. Python has a wide range of features that make it suitable for web scraping some of them are: A concise syntax that enhances the readability and saves your time. A wide range of libraries and tools like pandas, matplotlib, and Selenium makes the web scraping process easy and efficient. Easy to use and understand Some other real-world applications of Python are: Robotics and automation by the use of inbuilt libraries and tools like PyDy, Dart, PyRobot, and pyro. Image processing: some of the amazing libraries and tools for image processing are Blender, OpenCV, Houdini, and PIL. Scientific applications are facilitated by popular libraries like Pandas, Matplotlib, SciPy, and many more Conclusion: Python is a concise and extremely powerful language that is rapidly gaining popularity. It has been the epicenter of most amazing technologies like AI, automation, and machine learning. Further, it is used to facilitate hot subjects like data analysis and data visualization. In this blog, we have tried to give you a basic idea about the top 10 python applications in the real world. We hope that you found this helpful! GBlog Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GEEK-O-LYMPICS 2022 - May The Geeks Force Be With You! Geek Streak - 24 Days POTD Challenge What is Hashing | A Complete Tutorial GeeksforGeeks Jobathon - Are You Ready For This Hiring Challenge? GeeksforGeeks Job-A-Thon Exclusive - Hiring Challenge For Amazon Alexa Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe
[ { "code": null, "e": 54, "s": 26, "text": "\n22 Oct, 2021" }, { "code": null, "e": 657, "s": 54, "text": "We are living in a digital world that is completely driven by chunks of code. Every industry depends on software for its proper functioning be it healthcare, military, banking, research, and the list goes on. We have a huge list of programming languages that facilitate the software development process. One of these is Python which has emerged as the most lucrative and exciting programming language. As per a survey it is observed that python is the main coding language for more than 80% of developers. The main reason behind this is its extensive libraries and frameworks that fuel up the process. " }, { "code": null, "e": 997, "s": 657, "text": "Python has been at the forefront of Machine learning, data science, and artificial intelligence innovation. Further, it provides ease in building a plethora of applications, web development processes, and a lot more. In this blog, we will discuss the top 10 Python applications in the real world in a detailed manner. So let’s get started:" }, { "code": null, "e": 1356, "s": 997, "text": "It is one of the most astonishing applications of Python. This is because Python comes up with a wide range of frameworks like Django, Flask, Bottle, and a lot more that provide ease to developers. Furthermore, Python has inbuilt libraries and tools which make the web development process completely effortless. Use of Python for web development also offers:" }, { "code": null, "e": 1378, "s": 1356, "text": "Amazing visualization" }, { "code": null, "e": 1405, "s": 1378, "text": "Convenience in development" }, { "code": null, "e": 1423, "s": 1405, "text": "Enhanced security" }, { "code": null, "e": 1448, "s": 1423, "text": "Fast development process" }, { "code": null, "e": 1858, "s": 1448, "text": "Machine Learning and Artificial Intelligence are the hottest subjects right now. Python along with its inbuilt libraries and tools facilitate the development of AI and ML algorithms. Further, it offers simple, concise, and readable code which makes it easier for developers to write complex algorithms and provide a versatile flow. Some of the inbuilt libraries and tools that enhance AI and ML processes are:" }, { "code": null, "e": 1890, "s": 1858, "text": "Numpy for complex data analysis" }, { "code": null, "e": 1917, "s": 1890, "text": "Keras for Machine learning" }, { "code": null, "e": 1947, "s": 1917, "text": "SciPy for technical computing" }, { "code": null, "e": 1978, "s": 1947, "text": "Seaborn for data visualization" }, { "code": null, "e": 2500, "s": 1978, "text": "Data science involves data collection, data sorting, data analysis, and data visualization. Python provides amazing functionality to tackle statistics and complex mathematical calculations. The presence of in-built libraries provides convenience to data science professionals. Some of the popular libraries that provide ease in the data science process are TensorFlow, Pandas, and Socket learning. These libraries provide an ecosystem for fine-tuning data models, data preprocessing, and performing complex data analysis." }, { "code": null, "e": 2903, "s": 2500, "text": "With the rapidly growing gaming industry Python has proved to be an exceptional option for game development. Popular games like Pirates of the Caribbean, Bridge commander, and Battlefield 2 use Python programming for a wide range of functionalities and addons. The presence of popular 2D and 3D gaming libraries like pygame, panda3D, and Cocos2D make the game development process completely effortless." }, { "code": null, "e": 3208, "s": 2903, "text": "Audio and video applications are undoubtedly the most amazing feature of Python. Python is equipped with a lot of tools and libraries to accomplish your task flawlessly. Applications that are coded in Python include popular ones like Netflix, Spotify, and YouTube. This can be handled by libraries like " }, { "code": null, "e": 3215, "s": 3208, "text": "Dejavu" }, { "code": null, "e": 3219, "s": 3215, "text": "Pyo" }, { "code": null, "e": 3226, "s": 3219, "text": "Mingus" }, { "code": null, "e": 3232, "s": 3226, "text": "SciPy" }, { "code": null, "e": 3239, "s": 3232, "text": "OpenCV" }, { "code": null, "e": 3413, "s": 3239, "text": "Python is just the perfect option for software development. Popular applications like Google, Netflix, and Reddit all use Python. This language offers amazing features like:" }, { "code": null, "e": 3437, "s": 3413, "text": "Platform independence " }, { "code": null, "e": 3502, "s": 3437, "text": "Inbuilt libraries and frameworks to provide ease of development." }, { "code": null, "e": 3544, "s": 3502, "text": "Enhanced code reusability and readability" }, { "code": null, "e": 3563, "s": 3544, "text": "High compatibility" }, { "code": null, "e": 3784, "s": 3563, "text": "Apart from these Python offers enhanced features to work with rapidly growing technologies like Machine learning and Artificial intelligence. All these embedded features make it a popular choice for software development." }, { "code": null, "e": 4296, "s": 3784, "text": "CAD refers to computer-aided design; it is the process of creating 3D and 2D models digitally. This application has replaced manual drift and is used by architects, product designers, and construction managers to design products with extremely high consistency. Python is embedded with amazing applications like Blender, FreeCAD, open cascade, and a lot more to efficiently design products. These provide enhanced features like technical drawing, dynamic system development, recordings, file export, and import." }, { "code": null, "e": 4471, "s": 4296, "text": "Python offers excellent security and scalability features that make it perfect for delivering high-performance business applications. It has inbuilt libraries and tools like:" }, { "code": null, "e": 4580, "s": 4471, "text": "Odoo is business management software that provides you with an automated solution for your business process." }, { "code": null, "e": 4749, "s": 4580, "text": "Tryton is easy-to-use open-source business software. It has fully integrated features like financial accounting, sales, CRM, purchasing, shipping, and the list goes on." }, { "code": null, "e": 4831, "s": 4749, "text": "All these distinguishing features make it fit for creating business applications." }, { "code": null, "e": 5116, "s": 4831, "text": "Python is an interactive programming language that helps developers to create GUIs easily and efficiently. It has a huge list of inbuilt tools like PyQT, kivy, wxWidgets, and many other libraries like them to build a fully functional GUI in an extremely secure and efficient manner. " }, { "code": null, "e": 5414, "s": 5116, "text": "Web scraping is an automated process used to extract information from websites in an easier and faster way. The information is used by researchers, organizations, and analysts for a wide variety of tasks. Python has a wide range of features that make it suitable for web scraping some of them are:" }, { "code": null, "e": 5482, "s": 5414, "text": "A concise syntax that enhances the readability and saves your time." }, { "code": null, "e": 5607, "s": 5482, "text": "A wide range of libraries and tools like pandas, matplotlib, and Selenium makes the web scraping process easy and efficient." }, { "code": null, "e": 5634, "s": 5607, "text": "Easy to use and understand" }, { "code": null, "e": 5684, "s": 5634, "text": "Some other real-world applications of Python are:" }, { "code": null, "e": 5788, "s": 5684, "text": "Robotics and automation by the use of inbuilt libraries and tools like PyDy, Dart, PyRobot, and pyro. " }, { "code": null, "e": 5906, "s": 5788, "text": "Image processing: some of the amazing libraries and tools for image processing are Blender, OpenCV, Houdini, and PIL." }, { "code": null, "e": 6013, "s": 5906, "text": "Scientific applications are facilitated by popular libraries like Pandas, Matplotlib, SciPy, and many more" }, { "code": null, "e": 6447, "s": 6013, "text": "Conclusion: Python is a concise and extremely powerful language that is rapidly gaining popularity. It has been the epicenter of most amazing technologies like AI, automation, and machine learning. Further, it is used to facilitate hot subjects like data analysis and data visualization. In this blog, we have tried to give you a basic idea about the top 10 python applications in the real world. We hope that you found this helpful!" }, { "code": null, "e": 6453, "s": 6447, "text": "GBlog" }, { "code": null, "e": 6460, "s": 6453, "text": "Python" }, { "code": null, "e": 6558, "s": 6460, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6613, "s": 6558, "text": "GEEK-O-LYMPICS 2022 - May The Geeks Force Be With You!" }, { "code": null, "e": 6650, "s": 6613, "text": "Geek Streak - 24 Days POTD Challenge" }, { "code": null, "e": 6688, "s": 6650, "text": "What is Hashing | A Complete Tutorial" }, { "code": null, "e": 6754, "s": 6688, "text": "GeeksforGeeks Jobathon - Are You Ready For This Hiring Challenge?" }, { "code": null, "e": 6825, "s": 6754, "text": "GeeksforGeeks Job-A-Thon Exclusive - Hiring Challenge For Amazon Alexa" }, { "code": null, "e": 6853, "s": 6825, "text": "Read JSON file using Python" }, { "code": null, "e": 6903, "s": 6853, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 6925, "s": 6903, "text": "Python map() function" } ]
Make a fair coin from a biased coin
10 Sep, 2021 You are given a function foo() that represents a biased coin. When foo() is called, it returns 0 with 60% probability, and 1 with 40% probability. Write a new function that returns 0 and 1 with a 50% probability each. Your function should use only foo(), no other library method. Solution: We know foo() returns 0 with 60% probability. How can we ensure that 0 and 1 are returned with a 50% probability? The solution is similar to this post. If we can somehow get two cases with equal probability, then we are done. We call foo() two times. Both calls will return 0 with a 60% probability. So the two pairs (0, 1) and (1, 0) will be generated with equal probability from two calls of foo(). Let us see how.(0, 1): The probability to get 0 followed by 1 from two calls of foo() = 0.6 * 0.4 = 0.24 (1, 0): The probability to get 1 followed by 0 from two calls of foo() = 0.4 * 0.6 = 0.24So the two cases appear with equal probability. The idea is to return consider only the above two cases, return 0 in one case, return 1 in other case. For other cases [(0, 0) and (1, 1)], recur until you end up in any of the above two cases. The below program depicts how we can use foo() to return 0 and 1 with equal probability. C++ C Java Python3 C# PHP Javascript #include <bits/stdc++.h>using namespace std; int foo() // given method that returns 0 // with 60% probability and 1 with 40%{ // some code here} // returns both 0 and 1 with 50% probabilityint my_fun(){ int val1 = foo(); int val2 = foo(); if (val1 == 0 && val2 == 1) return 0; // Will reach here with // 0.24 probability if (val1 == 1 && val2 == 0) return 1; // Will reach here with // 0.24 probability return my_fun(); // will reach here with // (1 - 0.24 - 0.24) probability} // Driver Codeint main(){ cout << my_fun(); return 0;} // This is code is contributed// by rathbhupendra #include <stdio.h> int foo() // given method that returns 0 with 60% // probability and 1 with 40%{ // some code here} // returns both 0 and 1 with 50% probabilityint my_fun(){ int val1 = foo(); int val2 = foo(); if (val1 == 0 && val2 == 1) return 0; // Will reach here with 0.24 probability if (val1 == 1 && val2 == 0) return 1; // // Will reach here with 0.24 // probability return my_fun(); // will reach here with (1 - 0.24 - // 0.24) probability} int main(){ printf("%d ", my_fun()); return 0;} import java.io.*; class GFG { // Given method that returns 0 // with 60% probability and 1 with 40% static int foo() { // some code here } // Returns both 0 and 1 with 50% probability static int my_fun() { int val1 = foo(); int val2 = foo(); if (val1 == 0 && val2 == 1) return 0; // Will reach here with // 0.24 probability if (val1 == 1 && val2 == 0) return 1; // Will reach here with // 0.24 probability return my_fun(); // will reach here with // (1 - 0.24 - 0.24) probability } // Driver Code public static void main(String[] args) { System.out.println(my_fun()); }} // This code is contributed by ShubhamCoder # Python3 program for the# above approachdef foo(): # Some code here pass # Returns both 0 and 1# with 50% probabilitydef my_fun(): val1, val2 = foo(), foo() if val1 ^ val2: # Will reach here with # (0.24 + 0.24) probability return val1 # Will reach here with # (1 - 0.24 - 0.24) probability return my_fun() # Driver Codeif __name__ == '__main__': print(my_fun()) # This code is contributed by sgshah2 using System; class GFG { // given method that returns 0 // with 60% probability and 1 with 40% static int foo() { // some code here } // returns both 0 and 1 with 50% probability static int my_fun() { int val1 = foo(); int val2 = foo(); if (val1 == 0 && val2 == 1) return 0; // Will reach here with // 0.24 probability if (val1 == 1 && val2 == 0) return 1; // Will reach here with // 0.24 probability return my_fun(); // will reach here with // (1 - 0.24 - 0.24) probability } // Driver Code static public void Main() { Console.Write(my_fun()); }} // This is code is contributed// by ShubhamCoder <?php function foo() // given method that returns 0 // with 60% probability and 1 with 40%{ // some code here} // returns both 0 and 1 with 50% probabilityfunction my_fun(){ $val1 = foo(); $val2 = foo(); if ($val1 == 0 && $val2 == 1) return 0; // Will reach here with // 0.24 probability if ($val1 == 1 && $val2 == 0) return 1; // Will reach here with // 0.24 probability return my_fun(); // will reach here with // (1 - 0.24 - 0.24) probability} // Driver Codeecho my_fun(); // This is code is contributed// by Akanksha Rai?> <script> // Given method that returns 0 with// 60% probability and 1 with 40%function foo(){ // Some code here} // Returns both 0 and 1 with// 50% probabilityfunction my_fun(){ var val1 = foo(); var val2 = foo(); if (val1 == 0 && val2 == 1) return 0; // Will reach here with // 0.24 probability if (val1 == 1 && val2 == 0) return 1; // Will reach here with // 0.24 probability return my_fun(); // Will reach here with // (1 - 0.24 - 0.24) probability} // Driver Codedocument.write(my_fun()); // This code is contributed by noob2000 </script> Time Complexity: O(1) Auxiliary Space: O(1) References: http://en.wikipedia.org/wiki/Fair_coin#Fair_results_from_a_biased_coinThis article is compiled by Shashank Sinha and reviewed by GeeksforGeeks team. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. rathbhupendra Akanksha_Rai shubhamsingh84100 sgshah2 noob2000 subhammahato348 Mathematical Randomized Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Operators in C / C++ Prime Numbers Sieve of Eratosthenes Program to find GCD or HCF of two numbers K'th Smallest/Largest Element in Unsorted Array | Set 2 (Expected Linear Time) Shuffle a given array using Fisher–Yates shuffle Algorithm QuickSort using Random Pivoting Shuffle or Randomize a list in Java Generating Random String Using PHP
[ { "code": null, "e": 54, "s": 26, "text": "\n10 Sep, 2021" }, { "code": null, "e": 334, "s": 54, "text": "You are given a function foo() that represents a biased coin. When foo() is called, it returns 0 with 60% probability, and 1 with 40% probability. Write a new function that returns 0 and 1 with a 50% probability each. Your function should use only foo(), no other library method." }, { "code": null, "e": 1182, "s": 334, "text": "Solution: We know foo() returns 0 with 60% probability. How can we ensure that 0 and 1 are returned with a 50% probability? The solution is similar to this post. If we can somehow get two cases with equal probability, then we are done. We call foo() two times. Both calls will return 0 with a 60% probability. So the two pairs (0, 1) and (1, 0) will be generated with equal probability from two calls of foo(). Let us see how.(0, 1): The probability to get 0 followed by 1 from two calls of foo() = 0.6 * 0.4 = 0.24 (1, 0): The probability to get 1 followed by 0 from two calls of foo() = 0.4 * 0.6 = 0.24So the two cases appear with equal probability. The idea is to return consider only the above two cases, return 0 in one case, return 1 in other case. For other cases [(0, 0) and (1, 1)], recur until you end up in any of the above two cases. " }, { "code": null, "e": 1273, "s": 1182, "text": "The below program depicts how we can use foo() to return 0 and 1 with equal probability. " }, { "code": null, "e": 1277, "s": 1273, "text": "C++" }, { "code": null, "e": 1279, "s": 1277, "text": "C" }, { "code": null, "e": 1284, "s": 1279, "text": "Java" }, { "code": null, "e": 1292, "s": 1284, "text": "Python3" }, { "code": null, "e": 1295, "s": 1292, "text": "C#" }, { "code": null, "e": 1299, "s": 1295, "text": "PHP" }, { "code": null, "e": 1310, "s": 1299, "text": "Javascript" }, { "code": "#include <bits/stdc++.h>using namespace std; int foo() // given method that returns 0 // with 60% probability and 1 with 40%{ // some code here} // returns both 0 and 1 with 50% probabilityint my_fun(){ int val1 = foo(); int val2 = foo(); if (val1 == 0 && val2 == 1) return 0; // Will reach here with // 0.24 probability if (val1 == 1 && val2 == 0) return 1; // Will reach here with // 0.24 probability return my_fun(); // will reach here with // (1 - 0.24 - 0.24) probability} // Driver Codeint main(){ cout << my_fun(); return 0;} // This is code is contributed// by rathbhupendra", "e": 1994, "s": 1310, "text": null }, { "code": "#include <stdio.h> int foo() // given method that returns 0 with 60% // probability and 1 with 40%{ // some code here} // returns both 0 and 1 with 50% probabilityint my_fun(){ int val1 = foo(); int val2 = foo(); if (val1 == 0 && val2 == 1) return 0; // Will reach here with 0.24 probability if (val1 == 1 && val2 == 0) return 1; // // Will reach here with 0.24 // probability return my_fun(); // will reach here with (1 - 0.24 - // 0.24) probability} int main(){ printf(\"%d \", my_fun()); return 0;}", "e": 2578, "s": 1994, "text": null }, { "code": "import java.io.*; class GFG { // Given method that returns 0 // with 60% probability and 1 with 40% static int foo() { // some code here } // Returns both 0 and 1 with 50% probability static int my_fun() { int val1 = foo(); int val2 = foo(); if (val1 == 0 && val2 == 1) return 0; // Will reach here with // 0.24 probability if (val1 == 1 && val2 == 0) return 1; // Will reach here with // 0.24 probability return my_fun(); // will reach here with // (1 - 0.24 - 0.24) probability } // Driver Code public static void main(String[] args) { System.out.println(my_fun()); }} // This code is contributed by ShubhamCoder", "e": 3376, "s": 2578, "text": null }, { "code": "# Python3 program for the# above approachdef foo(): # Some code here pass # Returns both 0 and 1# with 50% probabilitydef my_fun(): val1, val2 = foo(), foo() if val1 ^ val2: # Will reach here with # (0.24 + 0.24) probability return val1 # Will reach here with # (1 - 0.24 - 0.24) probability return my_fun() # Driver Codeif __name__ == '__main__': print(my_fun()) # This code is contributed by sgshah2", "e": 3848, "s": 3376, "text": null }, { "code": "using System; class GFG { // given method that returns 0 // with 60% probability and 1 with 40% static int foo() { // some code here } // returns both 0 and 1 with 50% probability static int my_fun() { int val1 = foo(); int val2 = foo(); if (val1 == 0 && val2 == 1) return 0; // Will reach here with // 0.24 probability if (val1 == 1 && val2 == 0) return 1; // Will reach here with // 0.24 probability return my_fun(); // will reach here with // (1 - 0.24 - 0.24) probability } // Driver Code static public void Main() { Console.Write(my_fun()); }} // This is code is contributed// by ShubhamCoder", "e": 4612, "s": 3848, "text": null }, { "code": "<?php function foo() // given method that returns 0 // with 60% probability and 1 with 40%{ // some code here} // returns both 0 and 1 with 50% probabilityfunction my_fun(){ $val1 = foo(); $val2 = foo(); if ($val1 == 0 && $val2 == 1) return 0; // Will reach here with // 0.24 probability if ($val1 == 1 && $val2 == 0) return 1; // Will reach here with // 0.24 probability return my_fun(); // will reach here with // (1 - 0.24 - 0.24) probability} // Driver Codeecho my_fun(); // This is code is contributed// by Akanksha Rai?>", "e": 5241, "s": 4612, "text": null }, { "code": "<script> // Given method that returns 0 with// 60% probability and 1 with 40%function foo(){ // Some code here} // Returns both 0 and 1 with// 50% probabilityfunction my_fun(){ var val1 = foo(); var val2 = foo(); if (val1 == 0 && val2 == 1) return 0; // Will reach here with // 0.24 probability if (val1 == 1 && val2 == 0) return 1; // Will reach here with // 0.24 probability return my_fun(); // Will reach here with // (1 - 0.24 - 0.24) probability} // Driver Codedocument.write(my_fun()); // This code is contributed by noob2000 </script>", "e": 5912, "s": 5241, "text": null }, { "code": null, "e": 5934, "s": 5912, "text": "Time Complexity: O(1)" }, { "code": null, "e": 5956, "s": 5934, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 6465, "s": 5956, "text": "References: http://en.wikipedia.org/wiki/Fair_coin#Fair_results_from_a_biased_coinThis article is compiled by Shashank Sinha and reviewed by GeeksforGeeks team. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. " }, { "code": null, "e": 6479, "s": 6465, "text": "rathbhupendra" }, { "code": null, "e": 6492, "s": 6479, "text": "Akanksha_Rai" }, { "code": null, "e": 6510, "s": 6492, "text": "shubhamsingh84100" }, { "code": null, "e": 6518, "s": 6510, "text": "sgshah2" }, { "code": null, "e": 6527, "s": 6518, "text": "noob2000" }, { "code": null, "e": 6543, "s": 6527, "text": "subhammahato348" }, { "code": null, "e": 6556, "s": 6543, "text": "Mathematical" }, { "code": null, "e": 6567, "s": 6556, "text": "Randomized" }, { "code": null, "e": 6580, "s": 6567, "text": "Mathematical" }, { "code": null, "e": 6678, "s": 6580, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6702, "s": 6678, "text": "Merge two sorted arrays" }, { "code": null, "e": 6723, "s": 6702, "text": "Operators in C / C++" }, { "code": null, "e": 6737, "s": 6723, "text": "Prime Numbers" }, { "code": null, "e": 6759, "s": 6737, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 6801, "s": 6759, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 6880, "s": 6801, "text": "K'th Smallest/Largest Element in Unsorted Array | Set 2 (Expected Linear Time)" }, { "code": null, "e": 6939, "s": 6880, "text": "Shuffle a given array using Fisher–Yates shuffle Algorithm" }, { "code": null, "e": 6971, "s": 6939, "text": "QuickSort using Random Pivoting" }, { "code": null, "e": 7007, "s": 6971, "text": "Shuffle or Randomize a list in Java" } ]
Node.js GM thumbnail() Function
11 Oct, 2021 The thumbnail() function is an inbuilt function in the GraphicsMagick library which is used to make the thumbnail image of the given image. The function returns the true value on success.Syntax: thumbnail( x, y ) Parameters: This function accepts two parameters as mentioned above and described below: x: This parameter is used to specify width of the thumbnail image. y: This parameter is used to specify height of the thumbnail image. Return Value: This function returns the GraphicsMagick object.Original Image: Example 1: javascript // Include gm libraryvar gm = require('gm'); // Import the imagegm('1.png') // Invoke thumbnail function x, y as 300, 200.thumbnail(300, 200) // Process and Write the image.write("thumbnail1.png", function (err) { if (!err) console.log('done');}); Output: Example 2: javascript // Include gm libraryvar gm = require('gm'); // Import the imagegm(600, 300, 'white') // set the color for the stroke.stroke("green", 3) // Set the font .font("Helvetica.ttf", 60) //Call to drawText Function.drawText(100, 280, "GeeksforGeeks!") // Invoke thumbnail function// on x, y as 300, 150.thumbnail(300, 150) // Process and write the image .write("thumbnail2.png", function (err) { if (!err) console.log('done');}); Output: Reference: http://www.graphicsmagick.org/GraphicsMagick.html#details-rotate https://www.npmjs.com/package/gm adnanirshad158 Image-Processing Node.js-GM Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Oct, 2021" }, { "code": null, "e": 225, "s": 28, "text": "The thumbnail() function is an inbuilt function in the GraphicsMagick library which is used to make the thumbnail image of the given image. The function returns the true value on success.Syntax: " }, { "code": null, "e": 243, "s": 225, "text": "thumbnail( x, y )" }, { "code": null, "e": 334, "s": 243, "text": "Parameters: This function accepts two parameters as mentioned above and described below: " }, { "code": null, "e": 401, "s": 334, "text": "x: This parameter is used to specify width of the thumbnail image." }, { "code": null, "e": 469, "s": 401, "text": "y: This parameter is used to specify height of the thumbnail image." }, { "code": null, "e": 548, "s": 469, "text": "Return Value: This function returns the GraphicsMagick object.Original Image: " }, { "code": null, "e": 560, "s": 548, "text": "Example 1: " }, { "code": null, "e": 571, "s": 560, "text": "javascript" }, { "code": "// Include gm libraryvar gm = require('gm'); // Import the imagegm('1.png') // Invoke thumbnail function x, y as 300, 200.thumbnail(300, 200) // Process and Write the image.write(\"thumbnail1.png\", function (err) { if (!err) console.log('done');});", "e": 823, "s": 571, "text": null }, { "code": null, "e": 832, "s": 823, "text": "Output: " }, { "code": null, "e": 844, "s": 832, "text": "Example 2: " }, { "code": null, "e": 855, "s": 844, "text": "javascript" }, { "code": "// Include gm libraryvar gm = require('gm'); // Import the imagegm(600, 300, 'white') // set the color for the stroke.stroke(\"green\", 3) // Set the font .font(\"Helvetica.ttf\", 60) //Call to drawText Function.drawText(100, 280, \"GeeksforGeeks!\") // Invoke thumbnail function// on x, y as 300, 150.thumbnail(300, 150) // Process and write the image .write(\"thumbnail2.png\", function (err) { if (!err) console.log('done');});", "e": 1286, "s": 855, "text": null }, { "code": null, "e": 1295, "s": 1286, "text": "Output: " }, { "code": null, "e": 1307, "s": 1295, "text": "Reference: " }, { "code": null, "e": 1372, "s": 1307, "text": "http://www.graphicsmagick.org/GraphicsMagick.html#details-rotate" }, { "code": null, "e": 1405, "s": 1372, "text": "https://www.npmjs.com/package/gm" }, { "code": null, "e": 1420, "s": 1405, "text": "adnanirshad158" }, { "code": null, "e": 1437, "s": 1420, "text": "Image-Processing" }, { "code": null, "e": 1448, "s": 1437, "text": "Node.js-GM" }, { "code": null, "e": 1456, "s": 1448, "text": "Node.js" }, { "code": null, "e": 1473, "s": 1456, "text": "Web Technologies" } ]
Inverse of Matrix in R
22 Apr, 2020 The inverse of a matrix is just a reciprocal of the matrix as we do in normal arithmetic for a single number which is used to solve the equations to find the value of unknown variables. The inverse of a matrix is that matrix which when multiplied with the original matrix will give as an identity matrix. Finding the inverse of a matrix is one of the most common tasks while working with linear algebraic expressions. We can find the inverse of only those matrices which are square and whose determinant is non-zero. Note: Ensure that the matrix is non-singular that is the determinant should not be 0. Matrix Equation: where,A^-1 is the inverse of matrix A.x is the unknown variable column.B is the solution matrix. Equation for Inverse of Matrix: There are two ways in which the inverse of a Matrix can be found: Using the solve() function:solve() is a generic built-in function in R which is helpful for solving the following linear algebraic equation just as shown above in the image. It can be applied both on vectors as well as a matrix.# R program to find inverse of a Matrix # Create 3 different vectors# using combine method.a1 <- c(3, 2, 5)a2 <- c(2, 3, 2)a3 <- c(5, 2, 4) # bind the three vectors into a matrix # using rbind() which is basically# row-wise binding.A <- rbind(a1, a2, a3) # print the original matrixprint(A) # Use the solve() function # to calculate the inverse.T1 <- solve(A) # print the inverse of the matrix.print(T1)Output: [,1] [,2] [,3] a1 3 2 5 a2 2 3 2 a3 5 2 4 a1 a2 a3 [1,] -0.29629630 -0.07407407 0.4074074 [2,] -0.07407407 0.48148148 -0.1481481 [3,] 0.40740741 -0.14814815 -0.1851852 # R program to find inverse of a Matrix # Create 3 different vectors# using combine method.a1 <- c(3, 2, 5)a2 <- c(2, 3, 2)a3 <- c(5, 2, 4) # bind the three vectors into a matrix # using rbind() which is basically# row-wise binding.A <- rbind(a1, a2, a3) # print the original matrixprint(A) # Use the solve() function # to calculate the inverse.T1 <- solve(A) # print the inverse of the matrix.print(T1) Output: [,1] [,2] [,3] a1 3 2 5 a2 2 3 2 a3 5 2 4 a1 a2 a3 [1,] -0.29629630 -0.07407407 0.4074074 [2,] -0.07407407 0.48148148 -0.1481481 [3,] 0.40740741 -0.14814815 -0.1851852 Using the inv() function:inv() function is a built-in function in R which is especially used to find the inverse of a matrix.Note:Ensure that you have installed the ‘matlib’ package in your environment.Finding Determinant of Matrix:# Create 3 different vectors.a1 <- c(3, 2, 8)a2 <- c(6, 3, 2)a3 <- c(5, 2, 4) # Bind the 3 matrices row-wise # using the rbind() function.A <- rbind(a1, a2, a3) # determinant of matrixprint(det(A))Output:-28Finding Inverse of Matrix:# find inverse using the inv() function.print(inv(t(A))) Output: [1,] -0.2857143 0.5 0.1071429 [2,] -0.2857143 1.0 -0.1428571 [3,] 0.7142857 -1.5 0.1071429 Note:Ensure that you have installed the ‘matlib’ package in your environment. Finding Determinant of Matrix: # Create 3 different vectors.a1 <- c(3, 2, 8)a2 <- c(6, 3, 2)a3 <- c(5, 2, 4) # Bind the 3 matrices row-wise # using the rbind() function.A <- rbind(a1, a2, a3) # determinant of matrixprint(det(A)) Output: -28 Finding Inverse of Matrix: # find inverse using the inv() function.print(inv(t(A))) Output: [1,] -0.2857143 0.5 0.1071429 [2,] -0.2857143 1.0 -0.1428571 [3,] 0.7142857 -1.5 0.1071429 Picked R-Matrix R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Filter data by multiple conditions in R using Dplyr Change Color of Bars in Barchart using ggplot2 in R How to Split Column Into Multiple Columns in R DataFrame? Group by function in R using Dplyr How to change Row Names of DataFrame in R ? How to Change Axis Scales in R Plots? How to filter R DataFrame by values in a column? R - if statement Remove rows with NA in one column of R DataFrame Logistic Regression in R Programming
[ { "code": null, "e": 54, "s": 26, "text": "\n22 Apr, 2020" }, { "code": null, "e": 359, "s": 54, "text": "The inverse of a matrix is just a reciprocal of the matrix as we do in normal arithmetic for a single number which is used to solve the equations to find the value of unknown variables. The inverse of a matrix is that matrix which when multiplied with the original matrix will give as an identity matrix." }, { "code": null, "e": 571, "s": 359, "text": "Finding the inverse of a matrix is one of the most common tasks while working with linear algebraic expressions. We can find the inverse of only those matrices which are square and whose determinant is non-zero." }, { "code": null, "e": 657, "s": 571, "text": "Note: Ensure that the matrix is non-singular that is the determinant should not be 0." }, { "code": null, "e": 674, "s": 657, "text": "Matrix Equation:" }, { "code": null, "e": 771, "s": 674, "text": "where,A^-1 is the inverse of matrix A.x is the unknown variable column.B is the solution matrix." }, { "code": null, "e": 803, "s": 771, "text": "Equation for Inverse of Matrix:" }, { "code": null, "e": 869, "s": 803, "text": "There are two ways in which the inverse of a Matrix can be found:" }, { "code": null, "e": 1747, "s": 869, "text": "Using the solve() function:solve() is a generic built-in function in R which is helpful for solving the following linear algebraic equation just as shown above in the image. It can be applied both on vectors as well as a matrix.# R program to find inverse of a Matrix # Create 3 different vectors# using combine method.a1 <- c(3, 2, 5)a2 <- c(2, 3, 2)a3 <- c(5, 2, 4) # bind the three vectors into a matrix # using rbind() which is basically# row-wise binding.A <- rbind(a1, a2, a3) # print the original matrixprint(A) # Use the solve() function # to calculate the inverse.T1 <- solve(A) # print the inverse of the matrix.print(T1)Output: [,1] [,2] [,3]\na1 3 2 5\na2 2 3 2\na3 5 2 4\n\n a1 a2 a3\n[1,] -0.29629630 -0.07407407 0.4074074\n[2,] -0.07407407 0.48148148 -0.1481481\n[3,] 0.40740741 -0.14814815 -0.1851852\n\n" }, { "code": "# R program to find inverse of a Matrix # Create 3 different vectors# using combine method.a1 <- c(3, 2, 5)a2 <- c(2, 3, 2)a3 <- c(5, 2, 4) # bind the three vectors into a matrix # using rbind() which is basically# row-wise binding.A <- rbind(a1, a2, a3) # print the original matrixprint(A) # Use the solve() function # to calculate the inverse.T1 <- solve(A) # print the inverse of the matrix.print(T1)", "e": 2156, "s": 1747, "text": null }, { "code": null, "e": 2164, "s": 2156, "text": "Output:" }, { "code": null, "e": 2399, "s": 2164, "text": " [,1] [,2] [,3]\na1 3 2 5\na2 2 3 2\na3 5 2 4\n\n a1 a2 a3\n[1,] -0.29629630 -0.07407407 0.4074074\n[2,] -0.07407407 0.48148148 -0.1481481\n[3,] 0.40740741 -0.14814815 -0.1851852\n\n" }, { "code": null, "e": 3053, "s": 2399, "text": "Using the inv() function:inv() function is a built-in function in R which is especially used to find the inverse of a matrix.Note:Ensure that you have installed the ‘matlib’ package in your environment.Finding Determinant of Matrix:# Create 3 different vectors.a1 <- c(3, 2, 8)a2 <- c(6, 3, 2)a3 <- c(5, 2, 4) # Bind the 3 matrices row-wise # using the rbind() function.A <- rbind(a1, a2, a3) # determinant of matrixprint(det(A))Output:-28Finding Inverse of Matrix:# find inverse using the inv() function.print(inv(t(A))) Output: \n[1,] -0.2857143 0.5 0.1071429\n[2,] -0.2857143 1.0 -0.1428571\n[3,] 0.7142857 -1.5 0.1071429\n" }, { "code": null, "e": 3131, "s": 3053, "text": "Note:Ensure that you have installed the ‘matlib’ package in your environment." }, { "code": null, "e": 3162, "s": 3131, "text": "Finding Determinant of Matrix:" }, { "code": "# Create 3 different vectors.a1 <- c(3, 2, 8)a2 <- c(6, 3, 2)a3 <- c(5, 2, 4) # Bind the 3 matrices row-wise # using the rbind() function.A <- rbind(a1, a2, a3) # determinant of matrixprint(det(A))", "e": 3362, "s": 3162, "text": null }, { "code": null, "e": 3370, "s": 3362, "text": "Output:" }, { "code": null, "e": 3374, "s": 3370, "text": "-28" }, { "code": null, "e": 3401, "s": 3374, "text": "Finding Inverse of Matrix:" }, { "code": "# find inverse using the inv() function.print(inv(t(A))) ", "e": 3459, "s": 3401, "text": null }, { "code": null, "e": 3467, "s": 3459, "text": "Output:" }, { "code": null, "e": 3590, "s": 3467, "text": " \n[1,] -0.2857143 0.5 0.1071429\n[2,] -0.2857143 1.0 -0.1428571\n[3,] 0.7142857 -1.5 0.1071429\n" }, { "code": null, "e": 3597, "s": 3590, "text": "Picked" }, { "code": null, "e": 3606, "s": 3597, "text": "R-Matrix" }, { "code": null, "e": 3617, "s": 3606, "text": "R Language" }, { "code": null, "e": 3715, "s": 3617, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3767, "s": 3715, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 3819, "s": 3767, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 3877, "s": 3819, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 3912, "s": 3877, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 3956, "s": 3912, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 3994, "s": 3956, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 4043, "s": 3994, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 4060, "s": 4043, "text": "R - if statement" }, { "code": null, "e": 4109, "s": 4060, "text": "Remove rows with NA in one column of R DataFrame" } ]
Ruby - if...else, case, unless
Ruby offers conditional structures that are pretty common to modern languages. Here, we will explain all the conditional statements and modifiers available in Ruby. if conditional [then] code... [elsif conditional [then] code...]... [else code...] end if expressions are used for conditional execution. The values false and nil are false, and everything else are true. Notice Ruby uses elsif, not else if nor elif. Executes code if the conditional is true. If the conditional is not true, code specified in the else clause is executed. An if expression's conditional is separated from code by the reserved word then, a newline, or a semicolon. #!/usr/bin/ruby x = 1 if x > 2 puts "x is greater than 2" elsif x <= 2 and x!=0 puts "x is 1" else puts "I can't guess the number" end x is 1 code if condition Executes code if the conditional is true. #!/usr/bin/ruby $debug = 1 print "debug\n" if $debug This will produce the following result − debug unless conditional [then] code [else code ] end Executes code if conditional is false. If the conditional is true, code specified in the else clause is executed. #!/usr/bin/ruby x = 1 unless x>=2 puts "x is less than 2" else puts "x is greater than 2" end This will produce the following result − x is less than 2 code unless conditional Executes code if conditional is false. #!/usr/bin/ruby $var = 1 print "1 -- Value is set\n" if $var print "2 -- Value is set\n" unless $var $var = false print "3 -- Value is set\n" unless $var This will produce the following result − 1 -- Value is set 3 -- Value is set case expression [when expression [, expression ...] [then] code ]... [else code ] end Compares the expression specified by case and that specified by when using the === operator and executes the code of the when clause that matches. The expression specified by the when clause is evaluated as the left operand. If no when clauses match, case executes the code of the else clause. A when statement's expression is separated from code by the reserved word then, a newline, or a semicolon. Thus − case expr0 when expr1, expr2 stmt1 when expr3, expr4 stmt2 else stmt3 end is basically similar to the following − _tmp = expr0 if expr1 === _tmp || expr2 === _tmp stmt1 elsif expr3 === _tmp || expr4 === _tmp stmt2 else stmt3 end #!/usr/bin/ruby $age = 5 case $age when 0 .. 2 puts "baby" when 3 .. 6 puts "little child" when 7 .. 12 puts "child" when 13 .. 18 puts "youth" else puts "adult" end This will produce the following result − little child 46 Lectures 9.5 hours Eduonix Learning Solutions 97 Lectures 7.5 hours Skillbakerystudios 227 Lectures 40 hours YouAccel 19 Lectures 10 hours Programming Line 51 Lectures 5 hours Stone River ELearning 39 Lectures 4.5 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 2459, "s": 2294, "text": "Ruby offers conditional structures that are pretty common to modern languages. Here, we will explain all the conditional statements and modifiers available in Ruby." }, { "code": null, "e": 2556, "s": 2459, "text": "if conditional [then]\n code...\n[elsif conditional [then]\n code...]...\n[else\n code...]\nend\n" }, { "code": null, "e": 2719, "s": 2556, "text": "if expressions are used for conditional execution. The values false and nil are false, and everything else are true. Notice Ruby uses elsif, not else if nor elif." }, { "code": null, "e": 2840, "s": 2719, "text": "Executes code if the conditional is true. If the conditional is not true, code specified in the else clause is executed." }, { "code": null, "e": 2948, "s": 2840, "text": "An if expression's conditional is separated from code by the reserved word then, a newline, or a semicolon." }, { "code": null, "e": 3093, "s": 2948, "text": "#!/usr/bin/ruby\n\nx = 1\nif x > 2\n puts \"x is greater than 2\"\nelsif x <= 2 and x!=0\n puts \"x is 1\"\nelse\n puts \"I can't guess the number\"\nend" }, { "code": null, "e": 3101, "s": 3093, "text": "x is 1\n" }, { "code": null, "e": 3120, "s": 3101, "text": "code if condition\n" }, { "code": null, "e": 3162, "s": 3120, "text": "Executes code if the conditional is true." }, { "code": null, "e": 3216, "s": 3162, "text": "#!/usr/bin/ruby\n\n$debug = 1\nprint \"debug\\n\" if $debug" }, { "code": null, "e": 3257, "s": 3216, "text": "This will produce the following result −" }, { "code": null, "e": 3264, "s": 3257, "text": "debug\n" }, { "code": null, "e": 3319, "s": 3264, "text": "unless conditional [then]\n code\n[else\n code ]\nend\n" }, { "code": null, "e": 3433, "s": 3319, "text": "Executes code if conditional is false. If the conditional is true, code specified in the else clause is executed." }, { "code": null, "e": 3536, "s": 3433, "text": "#!/usr/bin/ruby\n\nx = 1 \nunless x>=2\n puts \"x is less than 2\"\n else\n puts \"x is greater than 2\"\nend" }, { "code": null, "e": 3577, "s": 3536, "text": "This will produce the following result −" }, { "code": null, "e": 3595, "s": 3577, "text": "x is less than 2\n" }, { "code": null, "e": 3620, "s": 3595, "text": "code unless conditional\n" }, { "code": null, "e": 3659, "s": 3620, "text": "Executes code if conditional is false." }, { "code": null, "e": 3816, "s": 3659, "text": "#!/usr/bin/ruby\n\n$var = 1\nprint \"1 -- Value is set\\n\" if $var\nprint \"2 -- Value is set\\n\" unless $var\n\n$var = false\nprint \"3 -- Value is set\\n\" unless $var" }, { "code": null, "e": 3857, "s": 3816, "text": "This will produce the following result −" }, { "code": null, "e": 3894, "s": 3857, "text": "1 -- Value is set\n3 -- Value is set\n" }, { "code": null, "e": 3987, "s": 3894, "text": "case expression\n[when expression [, expression ...] [then]\n code ]...\n[else\n code ]\nend\n" }, { "code": null, "e": 4134, "s": 3987, "text": "Compares the expression specified by case and that specified by when using the === operator and executes the code of the when clause that matches." }, { "code": null, "e": 4281, "s": 4134, "text": "The expression specified by the when clause is evaluated as the left operand. If no when clauses match, case executes the code of the else clause." }, { "code": null, "e": 4395, "s": 4281, "text": "A when statement's expression is separated from code by the reserved word then, a newline, or a semicolon. Thus −" }, { "code": null, "e": 4479, "s": 4395, "text": "case expr0\nwhen expr1, expr2\n stmt1\nwhen expr3, expr4\n stmt2\nelse\n stmt3\nend\n" }, { "code": null, "e": 4519, "s": 4479, "text": "is basically similar to the following −" }, { "code": null, "e": 4643, "s": 4519, "text": "_tmp = expr0\nif expr1 === _tmp || expr2 === _tmp\n stmt1\nelsif expr3 === _tmp || expr4 === _tmp\n stmt2\nelse\n stmt3\nend" }, { "code": null, "e": 4826, "s": 4643, "text": "#!/usr/bin/ruby\n\n$age = 5\ncase $age\nwhen 0 .. 2\n puts \"baby\"\nwhen 3 .. 6\n puts \"little child\"\nwhen 7 .. 12\n puts \"child\"\nwhen 13 .. 18\n puts \"youth\"\nelse\n puts \"adult\"\nend" }, { "code": null, "e": 4867, "s": 4826, "text": "This will produce the following result −" }, { "code": null, "e": 4881, "s": 4867, "text": "little child\n" }, { "code": null, "e": 4916, "s": 4881, "text": "\n 46 Lectures \n 9.5 hours \n" }, { "code": null, "e": 4944, "s": 4916, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 4979, "s": 4944, "text": "\n 97 Lectures \n 7.5 hours \n" }, { "code": null, "e": 4999, "s": 4979, "text": " Skillbakerystudios" }, { "code": null, "e": 5034, "s": 4999, "text": "\n 227 Lectures \n 40 hours \n" }, { "code": null, "e": 5044, "s": 5034, "text": " YouAccel" }, { "code": null, "e": 5078, "s": 5044, "text": "\n 19 Lectures \n 10 hours \n" }, { "code": null, "e": 5096, "s": 5078, "text": " Programming Line" }, { "code": null, "e": 5129, "s": 5096, "text": "\n 51 Lectures \n 5 hours \n" }, { "code": null, "e": 5152, "s": 5129, "text": " Stone River ELearning" }, { "code": null, "e": 5187, "s": 5152, "text": "\n 39 Lectures \n 4.5 hours \n" }, { "code": null, "e": 5210, "s": 5187, "text": " Stone River ELearning" }, { "code": null, "e": 5217, "s": 5210, "text": " Print" }, { "code": null, "e": 5228, "s": 5217, "text": " Add Notes" } ]
Setting column values as column names in the MySQL query result?
To set column values as column names in the query result, you need to use a CASE statement. The syntax is as follows − select yourIdColumnName, max(case when (yourColumnName1='yourValue1') then yourColumnName2 else NULL end) as 'yourValue1', max(case when (yourColumnName1='yourValue2') then yourColumnName2 else NULL end) as 'yourValue2', max(case when yourColumnName1='yourValue3') then yourColumnName2 else NULL end) as 'yourValue3’, . . N from valueAsColumn group by yourIdColumnName order by yourIdColumnName; To understand the above syntax, let us create a table. The query to create a table is as follows − mysql> create table valueAsColumn -> ( -> UserId int, -> UserColumn1 varchar(10), -> UserColumn2 varchar(10) -> ); Query OK, 0 rows affected (0.75 sec) Now you can insert some records in the table using insert command. The query is as follows − mysql> insert into valueAsColumn values(0,'John','A+'); Query OK, 1 row affected (0.18 sec) mysql> insert into valueAsColumn values(0,'Carol','B'); Query OK, 1 row affected (0.17 sec) mysql> insert into valueAsColumn values(0,'Sam','C'); Query OK, 1 row affected (0.17 sec) mysql> insert into valueAsColumn values(1,'John','D'); Query OK, 1 row affected (0.20 sec) mysql> insert into valueAsColumn values(1,'Carol','A'); Query OK, 1 row affected (0.20 sec) mysql> insert into valueAsColumn values(1,'Carol','C'); Query OK, 1 row affected (0.15 sec) Display all records from the table using a select statement. The query is as follows − mysql> select *from valueAsColumn; The following is the output − +--------+-------------+-------------+ | UserId | UserColumn1 | UserColumn2 | +--------+-------------+-------------+ | 0 | John | A+ | | 0 | Carol | B | | 0 | Sam | C | | 1 | John | D | | 1 | Carol | A | | 1 | Carol | C | +--------+-------------+-------------+ 6 rows in set (0.00 sec) Here is the query to set column value as column names − mysql> select UserId, -> max(case when (UserColumn1='John') then UserColumn2 else NULL end) as 'John', -> max(case when (UserColumn1='Carol') then UserColumn2 else NULL end) as 'Carol', -> max(case when (UserColumn1='Sam') then UserColumn2 else NULL end) as 'Sam' -> from valueAsColumn -> group by UserId -> order by UserId; The following is the output − +--------+------+-------+------+ | UserId | John | Carol | Sam | +--------+------+-------+------+ | 0 | A+ | B | C | | 1 | D | C | NULL | +--------+------+-------+------+ 2 rows in set (0.00 sec)
[ { "code": null, "e": 1154, "s": 1062, "text": "To set column values as column names in the query result, you need to use a CASE statement." }, { "code": null, "e": 1181, "s": 1154, "text": "The syntax is as follows −" }, { "code": null, "e": 1577, "s": 1181, "text": "select yourIdColumnName,\nmax(case when (yourColumnName1='yourValue1') then yourColumnName2 else NULL\nend) as 'yourValue1',\nmax(case when (yourColumnName1='yourValue2') then yourColumnName2 else NULL\nend) as 'yourValue2',\nmax(case when yourColumnName1='yourValue3') then yourColumnName2 else NULL\nend) as 'yourValue3’,\n.\n.\nN\nfrom valueAsColumn\ngroup by yourIdColumnName\norder by yourIdColumnName;" }, { "code": null, "e": 1676, "s": 1577, "text": "To understand the above syntax, let us create a table. The query to create a table is as follows −" }, { "code": null, "e": 1843, "s": 1676, "text": "mysql> create table valueAsColumn\n -> (\n -> UserId int,\n -> UserColumn1 varchar(10),\n -> UserColumn2 varchar(10)\n -> );\nQuery OK, 0 rows affected (0.75 sec)" }, { "code": null, "e": 1936, "s": 1843, "text": "Now you can insert some records in the table using insert command. The query is as follows −" }, { "code": null, "e": 2485, "s": 1936, "text": "mysql> insert into valueAsColumn values(0,'John','A+');\nQuery OK, 1 row affected (0.18 sec)\nmysql> insert into valueAsColumn values(0,'Carol','B');\nQuery OK, 1 row affected (0.17 sec)\nmysql> insert into valueAsColumn values(0,'Sam','C');\nQuery OK, 1 row affected (0.17 sec)\nmysql> insert into valueAsColumn values(1,'John','D');\nQuery OK, 1 row affected (0.20 sec)\nmysql> insert into valueAsColumn values(1,'Carol','A');\nQuery OK, 1 row affected (0.20 sec)\nmysql> insert into valueAsColumn values(1,'Carol','C');\nQuery OK, 1 row affected (0.15 sec)" }, { "code": null, "e": 2572, "s": 2485, "text": "Display all records from the table using a select statement. The query is as follows −" }, { "code": null, "e": 2607, "s": 2572, "text": "mysql> select *from valueAsColumn;" }, { "code": null, "e": 2637, "s": 2607, "text": "The following is the output −" }, { "code": null, "e": 3052, "s": 2637, "text": "+--------+-------------+-------------+\n| UserId | UserColumn1 | UserColumn2 |\n+--------+-------------+-------------+\n| 0 | John | A+ |\n| 0 | Carol | B |\n| 0 | Sam | C |\n| 1 | John | D |\n| 1 | Carol | A |\n| 1 | Carol | C |\n+--------+-------------+-------------+\n6 rows in set (0.00 sec)" }, { "code": null, "e": 3108, "s": 3052, "text": "Here is the query to set column value as column names −" }, { "code": null, "e": 3451, "s": 3108, "text": "mysql> select UserId,\n -> max(case when (UserColumn1='John') then UserColumn2 else NULL end) as 'John',\n -> max(case when (UserColumn1='Carol') then UserColumn2 else NULL end) as 'Carol',\n -> max(case when (UserColumn1='Sam') then UserColumn2 else NULL end) as 'Sam'\n -> from valueAsColumn\n -> group by UserId\n -> order by UserId;" }, { "code": null, "e": 3481, "s": 3451, "text": "The following is the output −" }, { "code": null, "e": 3704, "s": 3481, "text": "+--------+------+-------+------+\n| UserId | John | Carol | Sam |\n+--------+------+-------+------+\n| 0 | A+ | B | C |\n| 1 | D | C | NULL |\n+--------+------+-------+------+\n2 rows in set (0.00 sec)" } ]
Python - Dictionary items in value range - GeeksforGeeks
01 Aug, 2020 Given a range of values, extract all the items whose keys lie in range of values. Input : {‘Gfg’ : 6, ‘is’ : 7, ‘best’ : 9, ‘for’ : 8, ‘geeks’ : 11}, i, j = 9, 12Output : {‘best’ : 9, ‘geeks’ : 11}Explanation : Keys within 9 and 11 range extracted. Input : {‘Gfg’ : 6, ‘is’ : 7, ‘best’ : 9, ‘for’ : 8, ‘geeks’ : 11}, i, j = 14, 18Output : {}Explanation : No values in range. Method #1 : Using loop This is brute way in which this task can be performed. In this, we run a loop for all the keys with conditional checks for range of values. Python3 # Python3 code to demonstrate working of # Dictionary items in value range# Using loop # initializing dictionarytest_dict = {'Gfg' : 6, 'is' : 7, 'best' : 9, 'for' : 8, 'geeks' : 11} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # initializing range i, j = 8, 12 # using loop to iterate through all keysres = dict()for key, val in test_dict.items(): if int(val) >= i and int(val) <= j: res[key] = val # printing result print("The extracted dictionary : " + str(res)) The original dictionary is : {'Gfg': 6, 'is': 7, 'best': 9, 'for': 8, 'geeks': 11} The extracted dictionary : {'best': 9, 'for': 8, 'geeks': 11} Method #2 : Using filter() + lambda + dictionary comprehension The combination of above functions can be used to solve this problem. In this, we perform task of filtering using filter() and lambda is used for conditional checks. Python3 # Python3 code to demonstrate working of # Dictionary items in value range# Using filter() + lambda + dictionary comprehension # initializing dictionarytest_dict = {'Gfg' : 6, 'is' : 7, 'best' : 9, 'for' : 8, 'geeks' : 11} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # initializing range i, j = 8, 12 # using dictionary comprehension to compile result in one res = {key: val for key, val in filter(lambda sub: int(sub[1]) >= i and int(sub[1]) <= j, test_dict.items())} # printing result print("The extracted dictionary : " + str(res)) The original dictionary is : {'Gfg': 6, 'is': 7, 'best': 9, 'for': 8, 'geeks': 11} The extracted dictionary : {'best': 9, 'for': 8, 'geeks': 11} Python dictionary-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? Selecting rows in pandas DataFrame based on conditions How to drop one or multiple columns in Pandas Dataframe Python | Get unique values from a list Check if element exists in list in Python Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary How to print without newline in Python?
[ { "code": null, "e": 24212, "s": 24184, "text": "\n01 Aug, 2020" }, { "code": null, "e": 24294, "s": 24212, "text": "Given a range of values, extract all the items whose keys lie in range of values." }, { "code": null, "e": 24461, "s": 24294, "text": "Input : {‘Gfg’ : 6, ‘is’ : 7, ‘best’ : 9, ‘for’ : 8, ‘geeks’ : 11}, i, j = 9, 12Output : {‘best’ : 9, ‘geeks’ : 11}Explanation : Keys within 9 and 11 range extracted." }, { "code": null, "e": 24587, "s": 24461, "text": "Input : {‘Gfg’ : 6, ‘is’ : 7, ‘best’ : 9, ‘for’ : 8, ‘geeks’ : 11}, i, j = 14, 18Output : {}Explanation : No values in range." }, { "code": null, "e": 24611, "s": 24587, "text": "Method #1 : Using loop " }, { "code": null, "e": 24753, "s": 24611, "text": "This is brute way in which this task can be performed. In this, we run a loop for all the keys with conditional checks for range of values. " }, { "code": null, "e": 24761, "s": 24753, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of # Dictionary items in value range# Using loop # initializing dictionarytest_dict = {'Gfg' : 6, 'is' : 7, 'best' : 9, 'for' : 8, 'geeks' : 11} # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) # initializing range i, j = 8, 12 # using loop to iterate through all keysres = dict()for key, val in test_dict.items(): if int(val) >= i and int(val) <= j: res[key] = val # printing result print(\"The extracted dictionary : \" + str(res)) ", "e": 25285, "s": 24761, "text": null }, { "code": null, "e": 25431, "s": 25285, "text": "The original dictionary is : {'Gfg': 6, 'is': 7, 'best': 9, 'for': 8, 'geeks': 11}\nThe extracted dictionary : {'best': 9, 'for': 8, 'geeks': 11}\n" }, { "code": null, "e": 25495, "s": 25431, "text": "Method #2 : Using filter() + lambda + dictionary comprehension " }, { "code": null, "e": 25661, "s": 25495, "text": "The combination of above functions can be used to solve this problem. In this, we perform task of filtering using filter() and lambda is used for conditional checks." }, { "code": null, "e": 25669, "s": 25661, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of # Dictionary items in value range# Using filter() + lambda + dictionary comprehension # initializing dictionarytest_dict = {'Gfg' : 6, 'is' : 7, 'best' : 9, 'for' : 8, 'geeks' : 11} # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) # initializing range i, j = 8, 12 # using dictionary comprehension to compile result in one res = {key: val for key, val in filter(lambda sub: int(sub[1]) >= i and int(sub[1]) <= j, test_dict.items())} # printing result print(\"The extracted dictionary : \" + str(res)) ", "e": 26288, "s": 25669, "text": null }, { "code": null, "e": 26434, "s": 26288, "text": "The original dictionary is : {'Gfg': 6, 'is': 7, 'best': 9, 'for': 8, 'geeks': 11}\nThe extracted dictionary : {'best': 9, 'for': 8, 'geeks': 11}\n" }, { "code": null, "e": 26461, "s": 26434, "text": "Python dictionary-programs" }, { "code": null, "e": 26468, "s": 26461, "text": "Python" }, { "code": null, "e": 26484, "s": 26468, "text": "Python Programs" }, { "code": null, "e": 26582, "s": 26484, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26591, "s": 26582, "text": "Comments" }, { "code": null, "e": 26604, "s": 26591, "text": "Old Comments" }, { "code": null, "e": 26636, "s": 26604, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26691, "s": 26636, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 26747, "s": 26691, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26786, "s": 26747, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26828, "s": 26786, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26850, "s": 26828, "text": "Defaultdict in Python" }, { "code": null, "e": 26889, "s": 26850, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 26935, "s": 26889, "text": "Python | Split string into list of characters" }, { "code": null, "e": 26973, "s": 26935, "text": "Python | Convert a list to dictionary" } ]
Disable a button with Bootstrap
Use the .disabled class in Bootstrap to disable a button. You can try to run the following code to implement the .disabled class − Live Demo <!DOCTYPE html> <html> <head> <title>Bootstrap Example</title> <link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet"> <script src = "/scripts/jquery.min.js"></script> <script src = "/bootstrap/js/bootstrap.min.js"></script> <body> <div class = "container"> <h2>Rank of Cricketers</h2> <p>The following are the rank of cricketers:</p> <button type = "button" class = "btn btn-primary">Enabled</button> <button type = "button" class = "btn btn-primary disabled">Disabled</button> </div> </body> </html>
[ { "code": null, "e": 1120, "s": 1062, "text": "Use the .disabled class in Bootstrap to disable a button." }, { "code": null, "e": 1193, "s": 1120, "text": "You can try to run the following code to implement the .disabled class −" }, { "code": null, "e": 1203, "s": 1193, "text": "Live Demo" }, { "code": null, "e": 1798, "s": 1203, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Example</title>\n <link href = \"/bootstrap/css/bootstrap.min.css\" rel = \"stylesheet\">\n <script src = \"/scripts/jquery.min.js\"></script>\n <script src = \"/bootstrap/js/bootstrap.min.js\"></script>\n <body>\n <div class = \"container\">\n <h2>Rank of Cricketers</h2>\n <p>The following are the rank of cricketers:</p>\n <button type = \"button\" class = \"btn btn-primary\">Enabled</button>\n <button type = \"button\" class = \"btn btn-primary disabled\">Disabled</button>\n </div>\n </body>\n</html>" } ]
Linear Regression Model Selection through Zellner’s g prior | Towards Data Science
Linear Regression is a building block for complex models, widely used because of its simplicity and ease of interpretability. Often the classical approach to model selection in linear regression resumes in choosing the model with the highest R2 or finding the right balance between complexity and goodness of fit through the Akaike Information Criteria. By Contrast, in Bayesian Inference one relies heavily on distributions because we get one when doing estimates. In this article, we’ll use Zellner’s g prior to perform model selection. Additionally, while it is not common to build an ML model with both R and Python, we’ll take advantage of R packages bas and learnbayesto illustrate the computations. In multiple linear regression, we’re interested in describing the variability of an objective variable y by a set of covariates x1, ... , xn. Each one of these variables will normally have different contributions given by the weight of the coefficient relative to each variable β1, ..., βn, that is, where α is the intercept (the value of y when the covariates are zero) and we hold the assumption of equal variances σ2. If one considers the least-squares approach (classical statistics) one would estimate the values of the unknown parameters (α, βi, σ2) through Maximum Likelihood Estimation. However, a Bayesian approach lets you consider each one of the coefficients as random variables. Thus, the goal is to get a probability model of the possible values these coefficients could take, with the advantage of getting an estimation of the uncertainty we have about the values of these coefficients. To achieve this, the Bayesian approach is very flexible. First, one sets a prior belief on what these values could be, that is, before seeing the data y we reflect our knowledge about the values of the parameters. For example, let’s assume that we know nothing about them, then we can consider a noninformative prior where one reads this expression as the joint distribution of (α, β, σ2) is proportional to the inverse of the variance σ2, this is called the prior distribution. Notice that β is a vector with components β1, ..., βn. Then, after observing data y, we set how it is described given the parameters and the covariates. Because we’re holding the linear regression assumptions we have or given x, α, β, σ2 it is plausible that the data follows a normal distribution with mean α + βx and variance σ2, this is called the likelihood. Notice that x is a vector with components x1, ..., xn. Finally, Bayes Theorem states that the posterior distribution is proportional to the product of the likelihood and the prior distribution, Knowing these components, you’ll probably notice that choosing the prior is a little bit subjective. For this reason, Zellner introduced a way of assessing how certain one is about the prior selection. In 1986 Arnold Zellner proposed a simple way of introducing subjective information in a regression model. The idea is that the user specifies the location of the beta coefficients, for instance, assume that the beta coefficients are all unitary, then, one’s belief about this assumption is going to be reflected by a constant g that reflects the amount of information in the prior relative to the data. Therefore, choosing a smaller value for g means that one has a stronger belief in this guess. Conversely, choosing larger values of g has an effect similar to choosing the noninformative prior for (α, β, σ2) because as g goes to infinity it’s influence on the prior vanish, see [2] for more details. If we have n predictors for the response variable y, there are 2n possible regression models. Zellner’s g prior can be used to select the best model among the 2n candidates. For this, assume that the models have the same prior probability, that is, for every model we assign the beta coefficients a prior guess of 0 and the same value of g. Then, we can compare the regression models by calculating the prior predictive distribution (the distribution of the data y averaged over all possible values of the parameters), notice that this integral could be hard to compute if it does not has a closed-form or if it has several dimensions. One approach for approximating the result is the Laplace method, see [6] and chapter 8 of [1] for more details. Once, we have computed each value p(y) for each m model, we need a way to compare these models. For example, when comparing just two of them we can calculate the ratio of their prior predictive densities, this is known as the Bayes Factor. The larger the value of the ratio, the larger the support of model j in favor of model k, you can read more about Bayes Factors in chapter 8 of [1] and chapter 6 of [5]. Since we are comparing 2n models, we can compute the posterior probability for each model, Finally, we will choose the model with the highest probability. In the following sections, we’ll see this procedure in action with the aid of the R packages BAS and learnbayes. To run R and Python, we’ll use the Docker image datascience-notebook from Jupyter. For an alternative approach using Anaconda, check this Stackoverflow question. After installing Docker, run in your terminal docker run -it -p 8888:8888 -p 4040:4040 -v D:/user/your_user_name:/home/jovyan/work jupyter/datascience-notebook if this is the first time running this command, Docker will automatically pull the image datascience-notebook. Notice that one should enable file sharing to mount a local directory as a volume for the Docker container, see more here. Inside Jupyter, we will be using the R packages learnbayes and bas for computing the linear regression model with g priors. Additionally, we’re using a Kaggle’s dataset from car crashes, which comes by default in seaborn. Following the example in chapter 9 of [1], we will be using the function bayes_model_selection from the LearnBayes package to compute the posterior probability for each model. Our objective variable y will be total, “the number of drivers involved in fatal collisions per billion miles”. For simplicity, we’ll take the first four variables as covariates. The bayes_model_selection function is very intuitive in this case because we just need to provide the target variable, the covariates, and the belief g in the prior guess of β. Notice that we’re choosing a value of g=100 because we’re not quite sure about the prior guess. You can freely play with this value considering that the higher this value is, the more similar the estimates will be to least-square estimates. By accessing mod.prob on the model, we can visualize the results. In the code below, we’re sorting by the higher value of the posterior probability. From the table, we see that the most probable model considers as covariates not_distracted and no_previous. Also, the individual variables with the highest contributions are no_previous and speeding. When dealing with a large number of covariates, thus a large number of models, the bayesian adaptative sampling algorithm is a great alternative. It works by sampling models without replacement from the space of possible models. To illustrate it, we’re now considering all the variables in the dataset, we got 26 possible models to choose from. Again the model with the higher posterior probability or the higher marginal likelihood is the most likely, that is, the model with the set of covariates alcohol, not_distracted, and no_previous. To summarize, let’s outline some Key Findings: While in classical statistics one gets a point estimate, in Bayesian Statistics one gets a probability distribution of the possible values the parameter can take. The prior is the belief, the likelihood the evidence, and the posterior the final knowledge. Zellner's g prior reflects the confidence one takes on a prior belief. When you have a large number of models to choose from, consider using the BAS algorithm. Finally, we’ve seen that a Bayesian approach to model selection is as intuitive and easy to implement as the classical approach, while also giving you greater insight into the inner workings of your model. Got any questions? Leave a comment. Thanks for reading and feel free to share if you like the article. [1] Albert, Jim. Bayesian Computation with R 2nd Edition. Springer, 2009. [2] Marin, J.M.; Robert, Ch. Regression and Variable Selection. URL: https://www.ceremade.dauphine.fr/~xian/BCS/Breg.pdf [3] Clyde, Merlise; Ghosh, Joyee; Littman, Michael. Bayesian Adaptive Sampling for Variable Selection and Model Averaging. URL: https://homepage.divms.uiowa.edu/~jghsh/clyde_ghosh_littman_2010_jcgs.pdf [4] Zellner, Arnold. On Assessing Prior Distributions and Bayesian Regression Analysis with g-Prior Distribution. 1986 [5] Ghosh, Jayanta; Delampady, Mohan; Samanta, Tapas. An Introduction to Bayesian Analysis: Theory and Methods. Springer, 2006. [6] Easy Laplace approximation of Bayesian models in R. URL: https://www.r-bloggers.com/easy-laplace-approximation-of-bayesian-models-in-r/ [7] Rpy2 documentation. URL: https://rpy2.github.io/doc/latest/html/index.html [8] The Ultimate Guide to Evaluation and Selection of Models in Machine Learning. Neptune.ai. URL: https://neptune.ai/blog/the-ultimate-guide-to-evaluation-and-selection-of-models-in-machine-learning
[ { "code": null, "e": 298, "s": 172, "text": "Linear Regression is a building block for complex models, widely used because of its simplicity and ease of interpretability." }, { "code": null, "e": 638, "s": 298, "text": "Often the classical approach to model selection in linear regression resumes in choosing the model with the highest R2 or finding the right balance between complexity and goodness of fit through the Akaike Information Criteria. By Contrast, in Bayesian Inference one relies heavily on distributions because we get one when doing estimates." }, { "code": null, "e": 878, "s": 638, "text": "In this article, we’ll use Zellner’s g prior to perform model selection. Additionally, while it is not common to build an ML model with both R and Python, we’ll take advantage of R packages bas and learnbayesto illustrate the computations." }, { "code": null, "e": 1178, "s": 878, "text": "In multiple linear regression, we’re interested in describing the variability of an objective variable y by a set of covariates x1, ... , xn. Each one of these variables will normally have different contributions given by the weight of the coefficient relative to each variable β1, ..., βn, that is," }, { "code": null, "e": 1780, "s": 1178, "text": "where α is the intercept (the value of y when the covariates are zero) and we hold the assumption of equal variances σ2. If one considers the least-squares approach (classical statistics) one would estimate the values of the unknown parameters (α, βi, σ2) through Maximum Likelihood Estimation. However, a Bayesian approach lets you consider each one of the coefficients as random variables. Thus, the goal is to get a probability model of the possible values these coefficients could take, with the advantage of getting an estimation of the uncertainty we have about the values of these coefficients." }, { "code": null, "e": 2097, "s": 1780, "text": "To achieve this, the Bayesian approach is very flexible. First, one sets a prior belief on what these values could be, that is, before seeing the data y we reflect our knowledge about the values of the parameters. For example, let’s assume that we know nothing about them, then we can consider a noninformative prior" }, { "code": null, "e": 2314, "s": 2097, "text": "where one reads this expression as the joint distribution of (α, β, σ2) is proportional to the inverse of the variance σ2, this is called the prior distribution. Notice that β is a vector with components β1, ..., βn." }, { "code": null, "e": 2476, "s": 2314, "text": "Then, after observing data y, we set how it is described given the parameters and the covariates. Because we’re holding the linear regression assumptions we have" }, { "code": null, "e": 2677, "s": 2476, "text": "or given x, α, β, σ2 it is plausible that the data follows a normal distribution with mean α + βx and variance σ2, this is called the likelihood. Notice that x is a vector with components x1, ..., xn." }, { "code": null, "e": 2816, "s": 2677, "text": "Finally, Bayes Theorem states that the posterior distribution is proportional to the product of the likelihood and the prior distribution," }, { "code": null, "e": 3018, "s": 2816, "text": "Knowing these components, you’ll probably notice that choosing the prior is a little bit subjective. For this reason, Zellner introduced a way of assessing how certain one is about the prior selection." }, { "code": null, "e": 3264, "s": 3018, "text": "In 1986 Arnold Zellner proposed a simple way of introducing subjective information in a regression model. The idea is that the user specifies the location of the beta coefficients, for instance, assume that the beta coefficients are all unitary," }, { "code": null, "e": 3721, "s": 3264, "text": "then, one’s belief about this assumption is going to be reflected by a constant g that reflects the amount of information in the prior relative to the data. Therefore, choosing a smaller value for g means that one has a stronger belief in this guess. Conversely, choosing larger values of g has an effect similar to choosing the noninformative prior for (α, β, σ2) because as g goes to infinity it’s influence on the prior vanish, see [2] for more details." }, { "code": null, "e": 3895, "s": 3721, "text": "If we have n predictors for the response variable y, there are 2n possible regression models. Zellner’s g prior can be used to select the best model among the 2n candidates." }, { "code": null, "e": 4240, "s": 3895, "text": "For this, assume that the models have the same prior probability, that is, for every model we assign the beta coefficients a prior guess of 0 and the same value of g. Then, we can compare the regression models by calculating the prior predictive distribution (the distribution of the data y averaged over all possible values of the parameters)," }, { "code": null, "e": 4469, "s": 4240, "text": "notice that this integral could be hard to compute if it does not has a closed-form or if it has several dimensions. One approach for approximating the result is the Laplace method, see [6] and chapter 8 of [1] for more details." }, { "code": null, "e": 4674, "s": 4469, "text": "Once, we have computed each value p(y) for each m model, we need a way to compare these models. For example, when comparing just two of them we can calculate the ratio of their prior predictive densities," }, { "code": null, "e": 4879, "s": 4674, "text": "this is known as the Bayes Factor. The larger the value of the ratio, the larger the support of model j in favor of model k, you can read more about Bayes Factors in chapter 8 of [1] and chapter 6 of [5]." }, { "code": null, "e": 4970, "s": 4879, "text": "Since we are comparing 2n models, we can compute the posterior probability for each model," }, { "code": null, "e": 5147, "s": 4970, "text": "Finally, we will choose the model with the highest probability. In the following sections, we’ll see this procedure in action with the aid of the R packages BAS and learnbayes." }, { "code": null, "e": 5309, "s": 5147, "text": "To run R and Python, we’ll use the Docker image datascience-notebook from Jupyter. For an alternative approach using Anaconda, check this Stackoverflow question." }, { "code": null, "e": 5355, "s": 5309, "text": "After installing Docker, run in your terminal" }, { "code": null, "e": 5469, "s": 5355, "text": "docker run -it -p 8888:8888 -p 4040:4040 -v D:/user/your_user_name:/home/jovyan/work jupyter/datascience-notebook" }, { "code": null, "e": 5703, "s": 5469, "text": "if this is the first time running this command, Docker will automatically pull the image datascience-notebook. Notice that one should enable file sharing to mount a local directory as a volume for the Docker container, see more here." }, { "code": null, "e": 5925, "s": 5703, "text": "Inside Jupyter, we will be using the R packages learnbayes and bas for computing the linear regression model with g priors. Additionally, we’re using a Kaggle’s dataset from car crashes, which comes by default in seaborn." }, { "code": null, "e": 6101, "s": 5925, "text": "Following the example in chapter 9 of [1], we will be using the function bayes_model_selection from the LearnBayes package to compute the posterior probability for each model." }, { "code": null, "e": 6280, "s": 6101, "text": "Our objective variable y will be total, “the number of drivers involved in fatal collisions per billion miles”. For simplicity, we’ll take the first four variables as covariates." }, { "code": null, "e": 6457, "s": 6280, "text": "The bayes_model_selection function is very intuitive in this case because we just need to provide the target variable, the covariates, and the belief g in the prior guess of β." }, { "code": null, "e": 6698, "s": 6457, "text": "Notice that we’re choosing a value of g=100 because we’re not quite sure about the prior guess. You can freely play with this value considering that the higher this value is, the more similar the estimates will be to least-square estimates." }, { "code": null, "e": 6847, "s": 6698, "text": "By accessing mod.prob on the model, we can visualize the results. In the code below, we’re sorting by the higher value of the posterior probability." }, { "code": null, "e": 7047, "s": 6847, "text": "From the table, we see that the most probable model considers as covariates not_distracted and no_previous. Also, the individual variables with the highest contributions are no_previous and speeding." }, { "code": null, "e": 7392, "s": 7047, "text": "When dealing with a large number of covariates, thus a large number of models, the bayesian adaptative sampling algorithm is a great alternative. It works by sampling models without replacement from the space of possible models. To illustrate it, we’re now considering all the variables in the dataset, we got 26 possible models to choose from." }, { "code": null, "e": 7588, "s": 7392, "text": "Again the model with the higher posterior probability or the higher marginal likelihood is the most likely, that is, the model with the set of covariates alcohol, not_distracted, and no_previous." }, { "code": null, "e": 7635, "s": 7588, "text": "To summarize, let’s outline some Key Findings:" }, { "code": null, "e": 7798, "s": 7635, "text": "While in classical statistics one gets a point estimate, in Bayesian Statistics one gets a probability distribution of the possible values the parameter can take." }, { "code": null, "e": 7891, "s": 7798, "text": "The prior is the belief, the likelihood the evidence, and the posterior the final knowledge." }, { "code": null, "e": 7962, "s": 7891, "text": "Zellner's g prior reflects the confidence one takes on a prior belief." }, { "code": null, "e": 8051, "s": 7962, "text": "When you have a large number of models to choose from, consider using the BAS algorithm." }, { "code": null, "e": 8257, "s": 8051, "text": "Finally, we’ve seen that a Bayesian approach to model selection is as intuitive and easy to implement as the classical approach, while also giving you greater insight into the inner workings of your model." }, { "code": null, "e": 8360, "s": 8257, "text": "Got any questions? Leave a comment. Thanks for reading and feel free to share if you like the article." }, { "code": null, "e": 8434, "s": 8360, "text": "[1] Albert, Jim. Bayesian Computation with R 2nd Edition. Springer, 2009." }, { "code": null, "e": 8555, "s": 8434, "text": "[2] Marin, J.M.; Robert, Ch. Regression and Variable Selection. URL: https://www.ceremade.dauphine.fr/~xian/BCS/Breg.pdf" }, { "code": null, "e": 8757, "s": 8555, "text": "[3] Clyde, Merlise; Ghosh, Joyee; Littman, Michael. Bayesian Adaptive Sampling for Variable Selection and Model Averaging. URL: https://homepage.divms.uiowa.edu/~jghsh/clyde_ghosh_littman_2010_jcgs.pdf" }, { "code": null, "e": 8876, "s": 8757, "text": "[4] Zellner, Arnold. On Assessing Prior Distributions and Bayesian Regression Analysis with g-Prior Distribution. 1986" }, { "code": null, "e": 9004, "s": 8876, "text": "[5] Ghosh, Jayanta; Delampady, Mohan; Samanta, Tapas. An Introduction to Bayesian Analysis: Theory and Methods. Springer, 2006." }, { "code": null, "e": 9144, "s": 9004, "text": "[6] Easy Laplace approximation of Bayesian models in R. URL: https://www.r-bloggers.com/easy-laplace-approximation-of-bayesian-models-in-r/" }, { "code": null, "e": 9223, "s": 9144, "text": "[7] Rpy2 documentation. URL: https://rpy2.github.io/doc/latest/html/index.html" } ]
Templates and Static variables in C++
In this tutorial, we will be discussing a program to understand templates and static variables in C++. In case of function and class templates, each instance of the templates has its own local copy of the variables. Live Demo #include <iostream> using namespace std; template <typename T> void fun(const T& x){ static int i = 10; cout << ++i; return ; } int main(){ fun<int>(1); //printing 11 cout << endl; fun<int>(2); //printing 12 cout << endl; fun<double>(1.1); //printing 11 again cout << endl; getchar(); return 0; } 11 12 11
[ { "code": null, "e": 1165, "s": 1062, "text": "In this tutorial, we will be discussing a program to understand templates and static variables in C++." }, { "code": null, "e": 1278, "s": 1165, "text": "In case of function and class templates, each instance of the templates has its own local copy of the variables." }, { "code": null, "e": 1289, "s": 1278, "text": " Live Demo" }, { "code": null, "e": 1619, "s": 1289, "text": "#include <iostream>\nusing namespace std;\ntemplate <typename T>\nvoid fun(const T& x){\n static int i = 10;\n cout << ++i;\n return ;\n}\nint main(){\n fun<int>(1); //printing 11\n cout << endl;\n fun<int>(2); //printing 12\n cout << endl;\n fun<double>(1.1); //printing 11 again\n cout << endl;\n getchar();\n return 0;\n}" }, { "code": null, "e": 1628, "s": 1619, "text": "11\n12\n11" } ]
Print a HTML5 canvas element
The following is the code snippet to display an HTML5 canvas element. <a href = "javascript:print_voucher()">PRINT CANVAS</a> function print_canvas() { $("#canvas_voucher").printElement(); } Here canvas_voucher is ID of canvas element.To make this start functioning we need to convert the canvas into .png image URL and open it in a new browser window. Print dialog is triggered to let user print the page. function print_canvasr(){ var win1 = window.open(); win1.document.write("<br><img src = '"+canvas.toDataURL()+"'/>"); win1.print(); win1.location.reload(); }
[ { "code": null, "e": 1132, "s": 1062, "text": "The following is the code snippet to display an HTML5 canvas element." }, { "code": null, "e": 1256, "s": 1132, "text": "<a href = \"javascript:print_voucher()\">PRINT CANVAS</a>\nfunction print_canvas()\n{\n $(\"#canvas_voucher\").printElement();\n}" }, { "code": null, "e": 1472, "s": 1256, "text": "Here canvas_voucher is ID of canvas element.To make this start functioning we need to convert the canvas into .png image URL and open it in a new browser window. Print dialog is triggered to let user print the page." }, { "code": null, "e": 1642, "s": 1472, "text": "function print_canvasr(){\n var win1 = window.open();\n win1.document.write(\"<br><img src = '\"+canvas.toDataURL()+\"'/>\");\n win1.print();\n win1.location.reload();\n}" } ]
How to use Google Speech to Text API to transcribe long audio files? | by Sundar Krishnan | Towards Data Science
Speech recognition is a fun task. A lot of API resources are available in market today which makes it easier for user to opt for one or another. However, when it comes to audio files especially call center data, the task becomes little challenging. Let’s make an assumption that a call center conversation takes roughly 10 minutes. For this scenario, only a few API resources available in market can handle this type of data (Google, Amazon, IBM, Microsoft, Nuance, Rev.ai, Open source Wavenet, Open source CMU Sphinx). In this article, we will talk about Google speech to text API in detail. Google Speech to text has three types of API requests based on audio content. Synchronous Request The audio file content should be approximately 1 minute to make a synchronous request. In this type of request, the user does not have to upload the data to Google cloud. This provides the flexibility to users to store the audio file in their local computer or server and reference the API to get the text. Asynchronous Request The audio file content should be approximately 480 minutes(8 hours). In this type of request, the user have to upload their data to Google cloud. This is exactly what we will cover in this article. Streaming Request It is suitable for streaming data where the user is talking to microphone directly and needs to get it transcribed. This type of request is apt for chatbots. Again, the streaming data should be approximately a minute for this type of request. Before you begin, you need to do some initial setup. Please follow the link below to complete the setup. cloud.google.com I also wrote an article which explains the step 1 in detail. medium.com Once you create the API client, the next step is to create a storage bucket. You can use the link below to create a storage bucket. For this project, I named the bucket as ‘callsaudiofiles’. console.cloud.google.com Step 1: Import necessary packages Here the ‘filepath’ variable contains the location of the audio files in your local computer. So you can store multiple audio files in the path and it will still work. The ‘output_filepath’ is where all the transcripts created by Google cloud will be stored later in your local computer. In addition, provide the bucket name created in the step before in the ‘bucketname’ variable. You need not upload your file to Google storage. We will discuss about how to upload to Google storage in the later section. Step 2: Audio file encoding Google Speech to text handles some specific types of audio encodings. You can read in detail in the link below. cloud.google.com This limits us to convert audio files before using Google Speech to text API if they are in a different format. I provided a sample code for converting mp3 files to wav files below. Step 3: Audio file specs One other limitation is that the API does not support stereo audio files. So the user needs to convert a stereo file to mono file before using the API. In addition, the user has to provide the audio frame rate for the file. The code below helps you figure it out for any ‘.wav’ audio file. Step 4: Upload files to Google storage As we discussed before, in order to perform asynchronous request the file should be uploaded to google cloud. The code below will accomplish the same. Step 5: Delete files in Google storage Once the speech to text operation is completed, the file can be deleted from Google cloud. The code below can be used to delete files from Google cloud. Step 6: Transcribe Finally, the transcribe function below performs all the operations necessary to get the final transcripts. It calls the other functions described in the previous steps and stores the transcripts in the ‘transcript’ variable. One thing to note here is the timeout option. It is the number of seconds that the transcribe function will actively transcribe a current audio file. You can adjust this setting to a larger number if the audio file seconds is larger than the number provided here. Step 7: Write transcripts Once the Speech to text operation is completed and you need to store the final transcripts in a file, the code below can be used to perform the same. Step 8: Execute your code. Wait and watch the transcripts The code below starts the execution. You can have multiple audio files in the filepath. It executes each file sequentially. The final transcripts generated look like below. I was on the other roommate had to leave before I got half of them by him. I guess no way to get a hold back to you. Alright. Yeah, kinda I mean like what? What are you I have to I have to play with the other guys. So yeah, go ahead and I with me I can let my people like the one that you were calling me, but I go ahead and do it cuz I'm sure he's not work for lunch, but they just had them or is it 10 o'clock? I want to go ahead and get out with me. Call me. I understand. They probably to talk about Mom and I need to call back or maybe I can just figured after taxes advertises. It's 110 feet in so I guess alright. Well shoot let me know and then maybe I'll just minus the weather. Okay. Well so much for your help. Like I said, no problem. Alright, you have a good day. Okay. Bye. Speaker Diarization is a process of distinguishing speakers in an audio file. It turns you can use Google speech to text API to perform speaker diarization. The final transcripts generated by Google after speaker diarization looks like below. speaker 1: I was on the other roommate had to leave before I got half of them by him I guess no way to get a hold back to you alrightspeaker 2: yeah kinda I mean like what what are you Ispeaker 1: have to I have to play with the other guys so yeah go ahead and I with me I can let my people like the one that you were calling me but I go ahead and do it cuz I'm sure he's not work for lunch but they just had them or is it 10 o'clock I want to go ahead and get out with mespeaker 2: call me I understandspeaker 1: they probably to talk about Mom and I need to call back or maybe I can just figured after taxesspeaker 2: advertises it's 110 feet in so Ispeaker 1: guess alright well shoot let me know and then maybe I'll just minus the weather okay well so much for your help like I said no problem alright you have a good day okay bye To perform this, you need to make some changes to the code described before. Let us start with the package imports. Now, let us talk about the changes in the transcribe part. The entire code for both the projects can be found in the Github link.
[ { "code": null, "e": 765, "s": 172, "text": "Speech recognition is a fun task. A lot of API resources are available in market today which makes it easier for user to opt for one or another. However, when it comes to audio files especially call center data, the task becomes little challenging. Let’s make an assumption that a call center conversation takes roughly 10 minutes. For this scenario, only a few API resources available in market can handle this type of data (Google, Amazon, IBM, Microsoft, Nuance, Rev.ai, Open source Wavenet, Open source CMU Sphinx). In this article, we will talk about Google speech to text API in detail." }, { "code": null, "e": 843, "s": 765, "text": "Google Speech to text has three types of API requests based on audio content." }, { "code": null, "e": 863, "s": 843, "text": "Synchronous Request" }, { "code": null, "e": 1170, "s": 863, "text": "The audio file content should be approximately 1 minute to make a synchronous request. In this type of request, the user does not have to upload the data to Google cloud. This provides the flexibility to users to store the audio file in their local computer or server and reference the API to get the text." }, { "code": null, "e": 1191, "s": 1170, "text": "Asynchronous Request" }, { "code": null, "e": 1389, "s": 1191, "text": "The audio file content should be approximately 480 minutes(8 hours). In this type of request, the user have to upload their data to Google cloud. This is exactly what we will cover in this article." }, { "code": null, "e": 1407, "s": 1389, "text": "Streaming Request" }, { "code": null, "e": 1650, "s": 1407, "text": "It is suitable for streaming data where the user is talking to microphone directly and needs to get it transcribed. This type of request is apt for chatbots. Again, the streaming data should be approximately a minute for this type of request." }, { "code": null, "e": 1755, "s": 1650, "text": "Before you begin, you need to do some initial setup. Please follow the link below to complete the setup." }, { "code": null, "e": 1772, "s": 1755, "text": "cloud.google.com" }, { "code": null, "e": 1833, "s": 1772, "text": "I also wrote an article which explains the step 1 in detail." }, { "code": null, "e": 1844, "s": 1833, "text": "medium.com" }, { "code": null, "e": 2035, "s": 1844, "text": "Once you create the API client, the next step is to create a storage bucket. You can use the link below to create a storage bucket. For this project, I named the bucket as ‘callsaudiofiles’." }, { "code": null, "e": 2060, "s": 2035, "text": "console.cloud.google.com" }, { "code": null, "e": 2094, "s": 2060, "text": "Step 1: Import necessary packages" }, { "code": null, "e": 2601, "s": 2094, "text": "Here the ‘filepath’ variable contains the location of the audio files in your local computer. So you can store multiple audio files in the path and it will still work. The ‘output_filepath’ is where all the transcripts created by Google cloud will be stored later in your local computer. In addition, provide the bucket name created in the step before in the ‘bucketname’ variable. You need not upload your file to Google storage. We will discuss about how to upload to Google storage in the later section." }, { "code": null, "e": 2629, "s": 2601, "text": "Step 2: Audio file encoding" }, { "code": null, "e": 2741, "s": 2629, "text": "Google Speech to text handles some specific types of audio encodings. You can read in detail in the link below." }, { "code": null, "e": 2758, "s": 2741, "text": "cloud.google.com" }, { "code": null, "e": 2870, "s": 2758, "text": "This limits us to convert audio files before using Google Speech to text API if they are in a different format." }, { "code": null, "e": 2940, "s": 2870, "text": "I provided a sample code for converting mp3 files to wav files below." }, { "code": null, "e": 2965, "s": 2940, "text": "Step 3: Audio file specs" }, { "code": null, "e": 3255, "s": 2965, "text": "One other limitation is that the API does not support stereo audio files. So the user needs to convert a stereo file to mono file before using the API. In addition, the user has to provide the audio frame rate for the file. The code below helps you figure it out for any ‘.wav’ audio file." }, { "code": null, "e": 3294, "s": 3255, "text": "Step 4: Upload files to Google storage" }, { "code": null, "e": 3445, "s": 3294, "text": "As we discussed before, in order to perform asynchronous request the file should be uploaded to google cloud. The code below will accomplish the same." }, { "code": null, "e": 3484, "s": 3445, "text": "Step 5: Delete files in Google storage" }, { "code": null, "e": 3637, "s": 3484, "text": "Once the speech to text operation is completed, the file can be deleted from Google cloud. The code below can be used to delete files from Google cloud." }, { "code": null, "e": 3656, "s": 3637, "text": "Step 6: Transcribe" }, { "code": null, "e": 3881, "s": 3656, "text": "Finally, the transcribe function below performs all the operations necessary to get the final transcripts. It calls the other functions described in the previous steps and stores the transcripts in the ‘transcript’ variable." }, { "code": null, "e": 4145, "s": 3881, "text": "One thing to note here is the timeout option. It is the number of seconds that the transcribe function will actively transcribe a current audio file. You can adjust this setting to a larger number if the audio file seconds is larger than the number provided here." }, { "code": null, "e": 4171, "s": 4145, "text": "Step 7: Write transcripts" }, { "code": null, "e": 4321, "s": 4171, "text": "Once the Speech to text operation is completed and you need to store the final transcripts in a file, the code below can be used to perform the same." }, { "code": null, "e": 4379, "s": 4321, "text": "Step 8: Execute your code. Wait and watch the transcripts" }, { "code": null, "e": 4503, "s": 4379, "text": "The code below starts the execution. You can have multiple audio files in the filepath. It executes each file sequentially." }, { "code": null, "e": 4552, "s": 4503, "text": "The final transcripts generated look like below." }, { "code": null, "e": 5340, "s": 4552, "text": "I was on the other roommate had to leave before I got half of them by him. I guess no way to get a hold back to you. Alright. Yeah, kinda I mean like what? What are you I have to I have to play with the other guys. So yeah, go ahead and I with me I can let my people like the one that you were calling me, but I go ahead and do it cuz I'm sure he's not work for lunch, but they just had them or is it 10 o'clock? I want to go ahead and get out with me. Call me. I understand. They probably to talk about Mom and I need to call back or maybe I can just figured after taxes advertises. It's 110 feet in so I guess alright. Well shoot let me know and then maybe I'll just minus the weather. Okay. Well so much for your help. Like I said, no problem. Alright, you have a good day. Okay. Bye." }, { "code": null, "e": 5583, "s": 5340, "text": "Speaker Diarization is a process of distinguishing speakers in an audio file. It turns you can use Google speech to text API to perform speaker diarization. The final transcripts generated by Google after speaker diarization looks like below." }, { "code": null, "e": 6418, "s": 5583, "text": "speaker 1: I was on the other roommate had to leave before I got half of them by him I guess no way to get a hold back to you alrightspeaker 2: yeah kinda I mean like what what are you Ispeaker 1: have to I have to play with the other guys so yeah go ahead and I with me I can let my people like the one that you were calling me but I go ahead and do it cuz I'm sure he's not work for lunch but they just had them or is it 10 o'clock I want to go ahead and get out with mespeaker 2: call me I understandspeaker 1: they probably to talk about Mom and I need to call back or maybe I can just figured after taxesspeaker 2: advertises it's 110 feet in so Ispeaker 1: guess alright well shoot let me know and then maybe I'll just minus the weather okay well so much for your help like I said no problem alright you have a good day okay bye" }, { "code": null, "e": 6534, "s": 6418, "text": "To perform this, you need to make some changes to the code described before. Let us start with the package imports." }, { "code": null, "e": 6593, "s": 6534, "text": "Now, let us talk about the changes in the transcribe part." } ]
How to Build a Smile Detector. Detect Happiness in Python (Tutorial) | by Rohan Gupta | Towards Data Science
Businesses strive to deliver the most important product of all: happiness. Why? Happiness might just be more than a chemical reaction. A happy customer is more likely to walk through the door again, and data on happiness can help businesses understand which products would do better and have a higher retention rate. Machines can learn to recognize happiness and in this tutorial, I’m going to show you how to create a facial recognition model that can do so. Let’s start with the basics. How do we express happiness? On the face, it’s mostly through our eyes and smiles. We naturally infer that someone is happy when we see a smile on their face. A smile can have many variations, but its shape is mostly similar to a flatter kind of ‘U’ shaped figure. :) In the next steps, I’m going to put down my code and explain what I did to build the happiness detector. To understand the intuition behind the algorithm, check out this previous article on The Viola-Jones Algorithm. What you need to build happiness detector: Anaconda Navigator: https://docs.anaconda.com/anaconda/navigator/ OpenCV: https://opencv.org/ Haar Cascades (Link Below) I’m using Spyder on Anaconda, but you could also use Jupyter Nb I suppose. Once you have everything, get on the IDE (code editor). You should have a screen like this if you’re using spyder. Before you start coding, make sure to download the haar cascades (next section) As I had explained in the article cited above, the Viola-Jones algorithm uses haar-like features to detect facial properties. The cascade is a series of filters that will apply one after the other to detect a face through its features. These filters are stored in their own XML files in the Haar Cascade GitHub Repository. To build our happiness detector, we need these 3 XML Files: - haarcascade_eye.xml- haarcascade_smile.xml- haarcascade_frontalface_default.xml These are the cascades for the face, eyes, and smiles. We must have each one of these features if our image is of a happy face. Obtain the code from each of these links, place it into a text editor and save your files according to the names mentioned above. Put all three XML files into the same folder where you will start a python notebook. Now that we have our Haar Cascades, let’s head over to the virtual environment. — — — — — — — — -Now, its finally time to start coding. — — — — — — — — import cv2cascade_face = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')cascade_eye = cv2.CascadeClassifier('haarcascade_eye.xml') cascade_smile = cv2.CascadeClassifier('haarcascade_smile.xml') The only library you need to import is OpenCV. Even though it is a very powerful object-recognition tool, it is not the most powerful one. There are newer better ones out there, but OpenCV still delivers a lot of value and is a good way to understand the basics of object recognition. After importing OpenCV (cv2), I called each of the cascades that were downloaded. For this, I just need to use the OpenCV function called CascadeClassifier. def detection(grayscale, img): face = cascade_face.detectMultiScale(grayscale, 1.3, 5) for (x_face, y_face, w_face, h_face) in face: cv2.rectangle(img, (x_face, y_face), (x_face+w_face, y_face+h_face), (255, 130, 0), 2) Before you define the function for detection, you should know that it is going to be applied to single images, which are then put together to get the end result. Since the Viola-Jones algorithm works with grayscale images, I input the first argument of this function as grayscale. However, I also want the final output to have the original image in color, so I input another argument img for the original image. Next, I will need to get the coordinates of the rectangles that will detect the face. To define these coordinates, I took 4 tuples: x, y, w, and h. x & y are coordinates of the upper left corner, while w & h are width and height of rectangles respectively. I stored these tuples in a variable face and then used another one of OpenCV's functions called detectMultiScale to actually get these coordinates. So we use our object Cascade_face and apply the detectMultiScale method to it with 3 arguments:- grayscale as the image is being analyzed in b&w- a scale factor of 1.3 (size of the image will be reduced 1.3x)- a minimum number of accepted neighbor zones: 5 neighbors. Next, to actually draw the rectangles I create a ‘for loop’ with our 4 tuples x_face, y_face, h_face, w_face in faces. In the for loop, I used the rectangle function, which is another OpenCV function. This actually draws the rectangle on your face and is given the following arguments: - ‘img’ because we want rectangle drawn on our original colored image. - coordinates of the upper left corner: x and y- coordinates of the lower right corner: w and h- color of rectangle: I chose a blueish color.- The thickness of edges of rectangles: I picked 2. (doesn’t really matter but 2 is a good choice) Note: The code below is in continuation (I’ve put it all together at the bottom) ri_grayscale = grayscale[y_face:y_face+h_face, x_face:x_face + w_face] ri_color = img[y_face:y_face+h_face, x_face:x_face+w_face] Now that I’m done with the face, I’m going to detect the eyes. This is the only part that’s slightly tricky and a bit harder to understand. Basically, the lines above mention that you are looking for eyes within the face, and so the face becomes our “region of interest”. Since the algorithm works with grayscale images, we input the argument for grayscale. However, I also want to get the colored image, so I will add another argument for the colored image. Essentially, there are 2 regions of interests: one for the grayscale image and one for the original colored image. Subsequently, I create ri_grayscale on the grayscale image with the range of coordinates of the rectangles y:y+h and x:x+w. Then, on the colored image, I create ri_color with the same coordinates for the rectangles. eye = cascade_eye.detectMultiScale(ri_grayscale, 1.2, 18) for (x_eye, y_eye, w_eye, h_eye) in eye: cv2.rectangle(ri_color,(x_eye, y_eye),(x_eye+w_eye, y_eye+h_eye), (0, 180, 60), 2) For the eyes, I repeated the first step with the faces and create an object called eye with cascase_eye and use the detectMultiScale method to find the 4 tuples. I changed the scale factor to 1.2 and the minimum neighbors to 18. ( I had to experiment with these values to get perfect results). Next, I created a for loop for the eyes as well. You can copy-paste the previous one, just need to change the tuple names and choose a different color. smile = cascade_smile.detectMultiScale(ri_grayscale, 1.7, 20) for (x_smile, y_smile, w_smile, h_smile) in smile: cv2.rectangle(ri_color,(x_smile, y_smile),(x_smile+w_smile, y_smile+h_smile), (255, 0, 130), 2) return img Then again for the smile, I repeat the same steps that I did for the face and eyes. When using the detectMultiScale method, I used a scale factor of 1.7 and minimum neighbors of 20. (As I said before, this requires some experimentation to figure out).Once all that is done you just return the original frame. vc = cv2.VideoCapture(0)while True: _, img = vc.read() grayscale = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) final = detection(grayscale, img) cv2.imshow('Video', final) if cv2.waitKey(1) & 0xFF == ord('q'): break vc.release() cv2.destroyAllWindows() I started by creating an object called vc and used the VideoCapture class from OpenCV. It takes only one argument: 0 or 1.0 if you use an internal webcam, 1 if it is external. Since the detection function works for a single image, I now have to create some sort of loop that allows it to run over a series of images. So I start an infinite while loop which I will break later by using a break function. Now the next lines may seem confusing, but basically, the read method from VideoCapture gets two elements: one of which is the last frame coming from the webcam. Since you only want that, use _, img because the read method returns 2 frames and you only want this one. Now I need to call this method from the VideoCapture class. I use the cvtColor function that will convert the colored img to grayscale since it needs a b&w frame for the detect function. I call it grayscale and take the cvtColor class, which takes 2 arguments: - the frame (img)- cv2.COLOR_BGR2GRAY — does an average of Blue-green-red to get right shades of grey.Now I created a new variable called ‘final’ and this will be the result of the detect function. Within ‘final’, I use the detection function with arguments grayscale and img. The imshow function is another OpenCV function that allows us to view the original material coming from the webcam with the rectangle animations. It displays the processed images in an animated way. Then I used another function to close the window when I’m done using it. I applied an if condition which will terminate the application every time I press the ‘q’ button on the keyboard. This will break the while loop to end the process. Finally, I used the release method to turn off the webcam and the DestroyAllWindows function to terminate the windows. I’ve pasted my complete code put together below just in case there’s any confusion from the excerpts above. At first, there were many reasons why the model didn’t work. It would detect a non-smiling face as a smile too. I had to work with the scale factor, as well as the minimum neighbors to get a perfect result.
[ { "code": null, "e": 121, "s": 46, "text": "Businesses strive to deliver the most important product of all: happiness." }, { "code": null, "e": 506, "s": 121, "text": "Why? Happiness might just be more than a chemical reaction. A happy customer is more likely to walk through the door again, and data on happiness can help businesses understand which products would do better and have a higher retention rate. Machines can learn to recognize happiness and in this tutorial, I’m going to show you how to create a facial recognition model that can do so." }, { "code": null, "e": 800, "s": 506, "text": "Let’s start with the basics. How do we express happiness? On the face, it’s mostly through our eyes and smiles. We naturally infer that someone is happy when we see a smile on their face. A smile can have many variations, but its shape is mostly similar to a flatter kind of ‘U’ shaped figure." }, { "code": null, "e": 803, "s": 800, "text": ":)" }, { "code": null, "e": 1020, "s": 803, "text": "In the next steps, I’m going to put down my code and explain what I did to build the happiness detector. To understand the intuition behind the algorithm, check out this previous article on The Viola-Jones Algorithm." }, { "code": null, "e": 1063, "s": 1020, "text": "What you need to build happiness detector:" }, { "code": null, "e": 1129, "s": 1063, "text": "Anaconda Navigator: https://docs.anaconda.com/anaconda/navigator/" }, { "code": null, "e": 1157, "s": 1129, "text": "OpenCV: https://opencv.org/" }, { "code": null, "e": 1184, "s": 1157, "text": "Haar Cascades (Link Below)" }, { "code": null, "e": 1315, "s": 1184, "text": "I’m using Spyder on Anaconda, but you could also use Jupyter Nb I suppose. Once you have everything, get on the IDE (code editor)." }, { "code": null, "e": 1454, "s": 1315, "text": "You should have a screen like this if you’re using spyder. Before you start coding, make sure to download the haar cascades (next section)" }, { "code": null, "e": 1690, "s": 1454, "text": "As I had explained in the article cited above, the Viola-Jones algorithm uses haar-like features to detect facial properties. The cascade is a series of filters that will apply one after the other to detect a face through its features." }, { "code": null, "e": 1777, "s": 1690, "text": "These filters are stored in their own XML files in the Haar Cascade GitHub Repository." }, { "code": null, "e": 1919, "s": 1777, "text": "To build our happiness detector, we need these 3 XML Files: - haarcascade_eye.xml- haarcascade_smile.xml- haarcascade_frontalface_default.xml" }, { "code": null, "e": 2342, "s": 1919, "text": "These are the cascades for the face, eyes, and smiles. We must have each one of these features if our image is of a happy face. Obtain the code from each of these links, place it into a text editor and save your files according to the names mentioned above. Put all three XML files into the same folder where you will start a python notebook. Now that we have our Haar Cascades, let’s head over to the virtual environment." }, { "code": null, "e": 2414, "s": 2342, "text": "— — — — — — — — -Now, its finally time to start coding. — — — — — — — —" }, { "code": null, "e": 2621, "s": 2414, "text": "import cv2cascade_face = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')cascade_eye = cv2.CascadeClassifier('haarcascade_eye.xml') cascade_smile = cv2.CascadeClassifier('haarcascade_smile.xml')" }, { "code": null, "e": 3063, "s": 2621, "text": "The only library you need to import is OpenCV. Even though it is a very powerful object-recognition tool, it is not the most powerful one. There are newer better ones out there, but OpenCV still delivers a lot of value and is a good way to understand the basics of object recognition. After importing OpenCV (cv2), I called each of the cascades that were downloaded. For this, I just need to use the OpenCV function called CascadeClassifier." }, { "code": null, "e": 3298, "s": 3063, "text": "def detection(grayscale, img): face = cascade_face.detectMultiScale(grayscale, 1.3, 5) for (x_face, y_face, w_face, h_face) in face: cv2.rectangle(img, (x_face, y_face), (x_face+w_face, y_face+h_face), (255, 130, 0), 2) " }, { "code": null, "e": 3460, "s": 3298, "text": "Before you define the function for detection, you should know that it is going to be applied to single images, which are then put together to get the end result." }, { "code": null, "e": 4383, "s": 3460, "text": "Since the Viola-Jones algorithm works with grayscale images, I input the first argument of this function as grayscale. However, I also want the final output to have the original image in color, so I input another argument img for the original image. Next, I will need to get the coordinates of the rectangles that will detect the face. To define these coordinates, I took 4 tuples: x, y, w, and h. x & y are coordinates of the upper left corner, while w & h are width and height of rectangles respectively. I stored these tuples in a variable face and then used another one of OpenCV's functions called detectMultiScale to actually get these coordinates. So we use our object Cascade_face and apply the detectMultiScale method to it with 3 arguments:- grayscale as the image is being analyzed in b&w- a scale factor of 1.3 (size of the image will be reduced 1.3x)- a minimum number of accepted neighbor zones: 5 neighbors." }, { "code": null, "e": 4980, "s": 4383, "text": "Next, to actually draw the rectangles I create a ‘for loop’ with our 4 tuples x_face, y_face, h_face, w_face in faces. In the for loop, I used the rectangle function, which is another OpenCV function. This actually draws the rectangle on your face and is given the following arguments: - ‘img’ because we want rectangle drawn on our original colored image. - coordinates of the upper left corner: x and y- coordinates of the lower right corner: w and h- color of rectangle: I chose a blueish color.- The thickness of edges of rectangles: I picked 2. (doesn’t really matter but 2 is a good choice)" }, { "code": null, "e": 5061, "s": 4980, "text": "Note: The code below is in continuation (I’ve put it all together at the bottom)" }, { "code": null, "e": 5211, "s": 5061, "text": " ri_grayscale = grayscale[y_face:y_face+h_face, x_face:x_face + w_face] ri_color = img[y_face:y_face+h_face, x_face:x_face+w_face]" }, { "code": null, "e": 6001, "s": 5211, "text": "Now that I’m done with the face, I’m going to detect the eyes. This is the only part that’s slightly tricky and a bit harder to understand. Basically, the lines above mention that you are looking for eyes within the face, and so the face becomes our “region of interest”. Since the algorithm works with grayscale images, we input the argument for grayscale. However, I also want to get the colored image, so I will add another argument for the colored image. Essentially, there are 2 regions of interests: one for the grayscale image and one for the original colored image. Subsequently, I create ri_grayscale on the grayscale image with the range of coordinates of the rectangles y:y+h and x:x+w. Then, on the colored image, I create ri_color with the same coordinates for the rectangles." }, { "code": null, "e": 6218, "s": 6001, "text": " eye = cascade_eye.detectMultiScale(ri_grayscale, 1.2, 18) for (x_eye, y_eye, w_eye, h_eye) in eye: cv2.rectangle(ri_color,(x_eye, y_eye),(x_eye+w_eye, y_eye+h_eye), (0, 180, 60), 2) " }, { "code": null, "e": 6512, "s": 6218, "text": "For the eyes, I repeated the first step with the faces and create an object called eye with cascase_eye and use the detectMultiScale method to find the 4 tuples. I changed the scale factor to 1.2 and the minimum neighbors to 18. ( I had to experiment with these values to get perfect results)." }, { "code": null, "e": 6664, "s": 6512, "text": "Next, I created a for loop for the eyes as well. You can copy-paste the previous one, just need to change the tuple names and choose a different color." }, { "code": null, "e": 6914, "s": 6664, "text": "smile = cascade_smile.detectMultiScale(ri_grayscale, 1.7, 20) for (x_smile, y_smile, w_smile, h_smile) in smile: cv2.rectangle(ri_color,(x_smile, y_smile),(x_smile+w_smile, y_smile+h_smile), (255, 0, 130), 2) return img" }, { "code": null, "e": 7223, "s": 6914, "text": "Then again for the smile, I repeat the same steps that I did for the face and eyes. When using the detectMultiScale method, I used a scale factor of 1.7 and minimum neighbors of 20. (As I said before, this requires some experimentation to figure out).Once all that is done you just return the original frame." }, { "code": null, "e": 7496, "s": 7223, "text": "vc = cv2.VideoCapture(0)while True: _, img = vc.read() grayscale = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) final = detection(grayscale, img) cv2.imshow('Video', final) if cv2.waitKey(1) & 0xFF == ord('q'): break vc.release() cv2.destroyAllWindows() " }, { "code": null, "e": 7672, "s": 7496, "text": "I started by creating an object called vc and used the VideoCapture class from OpenCV. It takes only one argument: 0 or 1.0 if you use an internal webcam, 1 if it is external." }, { "code": null, "e": 8227, "s": 7672, "text": "Since the detection function works for a single image, I now have to create some sort of loop that allows it to run over a series of images. So I start an infinite while loop which I will break later by using a break function. Now the next lines may seem confusing, but basically, the read method from VideoCapture gets two elements: one of which is the last frame coming from the webcam. Since you only want that, use _, img because the read method returns 2 frames and you only want this one. Now I need to call this method from the VideoCapture class." }, { "code": null, "e": 8705, "s": 8227, "text": "I use the cvtColor function that will convert the colored img to grayscale since it needs a b&w frame for the detect function. I call it grayscale and take the cvtColor class, which takes 2 arguments: - the frame (img)- cv2.COLOR_BGR2GRAY — does an average of Blue-green-red to get right shades of grey.Now I created a new variable called ‘final’ and this will be the result of the detect function. Within ‘final’, I use the detection function with arguments grayscale and img." }, { "code": null, "e": 8904, "s": 8705, "text": "The imshow function is another OpenCV function that allows us to view the original material coming from the webcam with the rectangle animations. It displays the processed images in an animated way." }, { "code": null, "e": 9261, "s": 8904, "text": "Then I used another function to close the window when I’m done using it. I applied an if condition which will terminate the application every time I press the ‘q’ button on the keyboard. This will break the while loop to end the process. Finally, I used the release method to turn off the webcam and the DestroyAllWindows function to terminate the windows." }, { "code": null, "e": 9369, "s": 9261, "text": "I’ve pasted my complete code put together below just in case there’s any confusion from the excerpts above." } ]
Area of square Circumscribed by Circle - GeeksforGeeks
07 Nov, 2021 Given the radius(r) of circle then find the area of square which is Circumscribed by circle.Examples: Input : r = 3 Output :Area of square = 18 Input :r = 6 Output :Area of square = 72 All four sides of a square are of equal length and all four angles are 90 degree. The circle is circumscribed on a given square shown by a shaded region in the below diagram. Properties of Circumscribed circle are as follows: The center of the circumcircle is the point where the two diagonals of a square meet. Circumscribed circle of a square is made through the four vertices of a square. The radius of a circumcircle of a square is equal to the radius of a square. Formula used to calculate the area of circumscribed square is: 2 * r2 where, r is the radius of the circle in which a square is circumscribed by circle.How does this formula work?Assume diagonal of square is d and length of side is a.We know from the Pythagoras Theorem, the diagonal of a square is √(2) times the length of a side. i.e d2 = a2 + a2 d = 2 * a2 d = √(2) * a Now, a = d / √2and We know diagonal of square that are Circumscribed by Circle is equal to Diameter of circle. so Area of square = a * a = d / √(2) * d / √(2) = d2/ 2 = ( 2 * r )2/ 2 ( We know d = 2 * r ) = 2 * r2 CPP Java Python3 C# PHP Javascript // C++ program to find Area of// square Circumscribed by Circle#include <iostream>using namespace std; // Function to find area of squareint find_Area(int r){ return (2 * r * r);} // Driver codeint main() { // Radius of a circle int r = 3; // Call Function to find // an area of square cout << " Area of square = " << find_Area(r); return 0;} // Java program to find Area of// square Circumscribed by Circleclass GFG { // Function to find area of square static int find_Area(int r) { return (2 * r * r); } // Driver code public static void main(String[] args) { // Radius of a circle int r = 3; // Call Function to find // an area of square System.out.print(" Area of square = " + find_Area(r)); }} // This code is contributed by Anant Agarwal. # Python program to# find Area of# square Circumscribed# by Circle # Function to find# area of squaredef find_Area(r): return (2 * r * r) # driver code# Radius of a circler = 3 # Call Function to find # an area of squareprint(" Area of square = ", find_Area(r)) # This code is contributed# by Anant Agarwal. // C# program to find Area of// square Circumscribed by Circleusing System; class GFG { // Function to find area of square static int find_Area(int r) { return (2 * r * r); } // Driver code public static void Main() { // Radius of a circle int r = 3; // Call Function to find // an area of square Console.WriteLine(" Area of square = " + find_Area(r)); }} // This code is contributed by vt_m. <?php// PHP program to find Area of// square Circumscribed by Circle // Function to find area of squarefunction find_Area( $r){ return (2 * $r * $r);} // Driver code // Radius of a circle $r = 3; // Call Function to find // an area of square echo ("Area of square = "); echo(find_Area($r)); // This code is contributed by vt_m.?> <script>// Javascript program to find Area of // square Circumscribed by Circle // Function to find area of square function find_Area(r) { return (2 * r * r); } // Driver code // Radius of a circle let r = 3; // Call Function to find // an area of square document.write(" Area of square = " + find_Area(r)); // This code is contributed by Mayank Tyagi</script> Output: Area of square = 18 Time Complexity: O(1) vt_m mayanktyagi1709 area-volume-programs circle Geometric School Programming Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Circle and Lattice Points Queries on count of points lie inside a circle Convex Hull | Set 2 (Graham Scan) Given n line segments, find if any two segments intersect Check if a point lies inside a rectangle | Set-2 Python Dictionary Arrays in C/C++ Reverse a string in Java Inheritance in C++ C++ Classes and Objects
[ { "code": null, "e": 24533, "s": 24505, "text": "\n07 Nov, 2021" }, { "code": null, "e": 24637, "s": 24533, "text": "Given the radius(r) of circle then find the area of square which is Circumscribed by circle.Examples: " }, { "code": null, "e": 24721, "s": 24637, "text": "Input : r = 3\nOutput :Area of square = 18\n\nInput :r = 6\nOutput :Area of square = 72" }, { "code": null, "e": 24900, "s": 24723, "text": "All four sides of a square are of equal length and all four angles are 90 degree. The circle is circumscribed on a given square shown by a shaded region in the below diagram. " }, { "code": null, "e": 24953, "s": 24900, "text": "Properties of Circumscribed circle are as follows: " }, { "code": null, "e": 25039, "s": 24953, "text": "The center of the circumcircle is the point where the two diagonals of a square meet." }, { "code": null, "e": 25119, "s": 25039, "text": "Circumscribed circle of a square is made through the four vertices of a square." }, { "code": null, "e": 25196, "s": 25119, "text": "The radius of a circumcircle of a square is equal to the radius of a square." }, { "code": null, "e": 25785, "s": 25198, "text": "Formula used to calculate the area of circumscribed square is: 2 * r2 where, r is the radius of the circle in which a square is circumscribed by circle.How does this formula work?Assume diagonal of square is d and length of side is a.We know from the Pythagoras Theorem, the diagonal of a square is √(2) times the length of a side. i.e d2 = a2 + a2 d = 2 * a2 d = √(2) * a Now, a = d / √2and We know diagonal of square that are Circumscribed by Circle is equal to Diameter of circle. so Area of square = a * a = d / √(2) * d / √(2) = d2/ 2 = ( 2 * r )2/ 2 ( We know d = 2 * r ) = 2 * r2" }, { "code": null, "e": 25791, "s": 25787, "text": "CPP" }, { "code": null, "e": 25796, "s": 25791, "text": "Java" }, { "code": null, "e": 25804, "s": 25796, "text": "Python3" }, { "code": null, "e": 25807, "s": 25804, "text": "C#" }, { "code": null, "e": 25811, "s": 25807, "text": "PHP" }, { "code": null, "e": 25822, "s": 25811, "text": "Javascript" }, { "code": "// C++ program to find Area of// square Circumscribed by Circle#include <iostream>using namespace std; // Function to find area of squareint find_Area(int r){ return (2 * r * r);} // Driver codeint main() { // Radius of a circle int r = 3; // Call Function to find // an area of square cout << \" Area of square = \" << find_Area(r); return 0;}", "e": 26218, "s": 25822, "text": null }, { "code": "// Java program to find Area of// square Circumscribed by Circleclass GFG { // Function to find area of square static int find_Area(int r) { return (2 * r * r); } // Driver code public static void main(String[] args) { // Radius of a circle int r = 3; // Call Function to find // an area of square System.out.print(\" Area of square = \" + find_Area(r)); }} // This code is contributed by Anant Agarwal.", "e": 26729, "s": 26218, "text": null }, { "code": "# Python program to# find Area of# square Circumscribed# by Circle # Function to find# area of squaredef find_Area(r): return (2 * r * r) # driver code# Radius of a circler = 3 # Call Function to find # an area of squareprint(\" Area of square = \", find_Area(r)) # This code is contributed# by Anant Agarwal.", "e": 27054, "s": 26729, "text": null }, { "code": "// C# program to find Area of// square Circumscribed by Circleusing System; class GFG { // Function to find area of square static int find_Area(int r) { return (2 * r * r); } // Driver code public static void Main() { // Radius of a circle int r = 3; // Call Function to find // an area of square Console.WriteLine(\" Area of square = \" + find_Area(r)); }} // This code is contributed by vt_m.", "e": 27556, "s": 27054, "text": null }, { "code": "<?php// PHP program to find Area of// square Circumscribed by Circle // Function to find area of squarefunction find_Area( $r){ return (2 * $r * $r);} // Driver code // Radius of a circle $r = 3; // Call Function to find // an area of square echo (\"Area of square = \"); echo(find_Area($r)); // This code is contributed by vt_m.?>", "e": 27925, "s": 27556, "text": null }, { "code": "<script>// Javascript program to find Area of // square Circumscribed by Circle // Function to find area of square function find_Area(r) { return (2 * r * r); } // Driver code // Radius of a circle let r = 3; // Call Function to find // an area of square document.write(\" Area of square = \" + find_Area(r)); // This code is contributed by Mayank Tyagi</script>", "e": 28344, "s": 27925, "text": null }, { "code": null, "e": 28353, "s": 28344, "text": "Output: " }, { "code": null, "e": 28373, "s": 28353, "text": "Area of square = 18" }, { "code": null, "e": 28396, "s": 28373, "text": "Time Complexity: O(1) " }, { "code": null, "e": 28401, "s": 28396, "text": "vt_m" }, { "code": null, "e": 28417, "s": 28401, "text": "mayanktyagi1709" }, { "code": null, "e": 28438, "s": 28417, "text": "area-volume-programs" }, { "code": null, "e": 28445, "s": 28438, "text": "circle" }, { "code": null, "e": 28455, "s": 28445, "text": "Geometric" }, { "code": null, "e": 28474, "s": 28455, "text": "School Programming" }, { "code": null, "e": 28484, "s": 28474, "text": "Geometric" }, { "code": null, "e": 28582, "s": 28484, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28591, "s": 28582, "text": "Comments" }, { "code": null, "e": 28604, "s": 28591, "text": "Old Comments" }, { "code": null, "e": 28630, "s": 28604, "text": "Circle and Lattice Points" }, { "code": null, "e": 28677, "s": 28630, "text": "Queries on count of points lie inside a circle" }, { "code": null, "e": 28711, "s": 28677, "text": "Convex Hull | Set 2 (Graham Scan)" }, { "code": null, "e": 28769, "s": 28711, "text": "Given n line segments, find if any two segments intersect" }, { "code": null, "e": 28818, "s": 28769, "text": "Check if a point lies inside a rectangle | Set-2" }, { "code": null, "e": 28836, "s": 28818, "text": "Python Dictionary" }, { "code": null, "e": 28852, "s": 28836, "text": "Arrays in C/C++" }, { "code": null, "e": 28877, "s": 28852, "text": "Reverse a string in Java" }, { "code": null, "e": 28896, "s": 28877, "text": "Inheritance in C++" } ]
Convert HashSet to TreeSet in Java
At first, create a HashSet with string values − HashSet<String> hashSet = new HashSet<String>(); hashSet.add("Bradley"); hashSet.add("Katie"); hashSet.add("Brad"); hashSet.add("Amy"); hashSet.add("Ryan"); hashSet.add("Jamie"); Now, convert the HashSet to TreeSet − Set<String> set = new TreeSet<String>(hashSet); Following is the program to convert HashSet to TreeSet in Java − import java.util.HashSet; import java.util.Set; import java.util.TreeSet; public class Demo { public static void main(String[] args) { HashSet<String> hashSet = new HashSet<String>(); hashSet.add("Bradley"); hashSet.add("Katie"); hashSet.add("Brad"); hashSet.add("Amy"); hashSet.add("Ryan"); hashSet.add("Jamie"); hashSet.add("Kevin"); hashSet.add("David"); System.out.println("HashSet = "+ hashSet); Set<String> set = new TreeSet<String>(hashSet); System.out.println("TreeSet = "+set); } } HashSet = [Kevin, Jamie, Ryan, Bradley, Katie, David, Brad, Amy] TreeSet = [Amy, Brad, Bradley, David, Jamie, Katie, Kevin, Ryan]
[ { "code": null, "e": 1110, "s": 1062, "text": "At first, create a HashSet with string values −" }, { "code": null, "e": 1289, "s": 1110, "text": "HashSet<String> hashSet = new HashSet<String>();\nhashSet.add(\"Bradley\");\nhashSet.add(\"Katie\");\nhashSet.add(\"Brad\");\nhashSet.add(\"Amy\");\nhashSet.add(\"Ryan\");\nhashSet.add(\"Jamie\");" }, { "code": null, "e": 1327, "s": 1289, "text": "Now, convert the HashSet to TreeSet −" }, { "code": null, "e": 1375, "s": 1327, "text": "Set<String> set = new TreeSet<String>(hashSet);" }, { "code": null, "e": 1440, "s": 1375, "text": "Following is the program to convert HashSet to TreeSet in Java −" }, { "code": null, "e": 2009, "s": 1440, "text": "import java.util.HashSet;\nimport java.util.Set;\nimport java.util.TreeSet;\npublic class Demo {\n public static void main(String[] args) {\n HashSet<String> hashSet = new HashSet<String>();\n hashSet.add(\"Bradley\");\n hashSet.add(\"Katie\");\n hashSet.add(\"Brad\");\n hashSet.add(\"Amy\");\n hashSet.add(\"Ryan\");\n hashSet.add(\"Jamie\");\n hashSet.add(\"Kevin\");\n hashSet.add(\"David\");\n System.out.println(\"HashSet = \"+ hashSet);\n Set<String> set = new TreeSet<String>(hashSet);\n System.out.println(\"TreeSet = \"+set);\n }\n}" }, { "code": null, "e": 2139, "s": 2009, "text": "HashSet = [Kevin, Jamie, Ryan, Bradley, Katie, David, Brad, Amy]\nTreeSet = [Amy, Brad, Bradley, David, Jamie, Katie, Kevin, Ryan]" } ]
Number of elements with odd factors in given range - GeeksforGeeks
31 Mar, 2021 Given a range [n,m], find the number of elements that have odd number of factors in the given range (n and m inclusive). Examples : Input : n = 5, m = 100 Output : 8 The numbers with odd factors are 9, 16, 25, 36, 49, 64, 81 and 100 Input : n = 8, m = 65 Output : 6 Input : n = 10, m = 23500 Output : 150 A Simple Solution is to loop through all numbers starting from n. For every number, check if it has an even number of factors. If it has an even number of factors then increment count of such numbers and finally print the number of such elements. To find all divisors of a natural number efficiently, refer All divisors of a natural numberAn Efficient Solution is to observe the pattern. Only those numbers, which are perfect Squares have an odd number of factors. Let us analyze this pattern through an example.For example, 9 has odd number of factors, 1, 3 and 9. 16 also has odd number of factors, 1, 2, 4, 8, 16. The reason for this is, for numbers other than perfect squares, all factors are in the form of pairs, but for perfect squares, one factor is single and makes the total as odd.How to find number of perfect squares in a range? The answer is difference between square root of m and n-1 (not n) There is a little caveat. As both n and m are inclusive, if n is a perfect square, we will get an answer which is less than one the actual answer. To understand this, consider range [4, 36]. Answer is 5 i.e., numbers 4, 9, 16, 25 and 36. But if we do (36**0.5) – (4**0.5) we get 4. So to avoid this semantic error, we take n-1. C++ Java Python3 C# PHP Javascript // C++ program to count number of odd squares// in given range [n, m]#include <bits/stdc++.h>using namespace std; int countOddSquares(int n, int m){ return (int)pow(m,0.5) - (int)pow(n-1,0.5);} // Driver codeint main(){ int n = 5, m = 100; cout << "Count is " << countOddSquares(n, m); return 0;} // Java program to count number of odd squares// in given range [n, m] import java.io.*;import java.util.*;import java.lang.*; class GFG{ public static int countOddSquares(int n, int m) { return (int)Math.pow((double)m,0.5) - (int)Math.pow((double)n-1,0.5); } // Driver code for above functions public static void main (String[] args) { int n = 5, m = 100; System.out.print("Count is " + countOddSquares(n, m)); }}// Mohit Gupta_OMG <(o_0)> # Python program to count number of odd squares# in given range [n, m] def countOddSquares(n, m): return int(m**0.5) - int((n-1)**0.5) # Driver coden = 5m = 100print("Count is", countOddSquares(n, m)) # Mohit Gupta_OMG <0_o> // C# program to count number of odd// squares in given range [n, m]using System; class GFG { // Function to count odd squares public static int countOddSquares(int n, int m) { return (int)Math.Pow((double)m, 0.5) - (int)Math.Pow((double)n - 1, 0.5); } // Driver code public static void Main () { int n = 5, m = 100; Console.Write("Count is " + countOddSquares(n, m)); }} // This code is contributed by Nitin Mittal. <?php// PHP program to count// number of odd squares// in given range [n, m] function countOddSquares($n, $m){return pow($m, 0.5) - pow($n - 1, 0.5);} // Driver code$n = 5; $m = 100;echo "Count is " , countOddSquares($n, $m); // This code is contributed// by nitin mittal.?> <script> // JavaScript program to count number of odd squares// in given range [n, m] function countOddSquares(n, m) { return Math.pow(m,0.5) - Math.pow(n-1,0.5); } // Driver Code let n = 5, m = 100; document.write("Count is " + countOddSquares(n, m)); </script> Output : Count is 8 Time Complexity : O(1)This article is contributed by Divyanshu Bansal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. nitin mittal code_hunt Wipro Mathematical Wipro Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Prime Numbers Program for Decimal to Binary Conversion Modulo 10^9+7 (1000000007) Program to find sum of elements in a given array The Knight's tour problem | Backtracking-1 Program for factorial of a number Minimum number of jumps to reach end Operators in C / C++
[ { "code": null, "e": 24503, "s": 24475, "text": "\n31 Mar, 2021" }, { "code": null, "e": 24637, "s": 24503, "text": "Given a range [n,m], find the number of elements that have odd number of factors in the given range (n and m inclusive). Examples : " }, { "code": null, "e": 24816, "s": 24637, "text": "Input : n = 5, m = 100\nOutput : 8\nThe numbers with odd factors are 9, 16, 25, \n36, 49, 64, 81 and 100\n\nInput : n = 8, m = 65\nOutput : 6\n\nInput : n = 10, m = 23500\nOutput : 150" }, { "code": null, "e": 26055, "s": 24818, "text": "A Simple Solution is to loop through all numbers starting from n. For every number, check if it has an even number of factors. If it has an even number of factors then increment count of such numbers and finally print the number of such elements. To find all divisors of a natural number efficiently, refer All divisors of a natural numberAn Efficient Solution is to observe the pattern. Only those numbers, which are perfect Squares have an odd number of factors. Let us analyze this pattern through an example.For example, 9 has odd number of factors, 1, 3 and 9. 16 also has odd number of factors, 1, 2, 4, 8, 16. The reason for this is, for numbers other than perfect squares, all factors are in the form of pairs, but for perfect squares, one factor is single and makes the total as odd.How to find number of perfect squares in a range? The answer is difference between square root of m and n-1 (not n) There is a little caveat. As both n and m are inclusive, if n is a perfect square, we will get an answer which is less than one the actual answer. To understand this, consider range [4, 36]. Answer is 5 i.e., numbers 4, 9, 16, 25 and 36. But if we do (36**0.5) – (4**0.5) we get 4. So to avoid this semantic error, we take n-1. " }, { "code": null, "e": 26059, "s": 26055, "text": "C++" }, { "code": null, "e": 26064, "s": 26059, "text": "Java" }, { "code": null, "e": 26072, "s": 26064, "text": "Python3" }, { "code": null, "e": 26075, "s": 26072, "text": "C#" }, { "code": null, "e": 26079, "s": 26075, "text": "PHP" }, { "code": null, "e": 26090, "s": 26079, "text": "Javascript" }, { "code": "// C++ program to count number of odd squares// in given range [n, m]#include <bits/stdc++.h>using namespace std; int countOddSquares(int n, int m){ return (int)pow(m,0.5) - (int)pow(n-1,0.5);} // Driver codeint main(){ int n = 5, m = 100; cout << \"Count is \" << countOddSquares(n, m); return 0;}", "e": 26398, "s": 26090, "text": null }, { "code": "// Java program to count number of odd squares// in given range [n, m] import java.io.*;import java.util.*;import java.lang.*; class GFG{ public static int countOddSquares(int n, int m) { return (int)Math.pow((double)m,0.5) - (int)Math.pow((double)n-1,0.5); } // Driver code for above functions public static void main (String[] args) { int n = 5, m = 100; System.out.print(\"Count is \" + countOddSquares(n, m)); }}// Mohit Gupta_OMG <(o_0)>", "e": 26881, "s": 26398, "text": null }, { "code": "# Python program to count number of odd squares# in given range [n, m] def countOddSquares(n, m): return int(m**0.5) - int((n-1)**0.5) # Driver coden = 5m = 100print(\"Count is\", countOddSquares(n, m)) # Mohit Gupta_OMG <0_o>", "e": 27109, "s": 26881, "text": null }, { "code": "// C# program to count number of odd// squares in given range [n, m]using System; class GFG { // Function to count odd squares public static int countOddSquares(int n, int m) { return (int)Math.Pow((double)m, 0.5) - (int)Math.Pow((double)n - 1, 0.5); } // Driver code public static void Main () { int n = 5, m = 100; Console.Write(\"Count is \" + countOddSquares(n, m)); }} // This code is contributed by Nitin Mittal.", "e": 27595, "s": 27109, "text": null }, { "code": "<?php// PHP program to count// number of odd squares// in given range [n, m] function countOddSquares($n, $m){return pow($m, 0.5) - pow($n - 1, 0.5);} // Driver code$n = 5; $m = 100;echo \"Count is \" , countOddSquares($n, $m); // This code is contributed// by nitin mittal.?>", "e": 27881, "s": 27595, "text": null }, { "code": "<script> // JavaScript program to count number of odd squares// in given range [n, m] function countOddSquares(n, m) { return Math.pow(m,0.5) - Math.pow(n-1,0.5); } // Driver Code let n = 5, m = 100; document.write(\"Count is \" + countOddSquares(n, m)); </script>", "e": 28196, "s": 27881, "text": null }, { "code": null, "e": 28206, "s": 28196, "text": "Output : " }, { "code": null, "e": 28217, "s": 28206, "text": "Count is 8" }, { "code": null, "e": 28664, "s": 28217, "text": "Time Complexity : O(1)This article is contributed by Divyanshu Bansal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 28677, "s": 28664, "text": "nitin mittal" }, { "code": null, "e": 28687, "s": 28677, "text": "code_hunt" }, { "code": null, "e": 28693, "s": 28687, "text": "Wipro" }, { "code": null, "e": 28706, "s": 28693, "text": "Mathematical" }, { "code": null, "e": 28712, "s": 28706, "text": "Wipro" }, { "code": null, "e": 28725, "s": 28712, "text": "Mathematical" }, { "code": null, "e": 28823, "s": 28725, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28832, "s": 28823, "text": "Comments" }, { "code": null, "e": 28845, "s": 28832, "text": "Old Comments" }, { "code": null, "e": 28869, "s": 28845, "text": "Merge two sorted arrays" }, { "code": null, "e": 28912, "s": 28869, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 28926, "s": 28912, "text": "Prime Numbers" }, { "code": null, "e": 28967, "s": 28926, "text": "Program for Decimal to Binary Conversion" }, { "code": null, "e": 28994, "s": 28967, "text": "Modulo 10^9+7 (1000000007)" }, { "code": null, "e": 29043, "s": 28994, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 29086, "s": 29043, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 29120, "s": 29086, "text": "Program for factorial of a number" }, { "code": null, "e": 29157, "s": 29120, "text": "Minimum number of jumps to reach end" } ]
C++ Fstream Library - Swap Function
It is used to exchanges all internal data between x and *this. Following is the declaration for fstream::swap. void swap (basic_fstream& x); x − Another basic_fstream object of the same type (i.e., with the same template parameters charT and traits). none No-throw guarantee − this member function never throws exceptions. It modifies both stream objects (*this and x). In below example explains about fstream swap function. #include <fstream> int main () { std::fstream foo; std::fstream bar ("test.txt"); foo.swap(bar); foo << "lorem ipsum"; foo.close(); return 0; } Print Add Notes Bookmark this page
[ { "code": null, "e": 2666, "s": 2603, "text": "It is used to exchanges all internal data between x and *this." }, { "code": null, "e": 2714, "s": 2666, "text": "Following is the declaration for fstream::swap." }, { "code": null, "e": 2744, "s": 2714, "text": "void swap (basic_fstream& x);" }, { "code": null, "e": 2854, "s": 2744, "text": "x − Another basic_fstream object of the same type (i.e., with the same template parameters charT and traits)." }, { "code": null, "e": 2859, "s": 2854, "text": "none" }, { "code": null, "e": 2926, "s": 2859, "text": "No-throw guarantee − this member function never throws exceptions." }, { "code": null, "e": 2973, "s": 2926, "text": "It modifies both stream objects (*this and x)." }, { "code": null, "e": 3028, "s": 2973, "text": "In below example explains about fstream swap function." }, { "code": null, "e": 3195, "s": 3028, "text": "#include <fstream>\n\nint main () {\n std::fstream foo;\n std::fstream bar (\"test.txt\");\n\n foo.swap(bar);\n\n foo << \"lorem ipsum\";\n\n foo.close();\n\n return 0;\n}" }, { "code": null, "e": 3202, "s": 3195, "text": " Print" }, { "code": null, "e": 3213, "s": 3202, "text": " Add Notes" } ]
How to identify composite primary key in any MySQL database table?
You can use aggregate function count(*). If it returns a value greater than 1, that would mean the table has composite primary key. Let us first create a table − mysql> create table DemoTable1324 -> ( -> StudentId int, -> StudentName varchar(20), -> StudentAge int, -> StudentCountryName varchar(20) -> ); Query OK, 0 rows affected (0.52 sec) Here is the query to add composite primary key − mysql> alter table DemoTable1324 ADD CONSTRAINT constr_IdAgeCountry PRIMARY KEY (StudentId, StudentAge,StudentCountryName); Query OK, 0 rows affected (1.29 sec) Records: 0 Duplicates: 0 Warnings: 0 Following is the query to identify composite primary key in any MySQL database table − mysql> select count(*) AS Total -> from information_schema.KEY_COLUMN_USAGE -> where table_name='DemoTable1324' and table_schema=database(); This will produce the following output − +-------+ | Total | +-------+ | 3 | +-------+ 1 row in set, 2 warnings (0.76 sec)
[ { "code": null, "e": 1194, "s": 1062, "text": "You can use aggregate function count(*). If it returns a value greater than 1, that would mean the table has composite primary key." }, { "code": null, "e": 1224, "s": 1194, "text": "Let us first create a table −" }, { "code": null, "e": 1423, "s": 1224, "text": "mysql> create table DemoTable1324\n -> (\n -> StudentId int,\n -> StudentName varchar(20),\n -> StudentAge int,\n -> StudentCountryName varchar(20)\n -> );\nQuery OK, 0 rows affected (0.52 sec)" }, { "code": null, "e": 1472, "s": 1423, "text": "Here is the query to add composite primary key −" }, { "code": null, "e": 1670, "s": 1472, "text": "mysql> alter table DemoTable1324 ADD CONSTRAINT constr_IdAgeCountry PRIMARY KEY (StudentId, StudentAge,StudentCountryName);\nQuery OK, 0 rows affected (1.29 sec)\nRecords: 0 Duplicates: 0 Warnings: 0" }, { "code": null, "e": 1757, "s": 1670, "text": "Following is the query to identify composite primary key in any MySQL database table −" }, { "code": null, "e": 1904, "s": 1757, "text": "mysql> select count(*) AS Total\n -> from information_schema.KEY_COLUMN_USAGE\n -> where table_name='DemoTable1324' and table_schema=database();" }, { "code": null, "e": 1945, "s": 1904, "text": "This will produce the following output −" }, { "code": null, "e": 2031, "s": 1945, "text": "+-------+\n| Total |\n+-------+\n| 3 |\n+-------+\n1 row in set, 2 warnings (0.76 sec)" } ]
Count ways to split array into two subsets having difference between their sum equal to K - GeeksforGeeks
29 Jun, 2021 Given an array A[] of size N and an integer diff, the task is to count the number of ways to split the array into two subsets (non-empty subset is possible) such that the difference between their sums is equal to diff. Examples: Input: A[] = {1, 1, 2, 3}, diff = 1 Output: 3 Explanation: All possible combinations are as follows: {1, 1, 2} and {3} {1, 3} and {1, 2} {1, 2} and {1, 3} All partitions have difference between their sums equal to 1. Therefore, the count of ways is 3. Input: A[] = {1, 6, 11, 5}, diff=1Output: 2 Naive Approach: The simplest approach to solve the problem is based on the following observations: Let the sum of elements in the partition subsets S1 and S2 be sum1 and sum2 respectively.Let sum of the array A[] be X. Given, sum1 – sum2 = diff – (1)Also, sum1 + sum2 = X – (2) From equations (1) and (2), sum1 = (X + diff)/2 Therefore, the task is reduced to finding the number of subsets with a given sum. Therefore, the simplest approach is to solve this problem is by generating all the possible subsets and checking whether the subset has the required sum. Time Complexity: O(2N)Auxiliary Space: O(N) Efficient Approach: To optimize the above approach, the idea is to use Dynamic Programming. Initialize a dp[][] table of size N*X, where dp[i][C] stores the number of subsets of the sub-array A[i...N-1] such that their sum is equal to C. Thus, the recurrence is very trivial as there are only two choices i.e. either consider the ith element in the subset or don’t. So the recurrence relation will be: dp[i][C] = dp[i – 1][C – A[i]] + dp[i-1][C] Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to count the number of ways to divide// the array into two subsets and such that the// difference between their sums is equal to diffint countSubset(int arr[], int n, int diff){ // Store the sum of the set S1 int sum = 0; for (int i = 0; i < n; i++) sum += arr[i]; sum += diff; sum = sum / 2; // Initializing the matrix int t[n + 1][sum + 1]; // Number of ways to get sum // using 0 elements is 0 for (int j = 0; j <= sum; j++) t[0][j] = 0; // Number of ways to get sum 0 // using i elements is 1 for (int i = 0; i <= n; i++) t[i][0] = 1; // Traverse the 2D array for (int i = 1; i <= n; i++) { for (int j = 1; j <= sum; j++) { // If the value is greater // than the sum store the // value of previous state if (arr[i - 1] > j) t[i][j] = t[i - 1][j]; else { t[i][j] = t[i - 1][j] + t[i - 1][j - arr[i - 1]]; } } } // Return the result return t[n][sum];} // Driver Codeint main(){ // Given Input int diff = 1, n = 4; int arr[] = { 1, 1, 2, 3 }; // Function Call cout << countSubset(arr, n, diff);} // Java program for the above approachimport java.io.*;public class GFG{ // Function to count the number of ways to divide // the array into two subsets and such that the // difference between their sums is equal to diff static int countSubset(int []arr, int n, int diff) { // Store the sum of the set S1 int sum = 0; for (int i = 0; i < n; i++) sum += arr[i]; sum += diff; sum = sum / 2; // Initializing the matrix int t[][] = new int[n + 1][sum + 1]; // Number of ways to get sum // using 0 elements is 0 for (int j = 0; j <= sum; j++) t[0][j] = 0; // Number of ways to get sum 0 // using i elements is 1 for (int i = 0; i <= n; i++) t[i][0] = 1; // Traverse the 2D array for (int i = 1; i <= n; i++) { for (int j = 1; j <= sum; j++) { // If the value is greater // than the sum store the // value of previous state if (arr[i - 1] > j) t[i][j] = t[i - 1][j]; else { t[i][j] = t[i - 1][j] + t[i - 1][j - arr[i - 1]]; } } } // Return the result return t[n][sum]; } // Driver Code public static void main(String[] args) { // Given Input int diff = 1, n = 4; int arr[] = { 1, 1, 2, 3 }; // Function Call System.out.print(countSubset(arr, n, diff)); }} // This code is contributed by AnkThon # Python3 program for the above approach # Function to count the number of ways to divide# the array into two subsets and such that the# difference between their sums is equal to diffdef countSubset(arr, n, diff): # Store the sum of the set S1 sum = 0 for i in range(n): sum += arr[i] sum += diff sum = sum // 2 # Initializing the matrix t = [[0 for i in range(sum + 1)] for i in range(n + 1)] # Number of ways to get sum # using 0 elements is 0 for j in range(sum + 1): t[0][j] = 0 # Number of ways to get sum 0 # using i elements is 1 for i in range(n + 1): t[i][0] = 1 # Traverse the 2D array for i in range(1, n + 1): for j in range(1, sum + 1): # If the value is greater # than the sum store the # value of previous state if (arr[i - 1] > j): t[i][j] = t[i - 1][j] else: t[i][j] = t[i - 1][j] + t[i - 1][j - arr[i - 1]] # Return the result return t[n][sum] # Driver Codeif __name__ == '__main__': # Given Input diff, n = 1, 4 arr = [ 1, 1, 2, 3 ] # Function Call print (countSubset(arr, n, diff)) # This code is contributed by mohit kumar 29 // C# program for the above approach using System; public class GFG{ // Function to count the number of ways to divide // the array into two subsets and such that the // difference between their sums is equal to diff static int countSubset(int []arr, int n, int diff) { // Store the sum of the set S1 int sum = 0; for (int i = 0; i < n; i++) sum += arr[i]; sum += diff; sum = sum / 2; // Initializing the matrix int [,]t = new int[n + 1, sum + 1]; // Number of ways to get sum // using 0 elements is 0 for (int j = 0; j <= sum; j++) t[0,j] = 0; // Number of ways to get sum 0 // using i elements is 1 for (int i = 0; i <= n; i++) t[i,0] = 1; // Traverse the 2D array for (int i = 1; i <= n; i++) { for (int j = 1; j <= sum; j++) { // If the value is greater // than the sum store the // value of previous state if (arr[i - 1] > j) t[i,j] = t[i - 1,j]; else { t[i,j] = t[i - 1,j] + t[i - 1,j - arr[i - 1]]; } } } // Return the result return t[n,sum]; } // Driver Code public static void Main(string[] args) { // Given Input int diff = 1, n = 4; int []arr = { 1, 1, 2, 3 }; // Function Call Console.Write(countSubset(arr, n, diff)); }} // This code is contributed by AnkThon <script> // JavaScript program for the above approach // Function to count the number of ways to divide// the array into two subsets and such that the// difference between their sums is equal to difffunction countSubset(arr, n, diff){ // Store the sum of the set S1 var sum = 0; for (var i = 0; i < n; i++){ sum += arr[i]; } sum += diff; sum = sum / 2; // Initializing the matrix //int t[n + 1][sum + 1]; var t = new Array(n + 1); // Loop to create 2D array using 1D array for (var i = 0; i < t.length; i++) { t[i] = new Array(sum + 1); } // Loop to initialize 2D array elements. for (var i = 0; i < t.length; i++) { for (var j = 0; j < t[i].length; j++) { t[i][j] = 0; } } // Number of ways to get sum // using 0 elements is 0 for (var j = 0; j <= sum; j++) t[0][j] = 0; // Number of ways to get sum 0 // using i elements is 1 for (var i = 0; i <= n; i++) t[i][0] = 1; // Traverse the 2D array for (var i = 1; i <= n; i++) { for (var j = 1; j <= sum; j++) { // If the value is greater // than the sum store the // value of previous state if (arr[i - 1] > j) t[i][j] = t[i - 1][j]; else { t[i][j] = t[i - 1][j] + t[i - 1][j - arr[i - 1]]; } } } // Return the result return t[n][sum];} // Driver Code // Given Inputvar diff = 1;var n = 4;var arr = [ 1, 1, 2, 3 ]; // Function Calldocument.write(countSubset(arr, n, diff)); </script> 3 Time Complexity: O(S*N), where S = sum of array elements + K/2 Auxiliary Space: O(S*N) mohit kumar 29 ankthon partition subset Arrays Dynamic Programming Mathematical Arrays Dynamic Programming Mathematical subset Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Chocolate Distribution Problem Reversal algorithm for array rotation Window Sliding Technique Next Greater Element Find duplicates in O(n) time and O(1) extra space | Set 1 0-1 Knapsack Problem | DP-10 Program for Fibonacci numbers Longest Common Subsequence | DP-4 Bellman–Ford Algorithm | DP-23 Floyd Warshall Algorithm | DP-16
[ { "code": null, "e": 26175, "s": 26147, "text": "\n29 Jun, 2021" }, { "code": null, "e": 26394, "s": 26175, "text": "Given an array A[] of size N and an integer diff, the task is to count the number of ways to split the array into two subsets (non-empty subset is possible) such that the difference between their sums is equal to diff." }, { "code": null, "e": 26404, "s": 26394, "text": "Examples:" }, { "code": null, "e": 26508, "s": 26404, "text": "Input: A[] = {1, 1, 2, 3}, diff = 1 Output: 3 Explanation: All possible combinations are as follows: " }, { "code": null, "e": 26526, "s": 26508, "text": "{1, 1, 2} and {3}" }, { "code": null, "e": 26544, "s": 26526, "text": "{1, 3} and {1, 2}" }, { "code": null, "e": 26562, "s": 26544, "text": "{1, 2} and {1, 3}" }, { "code": null, "e": 26659, "s": 26562, "text": "All partitions have difference between their sums equal to 1. Therefore, the count of ways is 3." }, { "code": null, "e": 26703, "s": 26659, "text": "Input: A[] = {1, 6, 11, 5}, diff=1Output: 2" }, { "code": null, "e": 26802, "s": 26703, "text": "Naive Approach: The simplest approach to solve the problem is based on the following observations:" }, { "code": null, "e": 26981, "s": 26802, "text": "Let the sum of elements in the partition subsets S1 and S2 be sum1 and sum2 respectively.Let sum of the array A[] be X. Given, sum1 – sum2 = diff – (1)Also, sum1 + sum2 = X – (2)" }, { "code": null, "e": 27029, "s": 26981, "text": "From equations (1) and (2), sum1 = (X + diff)/2" }, { "code": null, "e": 27266, "s": 27029, "text": "Therefore, the task is reduced to finding the number of subsets with a given sum. Therefore, the simplest approach is to solve this problem is by generating all the possible subsets and checking whether the subset has the required sum. " }, { "code": null, "e": 27310, "s": 27266, "text": "Time Complexity: O(2N)Auxiliary Space: O(N)" }, { "code": null, "e": 27712, "s": 27310, "text": "Efficient Approach: To optimize the above approach, the idea is to use Dynamic Programming. Initialize a dp[][] table of size N*X, where dp[i][C] stores the number of subsets of the sub-array A[i...N-1] such that their sum is equal to C. Thus, the recurrence is very trivial as there are only two choices i.e. either consider the ith element in the subset or don’t. So the recurrence relation will be:" }, { "code": null, "e": 27756, "s": 27712, "text": "dp[i][C] = dp[i – 1][C – A[i]] + dp[i-1][C]" }, { "code": null, "e": 27807, "s": 27756, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 27811, "s": 27807, "text": "C++" }, { "code": null, "e": 27816, "s": 27811, "text": "Java" }, { "code": null, "e": 27824, "s": 27816, "text": "Python3" }, { "code": null, "e": 27827, "s": 27824, "text": "C#" }, { "code": null, "e": 27838, "s": 27827, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to count the number of ways to divide// the array into two subsets and such that the// difference between their sums is equal to diffint countSubset(int arr[], int n, int diff){ // Store the sum of the set S1 int sum = 0; for (int i = 0; i < n; i++) sum += arr[i]; sum += diff; sum = sum / 2; // Initializing the matrix int t[n + 1][sum + 1]; // Number of ways to get sum // using 0 elements is 0 for (int j = 0; j <= sum; j++) t[0][j] = 0; // Number of ways to get sum 0 // using i elements is 1 for (int i = 0; i <= n; i++) t[i][0] = 1; // Traverse the 2D array for (int i = 1; i <= n; i++) { for (int j = 1; j <= sum; j++) { // If the value is greater // than the sum store the // value of previous state if (arr[i - 1] > j) t[i][j] = t[i - 1][j]; else { t[i][j] = t[i - 1][j] + t[i - 1][j - arr[i - 1]]; } } } // Return the result return t[n][sum];} // Driver Codeint main(){ // Given Input int diff = 1, n = 4; int arr[] = { 1, 1, 2, 3 }; // Function Call cout << countSubset(arr, n, diff);}", "e": 29162, "s": 27838, "text": null }, { "code": "// Java program for the above approachimport java.io.*;public class GFG{ // Function to count the number of ways to divide // the array into two subsets and such that the // difference between their sums is equal to diff static int countSubset(int []arr, int n, int diff) { // Store the sum of the set S1 int sum = 0; for (int i = 0; i < n; i++) sum += arr[i]; sum += diff; sum = sum / 2; // Initializing the matrix int t[][] = new int[n + 1][sum + 1]; // Number of ways to get sum // using 0 elements is 0 for (int j = 0; j <= sum; j++) t[0][j] = 0; // Number of ways to get sum 0 // using i elements is 1 for (int i = 0; i <= n; i++) t[i][0] = 1; // Traverse the 2D array for (int i = 1; i <= n; i++) { for (int j = 1; j <= sum; j++) { // If the value is greater // than the sum store the // value of previous state if (arr[i - 1] > j) t[i][j] = t[i - 1][j]; else { t[i][j] = t[i - 1][j] + t[i - 1][j - arr[i - 1]]; } } } // Return the result return t[n][sum]; } // Driver Code public static void main(String[] args) { // Given Input int diff = 1, n = 4; int arr[] = { 1, 1, 2, 3 }; // Function Call System.out.print(countSubset(arr, n, diff)); }} // This code is contributed by AnkThon", "e": 30816, "s": 29162, "text": null }, { "code": "# Python3 program for the above approach # Function to count the number of ways to divide# the array into two subsets and such that the# difference between their sums is equal to diffdef countSubset(arr, n, diff): # Store the sum of the set S1 sum = 0 for i in range(n): sum += arr[i] sum += diff sum = sum // 2 # Initializing the matrix t = [[0 for i in range(sum + 1)] for i in range(n + 1)] # Number of ways to get sum # using 0 elements is 0 for j in range(sum + 1): t[0][j] = 0 # Number of ways to get sum 0 # using i elements is 1 for i in range(n + 1): t[i][0] = 1 # Traverse the 2D array for i in range(1, n + 1): for j in range(1, sum + 1): # If the value is greater # than the sum store the # value of previous state if (arr[i - 1] > j): t[i][j] = t[i - 1][j] else: t[i][j] = t[i - 1][j] + t[i - 1][j - arr[i - 1]] # Return the result return t[n][sum] # Driver Codeif __name__ == '__main__': # Given Input diff, n = 1, 4 arr = [ 1, 1, 2, 3 ] # Function Call print (countSubset(arr, n, diff)) # This code is contributed by mohit kumar 29", "e": 32091, "s": 30816, "text": null }, { "code": "// C# program for the above approach using System; public class GFG{ // Function to count the number of ways to divide // the array into two subsets and such that the // difference between their sums is equal to diff static int countSubset(int []arr, int n, int diff) { // Store the sum of the set S1 int sum = 0; for (int i = 0; i < n; i++) sum += arr[i]; sum += diff; sum = sum / 2; // Initializing the matrix int [,]t = new int[n + 1, sum + 1]; // Number of ways to get sum // using 0 elements is 0 for (int j = 0; j <= sum; j++) t[0,j] = 0; // Number of ways to get sum 0 // using i elements is 1 for (int i = 0; i <= n; i++) t[i,0] = 1; // Traverse the 2D array for (int i = 1; i <= n; i++) { for (int j = 1; j <= sum; j++) { // If the value is greater // than the sum store the // value of previous state if (arr[i - 1] > j) t[i,j] = t[i - 1,j]; else { t[i,j] = t[i - 1,j] + t[i - 1,j - arr[i - 1]]; } } } // Return the result return t[n,sum]; } // Driver Code public static void Main(string[] args) { // Given Input int diff = 1, n = 4; int []arr = { 1, 1, 2, 3 }; // Function Call Console.Write(countSubset(arr, n, diff)); }} // This code is contributed by AnkThon", "e": 33729, "s": 32091, "text": null }, { "code": "<script> // JavaScript program for the above approach // Function to count the number of ways to divide// the array into two subsets and such that the// difference between their sums is equal to difffunction countSubset(arr, n, diff){ // Store the sum of the set S1 var sum = 0; for (var i = 0; i < n; i++){ sum += arr[i]; } sum += diff; sum = sum / 2; // Initializing the matrix //int t[n + 1][sum + 1]; var t = new Array(n + 1); // Loop to create 2D array using 1D array for (var i = 0; i < t.length; i++) { t[i] = new Array(sum + 1); } // Loop to initialize 2D array elements. for (var i = 0; i < t.length; i++) { for (var j = 0; j < t[i].length; j++) { t[i][j] = 0; } } // Number of ways to get sum // using 0 elements is 0 for (var j = 0; j <= sum; j++) t[0][j] = 0; // Number of ways to get sum 0 // using i elements is 1 for (var i = 0; i <= n; i++) t[i][0] = 1; // Traverse the 2D array for (var i = 1; i <= n; i++) { for (var j = 1; j <= sum; j++) { // If the value is greater // than the sum store the // value of previous state if (arr[i - 1] > j) t[i][j] = t[i - 1][j]; else { t[i][j] = t[i - 1][j] + t[i - 1][j - arr[i - 1]]; } } } // Return the result return t[n][sum];} // Driver Code // Given Inputvar diff = 1;var n = 4;var arr = [ 1, 1, 2, 3 ]; // Function Calldocument.write(countSubset(arr, n, diff)); </script>", "e": 35344, "s": 33729, "text": null }, { "code": null, "e": 35346, "s": 35344, "text": "3" }, { "code": null, "e": 35435, "s": 35348, "text": "Time Complexity: O(S*N), where S = sum of array elements + K/2 Auxiliary Space: O(S*N)" }, { "code": null, "e": 35452, "s": 35437, "text": "mohit kumar 29" }, { "code": null, "e": 35460, "s": 35452, "text": "ankthon" }, { "code": null, "e": 35470, "s": 35460, "text": "partition" }, { "code": null, "e": 35477, "s": 35470, "text": "subset" }, { "code": null, "e": 35484, "s": 35477, "text": "Arrays" }, { "code": null, "e": 35504, "s": 35484, "text": "Dynamic Programming" }, { "code": null, "e": 35517, "s": 35504, "text": "Mathematical" }, { "code": null, "e": 35524, "s": 35517, "text": "Arrays" }, { "code": null, "e": 35544, "s": 35524, "text": "Dynamic Programming" }, { "code": null, "e": 35557, "s": 35544, "text": "Mathematical" }, { "code": null, "e": 35564, "s": 35557, "text": "subset" }, { "code": null, "e": 35662, "s": 35564, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35693, "s": 35662, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 35731, "s": 35693, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 35756, "s": 35731, "text": "Window Sliding Technique" }, { "code": null, "e": 35777, "s": 35756, "text": "Next Greater Element" }, { "code": null, "e": 35835, "s": 35777, "text": "Find duplicates in O(n) time and O(1) extra space | Set 1" }, { "code": null, "e": 35864, "s": 35835, "text": "0-1 Knapsack Problem | DP-10" }, { "code": null, "e": 35894, "s": 35864, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 35928, "s": 35894, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 35959, "s": 35928, "text": "Bellman–Ford Algorithm | DP-23" } ]
Beautiful Sequence | Practice | GeeksforGeeks
A beautiful sequence is a strictly increasing sequence, in which the term Ai divides all Aj, where j>i. Given N find a beautiful sequence whose last term is N and the length of the sequence is the maximum possible. If there are multiple solutions return any. Example 1: Input: N = 10 Output: 1 5 10 Explanation: 10 is divisible by 1 and 5, 5 is divisible by 1. Example 2: Input: N = 3 Output: 1 3 Explanation: 3 is divisible by 1. Your Task: You don't need to read or print anything. Your task is to complete the function FindSequenece() which takes N as an input parameter and returns a list of beautiful sequences. The driver will print two space-separated integers the length of the sequence and an integer x where x = 1 if your sequence is beautiful otherwise x = 0. Expected Time Complexity: O(sqrt(N)) Expected Space Complexity: O(sqrt(N)) Constraints: 1 < N < 109 0 piyushkrs7 months ago vector<int> FindSequenece(int N) { // Code here vector<int> ans; int r=sqrt(N); /*Check if any number is factor of N, N%i==0 i.e. N/i is a factor of N close to N. Now check for factor of N/i then it will be factor of N also thats why we are changing N to N/i here.*/ for(int i=2;i<=r;i++){ while(N%i==0){ ans.push_back(N); N=N/i; } } /*We didn't start from N=1 because we will end up in an infinite loop. If number is still greater than 1 then it is prime push it as well as 1 otherwise push 1 only.*/ if(N>1) ans.push_back(N); ans.push_back(1); reverse(ans.begin(),ans.end()); return ans; } 0 Sourashis1 year ago Sourashis N should not be pushed in the vector of sequence for getting the code accepted 0 fullmetal1 year ago fullmetal test case are wrong(no need of number itself in vector)10=(1 5)3=(1) 0 Nastik2 years ago Nastik This is a Good Question with low submissions. Please only add Hints. Hint from my Side: https://cp-algorithms.com/a...This will help in getting out of TLE 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": 487, "s": 226, "text": "A beautiful sequence is a strictly increasing sequence, in which the term Ai divides all Aj, where j>i. Given N find a beautiful sequence whose last term is N and the length of the sequence is the maximum possible. If there are multiple solutions return any.\n " }, { "code": null, "e": 498, "s": 487, "text": "Example 1:" }, { "code": null, "e": 590, "s": 498, "text": "Input: N = 10\nOutput: 1 5 10\nExplanation: 10 is divisible by\n1 and 5, 5 is divisible by 1.\n" }, { "code": null, "e": 601, "s": 590, "text": "Example 2:" }, { "code": null, "e": 661, "s": 601, "text": "Input: N = 3\nOutput: 1 3\nExplanation: 3 is divisible by 1.\n" }, { "code": null, "e": 1005, "s": 663, "text": "Your Task:\nYou don't need to read or print anything. Your task is to complete the function FindSequenece() which takes N as an input parameter and returns a list of beautiful sequences. The driver will print two space-separated integers the length of the sequence and an integer x where x = 1 if your sequence is beautiful otherwise x = 0.\n " }, { "code": null, "e": 1082, "s": 1005, "text": "Expected Time Complexity: O(sqrt(N))\nExpected Space Complexity: O(sqrt(N))\n " }, { "code": null, "e": 1107, "s": 1082, "text": "Constraints:\n1 < N < 109" }, { "code": null, "e": 1109, "s": 1107, "text": "0" }, { "code": null, "e": 1131, "s": 1109, "text": "piyushkrs7 months ago" }, { "code": null, "e": 1755, "s": 1131, "text": " vector<int> FindSequenece(int N) { // Code here vector<int> ans; int r=sqrt(N); /*Check if any number is factor of N, N%i==0 i.e. N/i is a factor of N close to N. Now check for factor of N/i then it will be factor of N also thats why we are changing N to N/i here.*/ for(int i=2;i<=r;i++){ while(N%i==0){ ans.push_back(N); N=N/i; } } /*We didn't start from N=1 because we will end up in an infinite loop. If number is still greater than 1 then it is prime push it as well as 1 otherwise push 1 only.*/" }, { "code": null, "e": 1896, "s": 1755, "text": " if(N>1) ans.push_back(N); ans.push_back(1); reverse(ans.begin(),ans.end()); return ans; }" }, { "code": null, "e": 1898, "s": 1896, "text": "0" }, { "code": null, "e": 1918, "s": 1898, "text": "Sourashis1 year ago" }, { "code": null, "e": 1928, "s": 1918, "text": "Sourashis" }, { "code": null, "e": 2007, "s": 1928, "text": "N should not be pushed in the vector of sequence for getting the code accepted" }, { "code": null, "e": 2009, "s": 2007, "text": "0" }, { "code": null, "e": 2029, "s": 2009, "text": "fullmetal1 year ago" }, { "code": null, "e": 2039, "s": 2029, "text": "fullmetal" }, { "code": null, "e": 2108, "s": 2039, "text": "test case are wrong(no need of number itself in vector)10=(1 5)3=(1)" }, { "code": null, "e": 2110, "s": 2108, "text": "0" }, { "code": null, "e": 2128, "s": 2110, "text": "Nastik2 years ago" }, { "code": null, "e": 2135, "s": 2128, "text": "Nastik" }, { "code": null, "e": 2204, "s": 2135, "text": "This is a Good Question with low submissions. Please only add Hints." }, { "code": null, "e": 2290, "s": 2204, "text": "Hint from my Side: https://cp-algorithms.com/a...This will help in getting out of TLE" }, { "code": null, "e": 2436, "s": 2290, "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": 2472, "s": 2436, "text": " Login to access your submissions. " }, { "code": null, "e": 2482, "s": 2472, "text": "\nProblem\n" }, { "code": null, "e": 2492, "s": 2482, "text": "\nContest\n" }, { "code": null, "e": 2555, "s": 2492, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 2703, "s": 2555, "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": 2911, "s": 2703, "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": 3017, "s": 2911, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Check if a queue can be sorted into another queue using a stack in Python
Suppose we have a Queue with first n natural numbers (unsorted). We have to check whether the given Queue elements can be sorted in non-decreasing sequence in another Queue by using a stack. We can use following operations to solve this problem − Push or pop elements from stack Delete element from given Queue. Insert element in the other Queue. So, if the input is like Que = [6, 1, 2, 3, 4, 5], then the output will be True as we can pop 6 from Que, then push it into stack. Now pop all remaining elements from Que to another queue, then pop 6 from stack and push into the second queue, so all elements in the new queue will be sorted in non-decreasing sequence. To solve this, we will follow these steps − n := size of que stk := a new stack exp_val := 1 front := null while que is not empty, dofront := front element of queremove front element from queif front is same as exp_val, thenexp_val := exp_val + 1otherwise,if stk is empty, thenpush front into stkotherwise when stk is not empty and top of stk < front, thenreturn Falseotherwise,push front into stkwhile stk is not empty and top of stack is same as exp_val, dopop from stkexp_val := exp_val + 1 front := front element of que remove front element from que if front is same as exp_val, thenexp_val := exp_val + 1 exp_val := exp_val + 1 otherwise,if stk is empty, thenpush front into stkotherwise when stk is not empty and top of stk < front, thenreturn Falseotherwise,push front into stk if stk is empty, thenpush front into stk push front into stk otherwise when stk is not empty and top of stk < front, thenreturn False return False otherwise,push front into stk push front into stk while stk is not empty and top of stack is same as exp_val, dopop from stkexp_val := exp_val + 1 pop from stk exp_val := exp_val + 1 if exp_val - 1 is same as n and stk is empty, thenreturn True return True return False Let us see the following implementation to get better understanding − Live Demo from queue import Queue def solve(que): n = que.qsize() stk = [] exp_val = 1 front = None while (not que.empty()): front = que.queue[0] que.get() if (front == exp_val): exp_val += 1 else: if (len(stk) == 0): stk.append(front) elif (len(stk) != 0 and stk[-1] < front): return False else: stk.append(front) while (len(stk) != 0 and stk[-1] == exp_val): stk.pop() exp_val += 1 if (exp_val - 1 == n and len(stk) == 0): return True return False que = Queue() items = [6, 1, 2, 3, 4, 5] for i in items: que.put(i) print(solve(que)) [6, 1, 2, 3, 4, 5] True
[ { "code": null, "e": 1309, "s": 1062, "text": "Suppose we have a Queue with first n natural numbers (unsorted). We have to check whether the given Queue elements can be sorted in non-decreasing sequence in another Queue by using a stack. We can use following operations to solve this problem −" }, { "code": null, "e": 1341, "s": 1309, "text": "Push or pop elements from stack" }, { "code": null, "e": 1374, "s": 1341, "text": "Delete element from given Queue." }, { "code": null, "e": 1409, "s": 1374, "text": "Insert element in the other Queue." }, { "code": null, "e": 1728, "s": 1409, "text": "So, if the input is like Que = [6, 1, 2, 3, 4, 5], then the output will be True as we can pop 6 from Que, then push it into stack. Now pop all remaining elements from Que to another queue, then pop 6 from stack and push into the second queue, so all elements in the new queue will be sorted in non-decreasing sequence." }, { "code": null, "e": 1772, "s": 1728, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1789, "s": 1772, "text": "n := size of que" }, { "code": null, "e": 1808, "s": 1789, "text": "stk := a new stack" }, { "code": null, "e": 1821, "s": 1808, "text": "exp_val := 1" }, { "code": null, "e": 1835, "s": 1821, "text": "front := null" }, { "code": null, "e": 2222, "s": 1835, "text": "while que is not empty, dofront := front element of queremove front element from queif front is same as exp_val, thenexp_val := exp_val + 1otherwise,if stk is empty, thenpush front into stkotherwise when stk is not empty and top of stk < front, thenreturn Falseotherwise,push front into stkwhile stk is not empty and top of stack is same as exp_val, dopop from stkexp_val := exp_val + 1" }, { "code": null, "e": 2252, "s": 2222, "text": "front := front element of que" }, { "code": null, "e": 2282, "s": 2252, "text": "remove front element from que" }, { "code": null, "e": 2338, "s": 2282, "text": "if front is same as exp_val, thenexp_val := exp_val + 1" }, { "code": null, "e": 2361, "s": 2338, "text": "exp_val := exp_val + 1" }, { "code": null, "e": 2513, "s": 2361, "text": "otherwise,if stk is empty, thenpush front into stkotherwise when stk is not empty and top of stk < front, thenreturn Falseotherwise,push front into stk" }, { "code": null, "e": 2554, "s": 2513, "text": "if stk is empty, thenpush front into stk" }, { "code": null, "e": 2574, "s": 2554, "text": "push front into stk" }, { "code": null, "e": 2647, "s": 2574, "text": "otherwise when stk is not empty and top of stk < front, thenreturn False" }, { "code": null, "e": 2660, "s": 2647, "text": "return False" }, { "code": null, "e": 2690, "s": 2660, "text": "otherwise,push front into stk" }, { "code": null, "e": 2710, "s": 2690, "text": "push front into stk" }, { "code": null, "e": 2807, "s": 2710, "text": "while stk is not empty and top of stack is same as exp_val, dopop from stkexp_val := exp_val + 1" }, { "code": null, "e": 2820, "s": 2807, "text": "pop from stk" }, { "code": null, "e": 2843, "s": 2820, "text": "exp_val := exp_val + 1" }, { "code": null, "e": 2905, "s": 2843, "text": "if exp_val - 1 is same as n and stk is empty, thenreturn True" }, { "code": null, "e": 2917, "s": 2905, "text": "return True" }, { "code": null, "e": 2930, "s": 2917, "text": "return False" }, { "code": null, "e": 3000, "s": 2930, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 3011, "s": 3000, "text": " Live Demo" }, { "code": null, "e": 3678, "s": 3011, "text": "from queue import Queue\ndef solve(que):\n n = que.qsize()\n stk = []\n exp_val = 1\n front = None\n while (not que.empty()):\n front = que.queue[0]\n que.get()\n if (front == exp_val):\n exp_val += 1\n else:\n if (len(stk) == 0):\n stk.append(front)\n elif (len(stk) != 0 and stk[-1] < front):\n return False\n else:\n stk.append(front)\n while (len(stk) != 0 and stk[-1] == exp_val):\n stk.pop()\n exp_val += 1\n if (exp_val - 1 == n and len(stk) == 0):\n return True\n return False\nque = Queue()\nitems = [6, 1, 2, 3, 4, 5]\nfor i in items:\n que.put(i)\nprint(solve(que))" }, { "code": null, "e": 3697, "s": 3678, "text": "[6, 1, 2, 3, 4, 5]" }, { "code": null, "e": 3702, "s": 3697, "text": "True" } ]
C# | How to use Interface References - GeeksforGeeks
11 Jun, 2019 In C#, you are allowed to create a reference variable of an interface type or in other words, you are allowed to create an interface reference variable. Such kind of variable can refer to any object that implements its interface. An interface reference variable only knows that methods which are declared by its interface declaration. It does not allow accessing any other variables or methods that might be supported by the objects. This concept is similar when you use a parent class reference to access a child class object. Below are the examples to illustrate the concept of Interface References: Example 1: // C# program to illustrate the // concept of Interface Referencesusing System; // interface declarationpublic interface Race { // declaration of abstract methods of // interface that will be implemented // by the class which inherits the interface void Speed(int s); void Distance(int d);} // class implementing interfacepublic class Person1 : Race { int sp1, di1; // abstract method of // Race interface public void Speed(int p1s) { sp1 = p1s; Console.WriteLine("Speed Method implemented by Person1"); } // abstract method of // Race interface public void Distance(int p1d) { di1 = p1d; Console.WriteLine("Distance Method implemented by Person1"); } // method of class Person1 public void display1() { Console.WriteLine("The Speed of 1st person is: "+sp1); Console.WriteLine("The distance covered by 1st person is: "+di1); } } // class implementing interfacepublic class Person2 : Race { int sp2, di2; // abstract method of // Race interface public void Speed(int p2s) { sp2 = p2s; Console.WriteLine("Speed Method implemented by Person2"); } // abstract method of // Race interface public void Distance(int p2d) { di2 = p2d; Console.WriteLine("Distance Method implemented by Person2"); } // method of class Person2 public void display2() { Console.WriteLine("The Speed of 2nd person is: "+sp2); Console.WriteLine("The distance covered by 2nd person is: "+di2); } } // Driver Classpublic class GFG { // Main method public static void Main(String []args) { // creating an instance of Person1 class Person1 obj1 = new Person1(); // creating an instance of Person2 class Person2 obj2 = new Person2(); // creating an Reference // of interface Race Race r; // ----- For Person1 Class ---------- // assigning Person1 object 'obj1' // to interface Reference 'r' r = obj1; // Now you can access the abstract method // of Race interface which are implemented // by class Person1 r.Speed(10); r.Distance(50); // if you will try to call display1() // method using 'r' it will give error //r.display1(); // calling the display1() // method of Person1 Class obj1.display1(); // ----- For Person2 Class ---------- // assigning Person2 object 'obj2' // to interface Reference 'r' r = obj2; // Now you can access the abstract method // of Race interface which are implemented // by class Person2 r.Speed(15); r.Distance(45); // if you will try to call display2() // method using 'r' it will give error //r.display2(); // calling the display1() // method of Person1 Class obj2.display2(); } } Speed Method implemented by Person1 Distance Method implemented by Person1 The Speed of 1st person is: 10 The distance covered by 1st person is: 50 Speed Method implemented by Person2 Distance Method implemented by Person2 The Speed of 2nd person is: 15 The distance covered by 2nd person is: 45 Explanation: In above example, we have an interface named Race an two classes Person1 and Person2 which are implementing the methods of the interface. The Person1 class has its own method named display1() and similar Person2 class its own method display2() which cannot be called by using interface reference. In order to call the methods using interface reference(here r is interface reference), you have to assign to class object to it. Like if you are assigning Person1’s object obj1 to r i.e. r = obj1; then you call the Speed() and Distance() methods that are implemented by the Person1 class. In order to call display1() method, you must have to use obj1. Similarly using r = obj2; we are calling methods of Person2 class. Example 2: // C# program to illustrate the // concept of Interface Referencesusing System; // interface declarationinterface Vehicle { // all are the abstract methods. void changeGear(int a); void speedUp(int a); void applyBrakes(int a); void printStates();} // class implements interfaceclass Bicycle : Vehicle { int speed; int gear; // to change gear public void changeGear(int newGear) { gear = newGear; } // to increase speed public void speedUp(int increment) { speed = speed + increment; } // to decrease speed public void applyBrakes(int decrement) { speed = speed - decrement; } public void printStates() { Console.WriteLine("speed: " + speed + " gear: " + gear); }} // Driver Classclass GFG { // Main Method public static void Main(String[] args) { // creating an instance of Bicycle Bicycle bicycle = new Bicycle(); // Creating interface references Vehicle obj; // assigning Bicycle object 'bicycle' // to interface Reference 'obj' obj = bicycle; // calling the abstract methods // implemented by class Bicycle obj.changeGear(4); obj.speedUp(5); obj.applyBrakes(2); Console.WriteLine("Bicycle Present State:"); // calling the method of class Bicycle obj.printStates(); }} Bicycle Present State: speed: 3 gear: 4 Explanation: In the above example, Vehicle is an interface and Bicycle class implements this interface. Here obj is declared to be a reference to Vehicle interface in the Main() method. Now this obj is used to refer the object bicycle of the Bicycle class. nidhi_biet CSharp-Interfaces CSharp-OOP C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# Dictionary with examples C# | Delegates C# | Replace() Method Extension Method in C# C# | String.IndexOf( ) Method | Set - 1 Introduction to .NET Framework C# | Data Types C# | Arrays HashSet in C# with Examples Common Language Runtime (CLR) in C#
[ { "code": null, "e": 25541, "s": 25513, "text": "\n11 Jun, 2019" }, { "code": null, "e": 26069, "s": 25541, "text": "In C#, you are allowed to create a reference variable of an interface type or in other words, you are allowed to create an interface reference variable. Such kind of variable can refer to any object that implements its interface. An interface reference variable only knows that methods which are declared by its interface declaration. It does not allow accessing any other variables or methods that might be supported by the objects. This concept is similar when you use a parent class reference to access a child class object." }, { "code": null, "e": 26143, "s": 26069, "text": "Below are the examples to illustrate the concept of Interface References:" }, { "code": null, "e": 26154, "s": 26143, "text": "Example 1:" }, { "code": "// C# program to illustrate the // concept of Interface Referencesusing System; // interface declarationpublic interface Race { // declaration of abstract methods of // interface that will be implemented // by the class which inherits the interface void Speed(int s); void Distance(int d);} // class implementing interfacepublic class Person1 : Race { int sp1, di1; // abstract method of // Race interface public void Speed(int p1s) { sp1 = p1s; Console.WriteLine(\"Speed Method implemented by Person1\"); } // abstract method of // Race interface public void Distance(int p1d) { di1 = p1d; Console.WriteLine(\"Distance Method implemented by Person1\"); } // method of class Person1 public void display1() { Console.WriteLine(\"The Speed of 1st person is: \"+sp1); Console.WriteLine(\"The distance covered by 1st person is: \"+di1); } } // class implementing interfacepublic class Person2 : Race { int sp2, di2; // abstract method of // Race interface public void Speed(int p2s) { sp2 = p2s; Console.WriteLine(\"Speed Method implemented by Person2\"); } // abstract method of // Race interface public void Distance(int p2d) { di2 = p2d; Console.WriteLine(\"Distance Method implemented by Person2\"); } // method of class Person2 public void display2() { Console.WriteLine(\"The Speed of 2nd person is: \"+sp2); Console.WriteLine(\"The distance covered by 2nd person is: \"+di2); } } // Driver Classpublic class GFG { // Main method public static void Main(String []args) { // creating an instance of Person1 class Person1 obj1 = new Person1(); // creating an instance of Person2 class Person2 obj2 = new Person2(); // creating an Reference // of interface Race Race r; // ----- For Person1 Class ---------- // assigning Person1 object 'obj1' // to interface Reference 'r' r = obj1; // Now you can access the abstract method // of Race interface which are implemented // by class Person1 r.Speed(10); r.Distance(50); // if you will try to call display1() // method using 'r' it will give error //r.display1(); // calling the display1() // method of Person1 Class obj1.display1(); // ----- For Person2 Class ---------- // assigning Person2 object 'obj2' // to interface Reference 'r' r = obj2; // Now you can access the abstract method // of Race interface which are implemented // by class Person2 r.Speed(15); r.Distance(45); // if you will try to call display2() // method using 'r' it will give error //r.display2(); // calling the display1() // method of Person1 Class obj2.display2(); } }", "e": 29403, "s": 26154, "text": null }, { "code": null, "e": 29700, "s": 29403, "text": "Speed Method implemented by Person1\nDistance Method implemented by Person1\nThe Speed of 1st person is: 10\nThe distance covered by 1st person is: 50\nSpeed Method implemented by Person2\nDistance Method implemented by Person2\nThe Speed of 2nd person is: 15\nThe distance covered by 2nd person is: 45\n" }, { "code": null, "e": 30429, "s": 29700, "text": "Explanation: In above example, we have an interface named Race an two classes Person1 and Person2 which are implementing the methods of the interface. The Person1 class has its own method named display1() and similar Person2 class its own method display2() which cannot be called by using interface reference. In order to call the methods using interface reference(here r is interface reference), you have to assign to class object to it. Like if you are assigning Person1’s object obj1 to r i.e. r = obj1; then you call the Speed() and Distance() methods that are implemented by the Person1 class. In order to call display1() method, you must have to use obj1. Similarly using r = obj2; we are calling methods of Person2 class." }, { "code": null, "e": 30440, "s": 30429, "text": "Example 2:" }, { "code": "// C# program to illustrate the // concept of Interface Referencesusing System; // interface declarationinterface Vehicle { // all are the abstract methods. void changeGear(int a); void speedUp(int a); void applyBrakes(int a); void printStates();} // class implements interfaceclass Bicycle : Vehicle { int speed; int gear; // to change gear public void changeGear(int newGear) { gear = newGear; } // to increase speed public void speedUp(int increment) { speed = speed + increment; } // to decrease speed public void applyBrakes(int decrement) { speed = speed - decrement; } public void printStates() { Console.WriteLine(\"speed: \" + speed + \" gear: \" + gear); }} // Driver Classclass GFG { // Main Method public static void Main(String[] args) { // creating an instance of Bicycle Bicycle bicycle = new Bicycle(); // Creating interface references Vehicle obj; // assigning Bicycle object 'bicycle' // to interface Reference 'obj' obj = bicycle; // calling the abstract methods // implemented by class Bicycle obj.changeGear(4); obj.speedUp(5); obj.applyBrakes(2); Console.WriteLine(\"Bicycle Present State:\"); // calling the method of class Bicycle obj.printStates(); }}", "e": 31859, "s": 30440, "text": null }, { "code": null, "e": 31900, "s": 31859, "text": "Bicycle Present State:\nspeed: 3 gear: 4\n" }, { "code": null, "e": 32157, "s": 31900, "text": "Explanation: In the above example, Vehicle is an interface and Bicycle class implements this interface. Here obj is declared to be a reference to Vehicle interface in the Main() method. Now this obj is used to refer the object bicycle of the Bicycle class." }, { "code": null, "e": 32168, "s": 32157, "text": "nidhi_biet" }, { "code": null, "e": 32186, "s": 32168, "text": "CSharp-Interfaces" }, { "code": null, "e": 32197, "s": 32186, "text": "CSharp-OOP" }, { "code": null, "e": 32200, "s": 32197, "text": "C#" }, { "code": null, "e": 32298, "s": 32200, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32326, "s": 32298, "text": "C# Dictionary with examples" }, { "code": null, "e": 32341, "s": 32326, "text": "C# | Delegates" }, { "code": null, "e": 32363, "s": 32341, "text": "C# | Replace() Method" }, { "code": null, "e": 32386, "s": 32363, "text": "Extension Method in C#" }, { "code": null, "e": 32426, "s": 32386, "text": "C# | String.IndexOf( ) Method | Set - 1" }, { "code": null, "e": 32457, "s": 32426, "text": "Introduction to .NET Framework" }, { "code": null, "e": 32473, "s": 32457, "text": "C# | Data Types" }, { "code": null, "e": 32485, "s": 32473, "text": "C# | Arrays" }, { "code": null, "e": 32513, "s": 32485, "text": "HashSet in C# with Examples" } ]
Jackson Annotations - @JsonIgnoreType
@JsonIgnoreType is used at mark a property of special type to be ignored. import java.io.IOException; import com.fasterxml.jackson.annotation.JsonIgnoreType; import com.fasterxml.jackson.databind.ObjectMapper; public class JacksonTester { public static void main(String args[]){ ObjectMapper mapper = new ObjectMapper(); try { Student student = new Student(1,11,"1ab","Mark"); String jsonString = mapper .writerWithDefaultPrettyPrinter() .writeValueAsString(student); System.out.println(jsonString); } catch (IOException e) { e.printStackTrace(); } } } class Student { public int id; @JsonIgnore public String systemId; public int rollNo; public Name nameObj; Student(int id, int rollNo, String systemId, String name){ this.id = id; this.systemId = systemId; this.rollNo = rollNo; nameObj = new Name(name); } @JsonIgnoreType class Name { public String name; Name(String name){ this.name = name; } } } { "id" : 1, "systemId" : "1ab", "rollNo" : 11 } Print Add Notes Bookmark this page
[ { "code": null, "e": 2549, "s": 2475, "text": "@JsonIgnoreType is used at mark a property of special type to be ignored." }, { "code": null, "e": 3577, "s": 2549, "text": "import java.io.IOException;\nimport com.fasterxml.jackson.annotation.JsonIgnoreType;\nimport com.fasterxml.jackson.databind.ObjectMapper;\n\npublic class JacksonTester {\n public static void main(String args[]){\n ObjectMapper mapper = new ObjectMapper();\n try {\n Student student = new Student(1,11,\"1ab\",\"Mark\"); \n String jsonString = mapper\n .writerWithDefaultPrettyPrinter()\n .writeValueAsString(student);\n System.out.println(jsonString);\n }\n catch (IOException e) { \n e.printStackTrace();\n } \n }\n}\nclass Student { \n public int id;\n @JsonIgnore\n public String systemId;\n public int rollNo;\n public Name nameObj;\n\n Student(int id, int rollNo, String systemId, String name){\n this.id = id;\n this.systemId = systemId;\n this.rollNo = rollNo;\n nameObj = new Name(name);\n }\n\n @JsonIgnoreType\n class Name {\n public String name;\n Name(String name){\n this.name = name;\n } \n }\n}" }, { "code": null, "e": 3635, "s": 3577, "text": "{\n \"id\" : 1,\n \"systemId\" : \"1ab\",\n \"rollNo\" : 11\n}\n" }, { "code": null, "e": 3642, "s": 3635, "text": " Print" }, { "code": null, "e": 3653, "s": 3642, "text": " Add Notes" } ]
AtomicInteger incrementAndGet() method in Java with examples - GeeksforGeeks
13 Dec, 2021 The java.util.concurrent.atomic.AtomicInteger.incrementAndGet() is an inbuilt method in java that increases the previous value by one and returns the value after updation which is of data-type int. Syntax: public final int incrementAndGet() Parameters: The function does not accepts a single parameter. Return value: The function returns the value after increment operation is performed to the previous value. Program below demonstrates the function: Program 1: Java // Java program that demonstrates// the incrementAndGet() function import java.util.concurrent.atomic.AtomicInteger; public class GFG { public static void main(String args[]) { // Initially value as 0 AtomicInteger val = new AtomicInteger(0); System.out.println("Previous value: " + val); // Increment and get int res = val.incrementAndGet(); // Prints the updated value System.out.println("Current value: " + res); }} Previous value: 0 Current value: 1 Program 2: Java // Java program that demonstrates// the incrementAndGet() function import java.util.concurrent.atomic.AtomicInteger; public class GFG { public static void main(String args[]) { // Initially value as 18 AtomicInteger val = new AtomicInteger(18); System.out.println("Previous value: " + val); // Increment and get new value int res = val.incrementAndGet(); // Prints the updated value System.out.println("Current value: " + res); }} Previous value: 18 Current value: 19 Reference: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/AtomicInteger.html#incrementAndGet– surindertarika1234 Java - util package Java-AtomicInteger Java-Functions 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 Initialize an ArrayList in Java Object Oriented Programming (OOPs) Concept in Java Interfaces in Java ArrayList in Java How to iterate any Map in Java Multidimensional Arrays in Java Singleton Class in Java Stack Class in Java Multithreading in Java
[ { "code": null, "e": 24402, "s": 24374, "text": "\n13 Dec, 2021" }, { "code": null, "e": 24600, "s": 24402, "text": "The java.util.concurrent.atomic.AtomicInteger.incrementAndGet() is an inbuilt method in java that increases the previous value by one and returns the value after updation which is of data-type int." }, { "code": null, "e": 24609, "s": 24600, "text": "Syntax: " }, { "code": null, "e": 24644, "s": 24609, "text": "public final int incrementAndGet()" }, { "code": null, "e": 24814, "s": 24644, "text": "Parameters: The function does not accepts a single parameter. Return value: The function returns the value after increment operation is performed to the previous value. " }, { "code": null, "e": 24855, "s": 24814, "text": "Program below demonstrates the function:" }, { "code": null, "e": 24868, "s": 24855, "text": "Program 1: " }, { "code": null, "e": 24873, "s": 24868, "text": "Java" }, { "code": "// Java program that demonstrates// the incrementAndGet() function import java.util.concurrent.atomic.AtomicInteger; public class GFG { public static void main(String args[]) { // Initially value as 0 AtomicInteger val = new AtomicInteger(0); System.out.println(\"Previous value: \" + val); // Increment and get int res = val.incrementAndGet(); // Prints the updated value System.out.println(\"Current value: \" + res); }}", "e": 25428, "s": 24873, "text": null }, { "code": null, "e": 25463, "s": 25428, "text": "Previous value: 0\nCurrent value: 1" }, { "code": null, "e": 25477, "s": 25465, "text": "Program 2: " }, { "code": null, "e": 25482, "s": 25477, "text": "Java" }, { "code": "// Java program that demonstrates// the incrementAndGet() function import java.util.concurrent.atomic.AtomicInteger; public class GFG { public static void main(String args[]) { // Initially value as 18 AtomicInteger val = new AtomicInteger(18); System.out.println(\"Previous value: \" + val); // Increment and get new value int res = val.incrementAndGet(); // Prints the updated value System.out.println(\"Current value: \" + res); }}", "e": 26038, "s": 25482, "text": null }, { "code": null, "e": 26075, "s": 26038, "text": "Previous value: 18\nCurrent value: 19" }, { "code": null, "e": 26195, "s": 26077, "text": "Reference: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/AtomicInteger.html#incrementAndGet– " }, { "code": null, "e": 26214, "s": 26195, "text": "surindertarika1234" }, { "code": null, "e": 26234, "s": 26214, "text": "Java - util package" }, { "code": null, "e": 26253, "s": 26234, "text": "Java-AtomicInteger" }, { "code": null, "e": 26268, "s": 26253, "text": "Java-Functions" }, { "code": null, "e": 26273, "s": 26268, "text": "Java" }, { "code": null, "e": 26278, "s": 26273, "text": "Java" }, { "code": null, "e": 26376, "s": 26278, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26385, "s": 26376, "text": "Comments" }, { "code": null, "e": 26398, "s": 26385, "text": "Old Comments" }, { "code": null, "e": 26428, "s": 26398, "text": "HashMap in Java with Examples" }, { "code": null, "e": 26460, "s": 26428, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 26511, "s": 26460, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 26530, "s": 26511, "text": "Interfaces in Java" }, { "code": null, "e": 26548, "s": 26530, "text": "ArrayList in Java" }, { "code": null, "e": 26579, "s": 26548, "text": "How to iterate any Map in Java" }, { "code": null, "e": 26611, "s": 26579, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 26635, "s": 26611, "text": "Singleton Class in Java" }, { "code": null, "e": 26655, "s": 26635, "text": "Stack Class in Java" } ]
Create a Count Plot with SeaBorn – Python Pandas
Count Plot in Seaborn is used to display the counts of observations in each categorical bin using bars. The seaborn.countplot() is used for this. Let’s say the following is our dataset in the form of a CSV file − Cricketers.csv At first, import the required 3 libraries − import seaborn as sb import pandas as pd import matplotlib.pyplot as plt Load data from a CSV file into a Pandas DataFrame − dataFrame = pd.read_csv("C:\\Users\\amit_\\Desktop\\Cricketers.csv") Following is the code − import seaborn as sb import pandas as pd import matplotlib.pyplot as plt # Load data from a CSV file into a Pandas DataFrame dataFrame = pd.read_csv("C:\\Users\\amit_\\Desktop\\Cricketers.csv") # plotting count plot with Age column sb.countplot(dataFrame["Age"]) # display plt.show() This will produce the following output − Let us see another example wherein we have used the hue parameter − import seaborn as sb import pandas as pd import matplotlib.pyplot as plt # Load data from a CSV file into a Pandas DataFrame dataFrame = pd.read_csv("C:\\Users\\amit_\\Desktop\\Cricketers.csv") # plotting count plot with Role column and hue as Academy sb.countplot( x= "Role", hue="Academy", data=dataFrame) # display plt.show() This will produce the following output −
[ { "code": null, "e": 1208, "s": 1062, "text": "Count Plot in Seaborn is used to display the counts of observations in each categorical bin using bars. The seaborn.countplot() is used for this." }, { "code": null, "e": 1290, "s": 1208, "text": "Let’s say the following is our dataset in the form of a CSV file − Cricketers.csv" }, { "code": null, "e": 1334, "s": 1290, "text": "At first, import the required 3 libraries −" }, { "code": null, "e": 1407, "s": 1334, "text": "import seaborn as sb\nimport pandas as pd\nimport matplotlib.pyplot as plt" }, { "code": null, "e": 1459, "s": 1407, "text": "Load data from a CSV file into a Pandas DataFrame −" }, { "code": null, "e": 1529, "s": 1459, "text": "dataFrame = pd.read_csv(\"C:\\\\Users\\\\amit_\\\\Desktop\\\\Cricketers.csv\")\n" }, { "code": null, "e": 1553, "s": 1529, "text": "Following is the code −" }, { "code": null, "e": 1840, "s": 1553, "text": "import seaborn as sb\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n# Load data from a CSV file into a Pandas DataFrame\ndataFrame = pd.read_csv(\"C:\\\\Users\\\\amit_\\\\Desktop\\\\Cricketers.csv\")\n\n# plotting count plot with Age column\nsb.countplot(dataFrame[\"Age\"])\n\n# display\nplt.show()" }, { "code": null, "e": 1881, "s": 1840, "text": "This will produce the following output −" }, { "code": null, "e": 1949, "s": 1881, "text": "Let us see another example wherein we have used the hue parameter −" }, { "code": null, "e": 2281, "s": 1949, "text": "import seaborn as sb\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n# Load data from a CSV file into a Pandas DataFrame\ndataFrame = pd.read_csv(\"C:\\\\Users\\\\amit_\\\\Desktop\\\\Cricketers.csv\")\n\n# plotting count plot with Role column and hue as Academy\nsb.countplot( x= \"Role\", hue=\"Academy\", data=dataFrame)\n\n# display\nplt.show()" }, { "code": null, "e": 2322, "s": 2281, "text": "This will produce the following output −" } ]
Set the coordinates of the area in an image map in HTML?
Use the cords attribute in HTML to set the coordinates of the area in an image map in HTML. You can try to run the following code to implement the cords attribute − <!DOCTYPE html> <html> <head> <title>HTML coords attribute</title> </head> <body> <img src = "/images/html.gif" alt = "HTML Map" border = "0" usemap = "#html"/> <map name = "html"> <area shape = "circle" coords = "154,150,59" href = "about/about_team.htm" alt = "Team" target = "_self" /> </map> </body> </html>
[ { "code": null, "e": 1154, "s": 1062, "text": "Use the cords attribute in HTML to set the coordinates of the area in an image map in HTML." }, { "code": null, "e": 1227, "s": 1154, "text": "You can try to run the following code to implement the cords attribute −" }, { "code": null, "e": 1596, "s": 1227, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>HTML coords attribute</title>\n </head>\n <body>\n <img src = \"/images/html.gif\" alt = \"HTML Map\" border = \"0\" usemap = \"#html\"/>\n <map name = \"html\">\n <area shape = \"circle\" coords = \"154,150,59\" href = \"about/about_team.htm\"\n alt = \"Team\" target = \"_self\" />\n </map>\n </body>\n</html>" } ]
How to Replace Null Values in Spark DataFrames | Towards Data Science
The replacement of null values in PySpark DataFrames is one of the most common operations undertaken. This can be achieved by using either DataFrame.fillna() or DataFrameNaFunctions.fill() methods. In today’s article we are going to discuss the main difference between these two functions. While working with Spark DataFrames, many operations that we typically perform over them may return null values in some of the records. From that point onwards, some other operations may result in error if null/empty values are observed and thus we have to somehow replace these values in order to keep processing a DataFrame. Additionally, when reporting tables (e.g. when outputting them into csv files) it is quite common to avoid the inclusion of empty values. For instance if an operation that was executed to create counts returns null values, it is more elegant to replace these values with 0. Before start discussing how to replace null values in PySpark and exploring the difference between fill() and fillNa(), let’s create a sample DataFrame that will use as a reference throughout the article. from pyspark.sql import SparkSessionspark_session = SparkSession.builder \ .master('local[1]') \ .appName('Example') \ .getOrCreate()df = spark_session.createDataFrame( [ (1, 'UK', 'London', None), (2, 'US', 'New York', 8000000), (3, 'US', 'Washington DC', None), (4, 'UK', 'Manchester', 550000), ], ['id', 'country', 'city', 'population'])df.show()+---+---------+--------------+-----------+| id| country| city | population|+---+---------+--------------+-----------+| 1| UK| London| null|| 2| US| New York| 8000000|| 3| US| Washington DC| null|| 4| UK| Manchester| 550000|+---+---------+--------------+-----------+ pyspark.sql.DataFrame.fillna() function was introduced in Spark version 1.3.1 and is used to replace null values with another specified value. It accepts two parameters namely value and subset. value corresponds to the desired value you want to replace nulls with. If the value is a dict object then it should be a mapping where keys correspond to column names and values to replacement values that must be int, float, bool or str. subset corresponds to a list of column names that will be considered when replacing null values. If value parameter is a dict then this parameter will be ignored. Now if we want to replace all null values in a DataFrame we can do so by simply providing only the value parameter: df.na.fill(value=0).show()#Replace Replace 0 for null on only population column df.na.fill(value=0,subset=["population"]).show() df.fillna(value=0).show()+---+---------+--------------+-----------+| id| country| city | population|+---+---------+--------------+-----------+| 1| UK| London| 0|| 2| US| New York| 8000000|| 3| US| Washington DC| 0|| 4| UK| Manchester| 550000|+---+---------+--------------+-----------+ The above operation will replace all null values in integer columns with the value of 0. We can even specify the column name explicitly using the subset parameter: df.fillna(value=0, subset=['population']).show()+---+---------+--------------+-----------+| id| country| city | population|+---+---------+--------------+-----------+| 1| UK| London| 0|| 2| US| New York| 8000000|| 3| US| Washington DC| 0|| 4| UK| Manchester| 550000|+---+---------+--------------+-----------+ Now pyspark.sql.DataFrameNaFunctions.fill() (which again was introduced back in version 1.3.1) is an alias to pyspark.sql.DataFrame.fillna() and both of the methods will lead to the exact same result. As we can see below the results with na.fill() are identical to those observed when pyspark.sql.DataFrame.fillna() was applied to the DataFrames. df.na.fill(value=0).show()+---+---------+--------------+-----------+| id| country| city | population|+---+---------+--------------+-----------+| 1| UK| London| 0|| 2| US| New York| 8000000|| 3| US| Washington DC| 0|| 4| UK| Manchester| 550000|+---+---------+--------------+-----------+ The above operation will replace all null values in integer columns with the value of 0. Similarly, we can explicitly specify the column name using the subset parameter: df.na.fill(value=0, subset=['population']).show()+---+---------+--------------+-----------+| id| country| city | population|+---+---------+--------------+-----------+| 1| UK| London| 0|| 2| US| New York| 8000000|| 3| US| Washington DC| 0|| 4| UK| Manchester| 550000|+---+---------+--------------+-----------+ In today’s article we discussed why it is sometimes important to replace null values in a Spark DataFrame. Additionally, we discussed how to use fillna() and fill() in order to do so which are essentially alias to each other. You can find more Spark related articles below.
[ { "code": null, "e": 462, "s": 172, "text": "The replacement of null values in PySpark DataFrames is one of the most common operations undertaken. This can be achieved by using either DataFrame.fillna() or DataFrameNaFunctions.fill() methods. In today’s article we are going to discuss the main difference between these two functions." }, { "code": null, "e": 789, "s": 462, "text": "While working with Spark DataFrames, many operations that we typically perform over them may return null values in some of the records. From that point onwards, some other operations may result in error if null/empty values are observed and thus we have to somehow replace these values in order to keep processing a DataFrame." }, { "code": null, "e": 1063, "s": 789, "text": "Additionally, when reporting tables (e.g. when outputting them into csv files) it is quite common to avoid the inclusion of empty values. For instance if an operation that was executed to create counts returns null values, it is more elegant to replace these values with 0." }, { "code": null, "e": 1268, "s": 1063, "text": "Before start discussing how to replace null values in PySpark and exploring the difference between fill() and fillNa(), let’s create a sample DataFrame that will use as a reference throughout the article." }, { "code": null, "e": 1996, "s": 1268, "text": "from pyspark.sql import SparkSessionspark_session = SparkSession.builder \\ .master('local[1]') \\ .appName('Example') \\ .getOrCreate()df = spark_session.createDataFrame( [ (1, 'UK', 'London', None), (2, 'US', 'New York', 8000000), (3, 'US', 'Washington DC', None), (4, 'UK', 'Manchester', 550000), ], ['id', 'country', 'city', 'population'])df.show()+---+---------+--------------+-----------+| id| country| city | population|+---+---------+--------------+-----------+| 1| UK| London| null|| 2| US| New York| 8000000|| 3| US| Washington DC| null|| 4| UK| Manchester| 550000|+---+---------+--------------+-----------+" }, { "code": null, "e": 2190, "s": 1996, "text": "pyspark.sql.DataFrame.fillna() function was introduced in Spark version 1.3.1 and is used to replace null values with another specified value. It accepts two parameters namely value and subset." }, { "code": null, "e": 2428, "s": 2190, "text": "value corresponds to the desired value you want to replace nulls with. If the value is a dict object then it should be a mapping where keys correspond to column names and values to replacement values that must be int, float, bool or str." }, { "code": null, "e": 2591, "s": 2428, "text": "subset corresponds to a list of column names that will be considered when replacing null values. If value parameter is a dict then this parameter will be ignored." }, { "code": null, "e": 2836, "s": 2591, "text": "Now if we want to replace all null values in a DataFrame we can do so by simply providing only the value parameter: df.na.fill(value=0).show()#Replace Replace 0 for null on only population column df.na.fill(value=0,subset=[\"population\"]).show()" }, { "code": null, "e": 3198, "s": 2836, "text": "df.fillna(value=0).show()+---+---------+--------------+-----------+| id| country| city | population|+---+---------+--------------+-----------+| 1| UK| London| 0|| 2| US| New York| 8000000|| 3| US| Washington DC| 0|| 4| UK| Manchester| 550000|+---+---------+--------------+-----------+" }, { "code": null, "e": 3287, "s": 3198, "text": "The above operation will replace all null values in integer columns with the value of 0." }, { "code": null, "e": 3362, "s": 3287, "text": "We can even specify the column name explicitly using the subset parameter:" }, { "code": null, "e": 3747, "s": 3362, "text": "df.fillna(value=0, subset=['population']).show()+---+---------+--------------+-----------+| id| country| city | population|+---+---------+--------------+-----------+| 1| UK| London| 0|| 2| US| New York| 8000000|| 3| US| Washington DC| 0|| 4| UK| Manchester| 550000|+---+---------+--------------+-----------+" }, { "code": null, "e": 3948, "s": 3747, "text": "Now pyspark.sql.DataFrameNaFunctions.fill() (which again was introduced back in version 1.3.1) is an alias to pyspark.sql.DataFrame.fillna() and both of the methods will lead to the exact same result." }, { "code": null, "e": 4094, "s": 3948, "text": "As we can see below the results with na.fill() are identical to those observed when pyspark.sql.DataFrame.fillna() was applied to the DataFrames." }, { "code": null, "e": 4457, "s": 4094, "text": "df.na.fill(value=0).show()+---+---------+--------------+-----------+| id| country| city | population|+---+---------+--------------+-----------+| 1| UK| London| 0|| 2| US| New York| 8000000|| 3| US| Washington DC| 0|| 4| UK| Manchester| 550000|+---+---------+--------------+-----------+" }, { "code": null, "e": 4627, "s": 4457, "text": "The above operation will replace all null values in integer columns with the value of 0. Similarly, we can explicitly specify the column name using the subset parameter:" }, { "code": null, "e": 5013, "s": 4627, "text": "df.na.fill(value=0, subset=['population']).show()+---+---------+--------------+-----------+| id| country| city | population|+---+---------+--------------+-----------+| 1| UK| London| 0|| 2| US| New York| 8000000|| 3| US| Washington DC| 0|| 4| UK| Manchester| 550000|+---+---------+--------------+-----------+" }, { "code": null, "e": 5239, "s": 5013, "text": "In today’s article we discussed why it is sometimes important to replace null values in a Spark DataFrame. Additionally, we discussed how to use fillna() and fill() in order to do so which are essentially alias to each other." } ]
Tryit Editor v3.7
Tryit: Using the animation-timing-function property
[]
Image Segmentation using Python’s scikit-image module. | by Parul Pandey | Towards Data Science
Sooner or later all things are numbers, including images. People who have seen The Terminator would definitely agree that it was the greatest sci-fi movie of that era. In the movie, James Cameron introduced an interesting visual effect concept that made it possible for the viewers to get behind the eyes of the cyborg called Terminator. This effect came to be known as the Terminator Vision and in a way, it segmented humans from the background. It might have sounded totally out of place then, but Image segmentation forms a vital part of many Image processing techniques today. We all are pretty aware of the endless possibilities offered by Photoshop or similar graphics editors that take a person from one image and place them into another. However, the first step of doing this is identifying where that person is in the source image and this is where Image Segmentation comes into play. There are many libraries written for Image Analysis purposes. In this article, we will be discussing in detail about scikit-image, a Python-based image processing library. The entire code can also be accessed from the Github Repository associated with this article. Scikit-image is a Python package dedicated to image processing. scikit-image can be installed as follows: pip install scikit-image# For Conda-based distributionsconda install -c conda-forge scikit-image Before proceeding with the technicalities of Image Segmentation, it is essential to get a little familiar with the scikit image ecosystem and how it handles images. Importing a GrayScale Image from the skimage library The skimage data module contains some inbuilt example data sets which are generally stored in jpeg or png format. from skimage import dataimport numpy as npimport matplotlib.pyplot as pltimage = data.binary_blobs()plt.imshow(image, cmap='gray') Importing a Colored Image from the skimage library from skimage import dataimport numpy as npimport matplotlib.pyplot as pltimage = data.astronaut()plt.imshow(image) Importing an image from an external source # The I/O module is used for importing the imagefrom skimage import dataimport numpy as npimport matplotlib.pyplot as pltfrom skimage import ioimage = io.imread('skimage_logo.png')plt.imshow(image); Loading multiple images images = io.ImageCollection('../images/*.png:../images/*.jpg')print('Type:', type(images))images.filesOut[]: Type: <class ‘skimage.io.collection.ImageCollection’> Saving images #Saving file as ‘logo.png’io.imsave('logo.png', logo) Now that we have an idea about scikit-image, let us get into details of Image Segmentation. Image Segmentation is essentially the process of partitioning a digital image into multiple segments to simplify and/or change the representation of an image into something that is more meaningful and easier to analyze. In this article, we will approach the Segmentation process as a combination of Supervised and Unsupervised algorithms. Supervised segmentation: Some prior knowledge, possibly from human input, is used to guide the algorithm. Unsupervised segmentation: No prior knowledge is required. These algorithms attempt to subdivide images into meaningful regions automatically. The user may still be able to tweak certain settings to obtain desired outputs. Let’s begin with the simplest algorithm called Thresholding. It is the simplest way to segment objects from background by choosing pixels above or below a certain threshold. This is generally helpful when we intend to segment objects from their background. You can read more about thresholding here. Let’s try this on an image of a textbook that comes preloaded with the scikit-image dataset. import numpy as npimport matplotlib.pyplot as pltimport skimage.data as dataimport skimage.segmentation as segimport skimage.filters as filtersimport skimage.draw as drawimport skimage.color as color A simple function to plot the images def image_show(image, nrows=1, ncols=1, cmap='gray'): fig, ax = plt.subplots(nrows=nrows, ncols=ncols, figsize=(14, 14)) ax.imshow(image, cmap='gray') ax.axis('off') return fig, ax text = data.page()image_show(text) This image is a little darker but maybe we can still pick a value that will give us a reasonable segmentation without any advanced algorithms. Now to help us in picking that value, we will use a Histogram. A histogram is a graph showing the number of pixels in an image at different intensity values found in that image. Simply put, a histogram is a graph wherein the x-axis shows all the values that are in the image while the y-axis shows the frequency of those values. fig, ax = plt.subplots(1, 1)ax.hist(text.ravel(), bins=32, range=[0, 256])ax.set_xlim(0, 256); Our example happens to be an 8-bit image so we have a total of 256 possible values on the x-axis. We observe that there is a concentration of pixels that are fairly light(0: black, 255: white). That’s most likely our fairly light text background but then the rest of it is kind of smeared out. An ideal segmentation histogram would be bimodal and fairly separated so that we could pick a number right in the middle. Now, let’s just try and make a few segmented images based on simple thresholding. Since we will be choosing the thresholding value ourselves, we call it supervised thresholding. text_segmented = text > (value concluded from histogram i.e 50,70,120 )image_show(text_segmented); We didn’t get any ideal results since the shadow on the left creates problems. Let’s try with unsupervised thresholding now. Scikit-image has a number of automatic thresholding methods, which require no input in choosing an optimal threshold. Some of the methods are : otsu, li, local. text_threshold = filters.threshold_ # Hit tab with the cursor after the underscore to get all the methods.image_show(text < text_threshold); In the case of local, we also need to specify the block_size . Offset helps to tune the image for better results. text_threshold = filters.threshold_local(text,block_size=51, offset=10) image_show(text > text_threshold); This is pretty good and has got rid of the noisy regions to a large extent. Thresholding is a very basic segmentation process and will not work properly in a high-contrast image for which we will be needing more advanced tools. For this section, we will use an example image that is freely available and attempt to segment the head portion using supervised segmentation techniques. # import the imagefrom skimage import ioimage = io.imread('girl.jpg') plt.imshow(image); Before doing any segmentation on an image, it is a good idea to de-noise it using some filters. However, in our case, the image is not very noisy, so we will take it as it is. Next step would be to convert the image to grayscale with rgb2gray. image_gray = color.rgb2gray(image) image_show(image_gray); We will use two segmentation methods that work on entirely different principles. Active Contour segmentation also called snakes and is initialized using a user-defined contour or line, around the area of interest, and this contour then slowly contracts and is attracted or repelled from light and edges. For our example image, let’s draw a circle around the person’s head to initialize the snake. def circle_points(resolution, center, radius): """ Generate points which define a circle on an image.Centre refers to the centre of the circle """ radians = np.linspace(0, 2*np.pi, resolution) c = center[1] + radius*np.cos(radians)#polar co-ordinates r = center[0] + radius*np.sin(radians) return np.array([c, r]).T# Exclude last point because a closed path should not have duplicate pointspoints = circle_points(200, [80, 250], 80)[:-1] The above calculations calculate x and y co-ordinates of the points on the periphery of the circle. Since we have given the resolution to be 200, it will calculate 200 such points. fig, ax = image_show(image)ax.plot(points[:, 0], points[:, 1], '--r', lw=3) The algorithm then segments the face of a person from the rest of an image by fitting a closed curve to the edges of the face. snake = seg.active_contour(image_gray, points)fig, ax = image_show(image)ax.plot(points[:, 0], points[:, 1], '--r', lw=3)ax.plot(snake[:, 0], snake[:, 1], '-b', lw=3); We can tweak the parameters called alpha and beta. Higher values of alpha will make this snake contract faster while beta makes the snake smoother. snake = seg.active_contour(image_gray, points,alpha=0.06,beta=0.3)fig, ax = image_show(image)ax.plot(points[:, 0], points[:, 1], '--r', lw=3)ax.plot(snake[:, 0], snake[:, 1], '-b', lw=3); In this method, a user interactively labels a small number of pixels which are known as labels. Each unlabeled pixel is then imagined to release a random walker and one can then determine the probability of a random walker starting at each unlabeled pixel and reaching one of the prelabeled pixels. By assigning each pixel to the label for which the greatest probability is calculated, high-quality image segmentation may be obtained. Read the Reference paper here. We will re-use the seed values from our previous example here. We could havedone different initializations but for simplicity let’s stick to circles. image_labels = np.zeros(image_gray.shape, dtype=np.uint8) The random walker algorithm expects a label image as input. So we will have the bigger circle that encompasses the person’s entire face and another smaller circle near the middle of the face. indices = draw.circle_perimeter(80, 250,20)#from hereimage_labels[indices] = 1image_labels[points[:, 1].astype(np.int), points[:, 0].astype(np.int)] = 2image_show(image_labels); Now, let’s use Random Walker and see what happens. image_segmented = seg.random_walker(image_gray, image_labels)# Check our resultsfig, ax = image_show(image_gray)ax.imshow(image_segmented == 1, alpha=0.3); It doesn’t look like it’s grabbing edges as we wanted. To resolve this situation we can tune in the beta parameter until we get the desired results. After several attempts, a value of 3000 works reasonably well. image_segmented = seg.random_walker(image_gray, image_labels, beta = 3000)# Check our resultsfig, ax = image_show(image_gray)ax.imshow(image_segmented == 1, alpha=0.3); That’s all for Supervised Segmentation where we had to provide certain inputs and also had to tweak certain parameters. However, it is not always possible to have a human looking at an image and then deciding what inputs to give or where to start from. Fortunately, for those situations, we have Unsupervised segmentation techniques. Unsupervised segmentation requires no prior knowledge. Consider an image that is so large that it is not feasible to consider all pixels simultaneously. So in such cases, Unsupervised segmentation can breakdown the image into several sub-regions, so instead of millions of pixels, you have tens to hundreds of regions. Let’s look at two such algorithms: SLIC algorithm actually uses a machine-learning algorithm called K-Means under the hood. It takes in all the pixel values of the image and tries to separate them out into the given number of sub-regions. Read the Reference Paper here. SLIC works in color so we will use the original image. image_slic = seg.slic(image,n_segments=155) All we’re doing is just setting each sub-image or sub-region that we have found, to the average of that region which makes it look less like a patchwork of randomly assigned colors and more like an image that has been decomposed into areas that are kind of similar. # label2rgb replaces each discrete label with the average interior colorimage_show(color.label2rgb(image_slic, image, kind='avg')); We’ve reduced this image from 512*512 = 262,000 pixels down to 155 regions. This algorithm also uses a machine-learning algorithm called minimum-spanning tree clustering under the hood. Felzenszwaib doesn’t tell us the exact number of clusters that the image will be partitioned into. It’s going to run and generate as many clusters as it thinks is appropriate for thatgiven scale or zoom factor on the image. The Reference Paper can be accessed here. image_felzenszwalb = seg.felzenszwalb(image) image_show(image_felzenszwalb); These are a lot of regions. Let’s calculate the number of unique regions. np.unique(image_felzenszwalb).size3368 Now let’s recolor them using the region average just as we did in the SLIC algorithm. image_felzenszwalb_colored = color.label2rgb(image_felzenszwalb, image, kind='avg')image_show(image_felzenszwalb_colored); Now we get reasonably smaller regions. If we wanted still fewer regions, we could change the scale parameter or start here and combine them. This approach is sometimes called over-segmentation. This almost looks more like a posterized image which is essentially just a reduction in the number of colors. To combine them again, you can use the Region Adjacency Graph(RAG) but that’s beyond the scope of this article. Till now, we went over image segmentation techniques using only the scikit image module. However, it will be worth mentioning some of the image segmentation techniques which use deep learning. Here is a wonderful blog post that focuses on image segmentation architectures, Losses, Datasets, and Frameworks that you can use for your image segmentation projects. neptune.ai Image segmentation is a very important image processing step. It is an active area of research with applications ranging from computer vision to medical imagery to traffic and video surveillance. Python provides a robust library in the form of scikit-image having a large number of algorithms for image processing. It is available free of charge and free of restriction having an active community behind it. Have a look at their documentation to learn more about the library and its use cases. References: Scikit image documentation
[ { "code": null, "e": 230, "s": 172, "text": "Sooner or later all things are numbers, including images." }, { "code": null, "e": 753, "s": 230, "text": "People who have seen The Terminator would definitely agree that it was the greatest sci-fi movie of that era. In the movie, James Cameron introduced an interesting visual effect concept that made it possible for the viewers to get behind the eyes of the cyborg called Terminator. This effect came to be known as the Terminator Vision and in a way, it segmented humans from the background. It might have sounded totally out of place then, but Image segmentation forms a vital part of many Image processing techniques today." }, { "code": null, "e": 1238, "s": 753, "text": "We all are pretty aware of the endless possibilities offered by Photoshop or similar graphics editors that take a person from one image and place them into another. However, the first step of doing this is identifying where that person is in the source image and this is where Image Segmentation comes into play. There are many libraries written for Image Analysis purposes. In this article, we will be discussing in detail about scikit-image, a Python-based image processing library." }, { "code": null, "e": 1332, "s": 1238, "text": "The entire code can also be accessed from the Github Repository associated with this article." }, { "code": null, "e": 1396, "s": 1332, "text": "Scikit-image is a Python package dedicated to image processing." }, { "code": null, "e": 1438, "s": 1396, "text": "scikit-image can be installed as follows:" }, { "code": null, "e": 1535, "s": 1438, "text": "pip install scikit-image# For Conda-based distributionsconda install -c conda-forge scikit-image" }, { "code": null, "e": 1700, "s": 1535, "text": "Before proceeding with the technicalities of Image Segmentation, it is essential to get a little familiar with the scikit image ecosystem and how it handles images." }, { "code": null, "e": 1753, "s": 1700, "text": "Importing a GrayScale Image from the skimage library" }, { "code": null, "e": 1867, "s": 1753, "text": "The skimage data module contains some inbuilt example data sets which are generally stored in jpeg or png format." }, { "code": null, "e": 1998, "s": 1867, "text": "from skimage import dataimport numpy as npimport matplotlib.pyplot as pltimage = data.binary_blobs()plt.imshow(image, cmap='gray')" }, { "code": null, "e": 2049, "s": 1998, "text": "Importing a Colored Image from the skimage library" }, { "code": null, "e": 2164, "s": 2049, "text": "from skimage import dataimport numpy as npimport matplotlib.pyplot as pltimage = data.astronaut()plt.imshow(image)" }, { "code": null, "e": 2207, "s": 2164, "text": "Importing an image from an external source" }, { "code": null, "e": 2406, "s": 2207, "text": "# The I/O module is used for importing the imagefrom skimage import dataimport numpy as npimport matplotlib.pyplot as pltfrom skimage import ioimage = io.imread('skimage_logo.png')plt.imshow(image);" }, { "code": null, "e": 2430, "s": 2406, "text": "Loading multiple images" }, { "code": null, "e": 2593, "s": 2430, "text": "images = io.ImageCollection('../images/*.png:../images/*.jpg')print('Type:', type(images))images.filesOut[]: Type: <class ‘skimage.io.collection.ImageCollection’>" }, { "code": null, "e": 2607, "s": 2593, "text": "Saving images" }, { "code": null, "e": 2661, "s": 2607, "text": "#Saving file as ‘logo.png’io.imsave('logo.png', logo)" }, { "code": null, "e": 2973, "s": 2661, "text": "Now that we have an idea about scikit-image, let us get into details of Image Segmentation. Image Segmentation is essentially the process of partitioning a digital image into multiple segments to simplify and/or change the representation of an image into something that is more meaningful and easier to analyze." }, { "code": null, "e": 3092, "s": 2973, "text": "In this article, we will approach the Segmentation process as a combination of Supervised and Unsupervised algorithms." }, { "code": null, "e": 3198, "s": 3092, "text": "Supervised segmentation: Some prior knowledge, possibly from human input, is used to guide the algorithm." }, { "code": null, "e": 3421, "s": 3198, "text": "Unsupervised segmentation: No prior knowledge is required. These algorithms attempt to subdivide images into meaningful regions automatically. The user may still be able to tweak certain settings to obtain desired outputs." }, { "code": null, "e": 3482, "s": 3421, "text": "Let’s begin with the simplest algorithm called Thresholding." }, { "code": null, "e": 3721, "s": 3482, "text": "It is the simplest way to segment objects from background by choosing pixels above or below a certain threshold. This is generally helpful when we intend to segment objects from their background. You can read more about thresholding here." }, { "code": null, "e": 3814, "s": 3721, "text": "Let’s try this on an image of a textbook that comes preloaded with the scikit-image dataset." }, { "code": null, "e": 4014, "s": 3814, "text": "import numpy as npimport matplotlib.pyplot as pltimport skimage.data as dataimport skimage.segmentation as segimport skimage.filters as filtersimport skimage.draw as drawimport skimage.color as color" }, { "code": null, "e": 4051, "s": 4014, "text": "A simple function to plot the images" }, { "code": null, "e": 4244, "s": 4051, "text": "def image_show(image, nrows=1, ncols=1, cmap='gray'): fig, ax = plt.subplots(nrows=nrows, ncols=ncols, figsize=(14, 14)) ax.imshow(image, cmap='gray') ax.axis('off') return fig, ax" }, { "code": null, "e": 4279, "s": 4244, "text": "text = data.page()image_show(text)" }, { "code": null, "e": 4485, "s": 4279, "text": "This image is a little darker but maybe we can still pick a value that will give us a reasonable segmentation without any advanced algorithms. Now to help us in picking that value, we will use a Histogram." }, { "code": null, "e": 4751, "s": 4485, "text": "A histogram is a graph showing the number of pixels in an image at different intensity values found in that image. Simply put, a histogram is a graph wherein the x-axis shows all the values that are in the image while the y-axis shows the frequency of those values." }, { "code": null, "e": 4846, "s": 4751, "text": "fig, ax = plt.subplots(1, 1)ax.hist(text.ravel(), bins=32, range=[0, 256])ax.set_xlim(0, 256);" }, { "code": null, "e": 5344, "s": 4846, "text": "Our example happens to be an 8-bit image so we have a total of 256 possible values on the x-axis. We observe that there is a concentration of pixels that are fairly light(0: black, 255: white). That’s most likely our fairly light text background but then the rest of it is kind of smeared out. An ideal segmentation histogram would be bimodal and fairly separated so that we could pick a number right in the middle. Now, let’s just try and make a few segmented images based on simple thresholding." }, { "code": null, "e": 5440, "s": 5344, "text": "Since we will be choosing the thresholding value ourselves, we call it supervised thresholding." }, { "code": null, "e": 5539, "s": 5440, "text": "text_segmented = text > (value concluded from histogram i.e 50,70,120 )image_show(text_segmented);" }, { "code": null, "e": 5664, "s": 5539, "text": "We didn’t get any ideal results since the shadow on the left creates problems. Let’s try with unsupervised thresholding now." }, { "code": null, "e": 5825, "s": 5664, "text": "Scikit-image has a number of automatic thresholding methods, which require no input in choosing an optimal threshold. Some of the methods are : otsu, li, local." }, { "code": null, "e": 5967, "s": 5825, "text": "text_threshold = filters.threshold_ # Hit tab with the cursor after the underscore to get all the methods.image_show(text < text_threshold);" }, { "code": null, "e": 6081, "s": 5967, "text": "In the case of local, we also need to specify the block_size . Offset helps to tune the image for better results." }, { "code": null, "e": 6188, "s": 6081, "text": "text_threshold = filters.threshold_local(text,block_size=51, offset=10) image_show(text > text_threshold);" }, { "code": null, "e": 6264, "s": 6188, "text": "This is pretty good and has got rid of the noisy regions to a large extent." }, { "code": null, "e": 6416, "s": 6264, "text": "Thresholding is a very basic segmentation process and will not work properly in a high-contrast image for which we will be needing more advanced tools." }, { "code": null, "e": 6570, "s": 6416, "text": "For this section, we will use an example image that is freely available and attempt to segment the head portion using supervised segmentation techniques." }, { "code": null, "e": 6659, "s": 6570, "text": "# import the imagefrom skimage import ioimage = io.imread('girl.jpg') plt.imshow(image);" }, { "code": null, "e": 6755, "s": 6659, "text": "Before doing any segmentation on an image, it is a good idea to de-noise it using some filters." }, { "code": null, "e": 6903, "s": 6755, "text": "However, in our case, the image is not very noisy, so we will take it as it is. Next step would be to convert the image to grayscale with rgb2gray." }, { "code": null, "e": 6962, "s": 6903, "text": "image_gray = color.rgb2gray(image) image_show(image_gray);" }, { "code": null, "e": 7043, "s": 6962, "text": "We will use two segmentation methods that work on entirely different principles." }, { "code": null, "e": 7266, "s": 7043, "text": "Active Contour segmentation also called snakes and is initialized using a user-defined contour or line, around the area of interest, and this contour then slowly contracts and is attracted or repelled from light and edges." }, { "code": null, "e": 7359, "s": 7266, "text": "For our example image, let’s draw a circle around the person’s head to initialize the snake." }, { "code": null, "e": 7825, "s": 7359, "text": "def circle_points(resolution, center, radius): \"\"\" Generate points which define a circle on an image.Centre refers to the centre of the circle \"\"\" radians = np.linspace(0, 2*np.pi, resolution) c = center[1] + radius*np.cos(radians)#polar co-ordinates r = center[0] + radius*np.sin(radians) return np.array([c, r]).T# Exclude last point because a closed path should not have duplicate pointspoints = circle_points(200, [80, 250], 80)[:-1]" }, { "code": null, "e": 8006, "s": 7825, "text": "The above calculations calculate x and y co-ordinates of the points on the periphery of the circle. Since we have given the resolution to be 200, it will calculate 200 such points." }, { "code": null, "e": 8082, "s": 8006, "text": "fig, ax = image_show(image)ax.plot(points[:, 0], points[:, 1], '--r', lw=3)" }, { "code": null, "e": 8209, "s": 8082, "text": "The algorithm then segments the face of a person from the rest of an image by fitting a closed curve to the edges of the face." }, { "code": null, "e": 8377, "s": 8209, "text": "snake = seg.active_contour(image_gray, points)fig, ax = image_show(image)ax.plot(points[:, 0], points[:, 1], '--r', lw=3)ax.plot(snake[:, 0], snake[:, 1], '-b', lw=3);" }, { "code": null, "e": 8525, "s": 8377, "text": "We can tweak the parameters called alpha and beta. Higher values of alpha will make this snake contract faster while beta makes the snake smoother." }, { "code": null, "e": 8713, "s": 8525, "text": "snake = seg.active_contour(image_gray, points,alpha=0.06,beta=0.3)fig, ax = image_show(image)ax.plot(points[:, 0], points[:, 1], '--r', lw=3)ax.plot(snake[:, 0], snake[:, 1], '-b', lw=3);" }, { "code": null, "e": 9179, "s": 8713, "text": "In this method, a user interactively labels a small number of pixels which are known as labels. Each unlabeled pixel is then imagined to release a random walker and one can then determine the probability of a random walker starting at each unlabeled pixel and reaching one of the prelabeled pixels. By assigning each pixel to the label for which the greatest probability is calculated, high-quality image segmentation may be obtained. Read the Reference paper here." }, { "code": null, "e": 9329, "s": 9179, "text": "We will re-use the seed values from our previous example here. We could havedone different initializations but for simplicity let’s stick to circles." }, { "code": null, "e": 9387, "s": 9329, "text": "image_labels = np.zeros(image_gray.shape, dtype=np.uint8)" }, { "code": null, "e": 9579, "s": 9387, "text": "The random walker algorithm expects a label image as input. So we will have the bigger circle that encompasses the person’s entire face and another smaller circle near the middle of the face." }, { "code": null, "e": 9757, "s": 9579, "text": "indices = draw.circle_perimeter(80, 250,20)#from hereimage_labels[indices] = 1image_labels[points[:, 1].astype(np.int), points[:, 0].astype(np.int)] = 2image_show(image_labels);" }, { "code": null, "e": 9808, "s": 9757, "text": "Now, let’s use Random Walker and see what happens." }, { "code": null, "e": 9964, "s": 9808, "text": "image_segmented = seg.random_walker(image_gray, image_labels)# Check our resultsfig, ax = image_show(image_gray)ax.imshow(image_segmented == 1, alpha=0.3);" }, { "code": null, "e": 10176, "s": 9964, "text": "It doesn’t look like it’s grabbing edges as we wanted. To resolve this situation we can tune in the beta parameter until we get the desired results. After several attempts, a value of 3000 works reasonably well." }, { "code": null, "e": 10345, "s": 10176, "text": "image_segmented = seg.random_walker(image_gray, image_labels, beta = 3000)# Check our resultsfig, ax = image_show(image_gray)ax.imshow(image_segmented == 1, alpha=0.3);" }, { "code": null, "e": 10679, "s": 10345, "text": "That’s all for Supervised Segmentation where we had to provide certain inputs and also had to tweak certain parameters. However, it is not always possible to have a human looking at an image and then deciding what inputs to give or where to start from. Fortunately, for those situations, we have Unsupervised segmentation techniques." }, { "code": null, "e": 11033, "s": 10679, "text": "Unsupervised segmentation requires no prior knowledge. Consider an image that is so large that it is not feasible to consider all pixels simultaneously. So in such cases, Unsupervised segmentation can breakdown the image into several sub-regions, so instead of millions of pixels, you have tens to hundreds of regions. Let’s look at two such algorithms:" }, { "code": null, "e": 11268, "s": 11033, "text": "SLIC algorithm actually uses a machine-learning algorithm called K-Means under the hood. It takes in all the pixel values of the image and tries to separate them out into the given number of sub-regions. Read the Reference Paper here." }, { "code": null, "e": 11323, "s": 11268, "text": "SLIC works in color so we will use the original image." }, { "code": null, "e": 11367, "s": 11323, "text": "image_slic = seg.slic(image,n_segments=155)" }, { "code": null, "e": 11633, "s": 11367, "text": "All we’re doing is just setting each sub-image or sub-region that we have found, to the average of that region which makes it look less like a patchwork of randomly assigned colors and more like an image that has been decomposed into areas that are kind of similar." }, { "code": null, "e": 11765, "s": 11633, "text": "# label2rgb replaces each discrete label with the average interior colorimage_show(color.label2rgb(image_slic, image, kind='avg'));" }, { "code": null, "e": 11841, "s": 11765, "text": "We’ve reduced this image from 512*512 = 262,000 pixels down to 155 regions." }, { "code": null, "e": 12217, "s": 11841, "text": "This algorithm also uses a machine-learning algorithm called minimum-spanning tree clustering under the hood. Felzenszwaib doesn’t tell us the exact number of clusters that the image will be partitioned into. It’s going to run and generate as many clusters as it thinks is appropriate for thatgiven scale or zoom factor on the image. The Reference Paper can be accessed here." }, { "code": null, "e": 12294, "s": 12217, "text": "image_felzenszwalb = seg.felzenszwalb(image) image_show(image_felzenszwalb);" }, { "code": null, "e": 12368, "s": 12294, "text": "These are a lot of regions. Let’s calculate the number of unique regions." }, { "code": null, "e": 12407, "s": 12368, "text": "np.unique(image_felzenszwalb).size3368" }, { "code": null, "e": 12493, "s": 12407, "text": "Now let’s recolor them using the region average just as we did in the SLIC algorithm." }, { "code": null, "e": 12616, "s": 12493, "text": "image_felzenszwalb_colored = color.label2rgb(image_felzenszwalb, image, kind='avg')image_show(image_felzenszwalb_colored);" }, { "code": null, "e": 12810, "s": 12616, "text": "Now we get reasonably smaller regions. If we wanted still fewer regions, we could change the scale parameter or start here and combine them. This approach is sometimes called over-segmentation." }, { "code": null, "e": 13032, "s": 12810, "text": "This almost looks more like a posterized image which is essentially just a reduction in the number of colors. To combine them again, you can use the Region Adjacency Graph(RAG) but that’s beyond the scope of this article." }, { "code": null, "e": 13393, "s": 13032, "text": "Till now, we went over image segmentation techniques using only the scikit image module. However, it will be worth mentioning some of the image segmentation techniques which use deep learning. Here is a wonderful blog post that focuses on image segmentation architectures, Losses, Datasets, and Frameworks that you can use for your image segmentation projects." }, { "code": null, "e": 13404, "s": 13393, "text": "neptune.ai" }, { "code": null, "e": 13898, "s": 13404, "text": "Image segmentation is a very important image processing step. It is an active area of research with applications ranging from computer vision to medical imagery to traffic and video surveillance. Python provides a robust library in the form of scikit-image having a large number of algorithms for image processing. It is available free of charge and free of restriction having an active community behind it. Have a look at their documentation to learn more about the library and its use cases." }, { "code": null, "e": 13910, "s": 13898, "text": "References:" } ]
Hamming code Implementation in Java - GeeksforGeeks
11 Jun, 2020 Pre-requisite: Hamming code Hamming code is a set of error-correction codes that can be used to detect and correct the errors that can occur when the data is moved or stored from the sender to the receiver. It is a technique developed by R.W. Hamming for error correction. Examples: Input: message bit = 0101 r1 r2 m1 r4 m2 m3 m4 0 1 0 1 Output: Generated codeword : r1 r2 m1 r4 m2 m3 m4 0 1 0 0 1 0 1 Explanation: Initially r1, r2, r4 is set to '0'. r1 = xor of all bits position which has '1' in its 0th-bit position r2 = xor of all bits which has '1' in its 1st-bit position r3 = xor of all bits which has '1' in its 2nd-bit position Below is the implementation of the Hamming Code: // Java code to implement Hamming Codeclass HammingCode { // print elements of array static void print(int ar[]) { for (int i = 1; i < ar.length; i++) { System.out.print(ar[i]); } System.out.println(); } // calculating value of redundant bits static int[] calculation(int[] ar, int r) { for (int i = 0; i < r; i++) { int x = (int)Math.pow(2, i); for (int j = 1; j < ar.length; j++) { if (((j >> i) & 1) == 1) { if (x != j) ar[x] = ar[x] ^ ar[j]; } } System.out.println("r" + x + " = " + ar[x]); } return ar; } static int[] generateCode(String str, int M, int r) { int[] ar = new int[r + M + 1]; int j = 0; for (int i = 1; i < ar.length; i++) { if ((Math.ceil(Math.log(i) / Math.log(2)) - Math.floor(Math.log(i) / Math.log(2))) == 0) { // if i == 2^n for n in (0, 1, 2, .....) // then ar[i]=0 // codeword[i] = 0 ---- // redundant bits are initialized // with value 0 ar[i] = 0; } else { // codeword[i] = dataword[j] ar[i] = (int)(str.charAt(j) - '0'); j++; } } return ar; } // Driver code public static void main(String[] args) { // input message String str = "0101"; int M = str.length(); int r = 1; while (Math.pow(2, r) < (M + r + 1)) { // r is number of redundant bits r++; } int[] ar = generateCode(str, M, r); System.out.println("Generated hamming code "); ar = calculation(ar, r); print(ar); }} Generated hamming code r1 = 0 r2 = 1 r4 = 0 0100101 Akanksha_Rai cryptography Computer Networks Java Programs cryptography Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Advanced Encryption Standard (AES) Intrusion Detection System (IDS) Introduction and IPv4 Datagram Header Block Cipher modes of Operation Stop and Wait ARQ Initializing a List in Java Convert a String to Character array in Java Java Programming Examples How to Iterate HashMap in Java? Implementing a Linked List in Java using Class
[ { "code": null, "e": 24145, "s": 24117, "text": "\n11 Jun, 2020" }, { "code": null, "e": 24173, "s": 24145, "text": "Pre-requisite: Hamming code" }, { "code": null, "e": 24418, "s": 24173, "text": "Hamming code is a set of error-correction codes that can be used to detect and correct the errors that can occur when the data is moved or stored from the sender to the receiver. It is a technique developed by R.W. Hamming for error correction." }, { "code": null, "e": 24428, "s": 24418, "text": "Examples:" }, { "code": null, "e": 24816, "s": 24428, "text": "Input: \nmessage bit = 0101\nr1 r2 m1 r4 m2 m3 m4\n 0 1 0 1\nOutput:\nGenerated codeword :\nr1 r2 m1 r4 m2 m3 m4\n0 1 0 0 1 0 1\n\nExplanation:\nInitially r1, r2, r4 is set to '0'.\nr1 = xor of all bits position \n which has '1' in its 0th-bit position\nr2 = xor of all bits\n which has '1' in its 1st-bit position\nr3 = xor of all bits\n which has '1' in its 2nd-bit position\n" }, { "code": null, "e": 24865, "s": 24816, "text": "Below is the implementation of the Hamming Code:" }, { "code": "// Java code to implement Hamming Codeclass HammingCode { // print elements of array static void print(int ar[]) { for (int i = 1; i < ar.length; i++) { System.out.print(ar[i]); } System.out.println(); } // calculating value of redundant bits static int[] calculation(int[] ar, int r) { for (int i = 0; i < r; i++) { int x = (int)Math.pow(2, i); for (int j = 1; j < ar.length; j++) { if (((j >> i) & 1) == 1) { if (x != j) ar[x] = ar[x] ^ ar[j]; } } System.out.println(\"r\" + x + \" = \" + ar[x]); } return ar; } static int[] generateCode(String str, int M, int r) { int[] ar = new int[r + M + 1]; int j = 0; for (int i = 1; i < ar.length; i++) { if ((Math.ceil(Math.log(i) / Math.log(2)) - Math.floor(Math.log(i) / Math.log(2))) == 0) { // if i == 2^n for n in (0, 1, 2, .....) // then ar[i]=0 // codeword[i] = 0 ---- // redundant bits are initialized // with value 0 ar[i] = 0; } else { // codeword[i] = dataword[j] ar[i] = (int)(str.charAt(j) - '0'); j++; } } return ar; } // Driver code public static void main(String[] args) { // input message String str = \"0101\"; int M = str.length(); int r = 1; while (Math.pow(2, r) < (M + r + 1)) { // r is number of redundant bits r++; } int[] ar = generateCode(str, M, r); System.out.println(\"Generated hamming code \"); ar = calculation(ar, r); print(ar); }}", "e": 26767, "s": 24865, "text": null }, { "code": null, "e": 26821, "s": 26767, "text": "Generated hamming code \nr1 = 0\nr2 = 1\nr4 = 0\n0100101\n" }, { "code": null, "e": 26834, "s": 26821, "text": "Akanksha_Rai" }, { "code": null, "e": 26847, "s": 26834, "text": "cryptography" }, { "code": null, "e": 26865, "s": 26847, "text": "Computer Networks" }, { "code": null, "e": 26879, "s": 26865, "text": "Java Programs" }, { "code": null, "e": 26892, "s": 26879, "text": "cryptography" }, { "code": null, "e": 26910, "s": 26892, "text": "Computer Networks" }, { "code": null, "e": 27008, "s": 26910, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27017, "s": 27008, "text": "Comments" }, { "code": null, "e": 27030, "s": 27017, "text": "Old Comments" }, { "code": null, "e": 27065, "s": 27030, "text": "Advanced Encryption Standard (AES)" }, { "code": null, "e": 27098, "s": 27065, "text": "Intrusion Detection System (IDS)" }, { "code": null, "e": 27136, "s": 27098, "text": "Introduction and IPv4 Datagram Header" }, { "code": null, "e": 27168, "s": 27136, "text": "Block Cipher modes of Operation" }, { "code": null, "e": 27186, "s": 27168, "text": "Stop and Wait ARQ" }, { "code": null, "e": 27214, "s": 27186, "text": "Initializing a List in Java" }, { "code": null, "e": 27258, "s": 27214, "text": "Convert a String to Character array in Java" }, { "code": null, "e": 27284, "s": 27258, "text": "Java Programming Examples" }, { "code": null, "e": 27316, "s": 27284, "text": "How to Iterate HashMap in Java?" } ]
GATE | GATE-CS-2017 (Set 2) | Question 29 - GeeksforGeeks
29 Sep, 2021 Given the following binary number in 32 bit (single precision) IEEE-754 format: 00111110011011010000000000000000 The decimal value closest to this floating-point number is:(A) 1.45 X 101(B) 1.45 X 10-1(C) 2.27 X 10-1(D) 2.27 X 101Answer: (C)Explanation: In 32-bit IEEE-754 format 1st bit represent sign 2-9th bit represent exponent and 10-32 represent Mantissa (Fraction part) Sign = 0, so positive2-9 bits — 01111100 when subtracted by 01111111 i.e., 126 decimal value gives -> 0000 0011Which is -3.(negative as the value is less than 126)As number is less than 126 it is subtracted otherwise 126 would have been subtracted from it in 32 bit representation.(https://www3.ntu.edu.sg/home/ehchua/programming/java/datarepresentation.html) Mantissa is normal ,hence, 1.M can be used .Which is 1.1101101.Thus,Data + 1.1101101 * 2^-3 (±M * B^(±e) )Mantissa shift right 3 times ->+0.0011101101= 0.228= 2.28 * 10^-1 Thus, option c is correct. This explanation is contributed by Shashank Shanker. YouTubeGeeksforGeeks GATE Computer Science16.1K subscribersFloating Point Representation with Rishabh Setiya | GeeksforGeeks GATEWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0011:55 / 24:34•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=M91XDWNNVU8" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question GATE-CS-2017 (Set 2) GATE-GATE-CS-2017 (Set 2) GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments GATE | GATE CS 1997 | Question 25 GATE | GATE CS 2012 | Question 54 GATE | GATE-CS-2014-(Set-1) | Question 65 GATE | GATE CS 2019 | Question 50 GATE | GATE CS 2008 | Question 69 GATE | GATE CS 2018 | Question 45 GATE | GATE CS 2020 | Question 16 GATE | GATE CS 2011 | Question 65 GATE | GATE CS 2011 | Question 43 GATE | GATE CS 2010 | Question 33
[ { "code": null, "e": 24167, "s": 24139, "text": "\n29 Sep, 2021" }, { "code": null, "e": 24247, "s": 24167, "text": "Given the following binary number in 32 bit (single precision) IEEE-754 format:" }, { "code": null, "e": 24281, "s": 24247, "text": "00111110011011010000000000000000\n" }, { "code": null, "e": 24448, "s": 24281, "text": "The decimal value closest to this floating-point number is:(A) 1.45 X 101(B) 1.45 X 10-1(C) 2.27 X 10-1(D) 2.27 X 101Answer: (C)Explanation: In 32-bit IEEE-754 format" }, { "code": null, "e": 24546, "s": 24448, "text": "1st bit represent sign\n2-9th bit represent exponent\nand 10-32 represent Mantissa (Fraction part)\n" }, { "code": null, "e": 24906, "s": 24546, "text": "Sign = 0, so positive2-9 bits — 01111100 when subtracted by 01111111 i.e., 126 decimal value gives -> 0000 0011Which is -3.(negative as the value is less than 126)As number is less than 126 it is subtracted otherwise 126 would have been subtracted from it in 32 bit representation.(https://www3.ntu.edu.sg/home/ehchua/programming/java/datarepresentation.html)" }, { "code": null, "e": 25078, "s": 24906, "text": "Mantissa is normal ,hence, 1.M can be used .Which is 1.1101101.Thus,Data + 1.1101101 * 2^-3 (±M * B^(±e) )Mantissa shift right 3 times ->+0.0011101101= 0.228= 2.28 * 10^-1" }, { "code": null, "e": 25105, "s": 25078, "text": "Thus, option c is correct." }, { "code": null, "e": 25158, "s": 25105, "text": "This explanation is contributed by Shashank Shanker." }, { "code": null, "e": 26057, "s": 25158, "text": "YouTubeGeeksforGeeks GATE Computer Science16.1K subscribersFloating Point Representation with Rishabh Setiya | GeeksforGeeks GATEWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0011:55 / 24:34•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=M91XDWNNVU8\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question" }, { "code": null, "e": 26078, "s": 26057, "text": "GATE-CS-2017 (Set 2)" }, { "code": null, "e": 26104, "s": 26078, "text": "GATE-GATE-CS-2017 (Set 2)" }, { "code": null, "e": 26109, "s": 26104, "text": "GATE" }, { "code": null, "e": 26207, "s": 26109, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26216, "s": 26207, "text": "Comments" }, { "code": null, "e": 26229, "s": 26216, "text": "Old Comments" }, { "code": null, "e": 26263, "s": 26229, "text": "GATE | GATE CS 1997 | Question 25" }, { "code": null, "e": 26297, "s": 26263, "text": "GATE | GATE CS 2012 | Question 54" }, { "code": null, "e": 26339, "s": 26297, "text": "GATE | GATE-CS-2014-(Set-1) | Question 65" }, { "code": null, "e": 26373, "s": 26339, "text": "GATE | GATE CS 2019 | Question 50" }, { "code": null, "e": 26407, "s": 26373, "text": "GATE | GATE CS 2008 | Question 69" }, { "code": null, "e": 26441, "s": 26407, "text": "GATE | GATE CS 2018 | Question 45" }, { "code": null, "e": 26475, "s": 26441, "text": "GATE | GATE CS 2020 | Question 16" }, { "code": null, "e": 26509, "s": 26475, "text": "GATE | GATE CS 2011 | Question 65" }, { "code": null, "e": 26543, "s": 26509, "text": "GATE | GATE CS 2011 | Question 43" } ]
C - Structured Datatypes
C - Programming HOME C - Basic Introduction C - Program Structure C - Reserved Keywords C - Basic Datatypes C - Variable Types C - Storage Classes C - Using Constants C - Operator Types C - Control Statements C - Input and Output C - Pointing to Data C - Using Functions C - Play with Strings C - Structure Datatype C - Working with Files C - Bits Manipulation C - Pre-Processors C - Useful Concepts C - Built-in Functions C - Useful Resources Computer Glossary Who is Who Copyright © 2014 by tutorialspoint A structure in C is a collection of items of different types. You can think of a structure as a "record" is in Pascal or a class in Java without methods. A structure in C is a collection of items of different types. You can think of a structure as a "record" is in Pascal or a class in Java without methods. Structures, or structs, are very useful in creating data structures larger and more complex than the ones we have discussed so far. Structures, or structs, are very useful in creating data structures larger and more complex than the ones we have discussed so far. Simply you can group various built-in data types into a structure. Simply you can group various built-in data types into a structure. Object conepts was derived from Structure concept. You can achieve few object oriented goals using C structure but it is very complex. Object conepts was derived from Structure concept. You can achieve few object oriented goals using C structure but it is very complex. Following is the example how to define a structure. struct student { char firstName[20]; char lastName[20]; char SSN[9]; float gpa; }; Now you have a new datatype called student and you can use this datatype define your variables of student type: struct student student_a, student_b; or an array of students as struct student students[50]; Another way to declare the same thing is: struct { char firstName[20]; char lastName[20]; char SSN[10]; float gpa; } student_a, student_b; All the variables inside an structure will be accessed using these values as student_a.firstName will give value of firstName variable. Similarly we can aqccess other variables. Try out following example to understand the concept: #include <stdio.h> struct student { char firstName[20]; char lastName[20]; char SSN[10]; float gpa; }; main() { struct student student_a; strcpy(student_a.firstName, "Deo"); strcpy(student_a.lastName, "Dum"); strcpy(student_a.SSN, "2333234" ); student_a.gpa = 2009.20; printf( "First Name: %s\n", student_a.firstName ); printf( "Last Name: %s\n", student_a.lastName ); printf( "SNN : %s\n", student_a.SSN ); printf( "GPA : %f\n", student_a.gpa ); } This will produce following results: First Name: Deo Last Name: Dum SSN : 2333234 GPA : 2009.20 Sometimes it is useful to assign pointers to structures (this will be evident in the next section with self-referential structures). Declaring pointers to structures is basically the same as declaring a normal pointer: struct student *student_a; To dereference, you can use the infix operator: ->. printf("%s\n", student_a->SSN); There is an easier way to define structs or you could "alias" types you create. For example: typedef struct{ char firstName[20]; char lastName[20]; char SSN[10]; float gpa; }student; Now you can use student directly to define variables of student type without using struct keyword. Following is the example: student student_a; You can use typedef for non-structs: typedef long int *pint32; pint32 x, y, z; x, y and z are all pointers to long ints Unions are declared in the same fashion as structs, but have a fundamental difference. Only one item within the union can be used at any time, because the memory allocated for each item inside the union is in a shared memory location. Here is how we define a Union union Shape { int circle; int triangle; int ovel; }; We use union in such case where only one condition will be applied and only one variable will be used. You can create arrays of structs. Structs can be copied or assigned. The & operator may be used with structs to show addresses. Structs can be passed into functions. Structs can also be returned from functions. Structs cannot be compared! Structures can store non-homogenous data types into a single collection, much like an array does for common data (except it isn't accessed in the same manner). Pointers to structs have a special infix operator: -> for dereferencing the pointer. typedef can help you clear your code up and can help save some keystrokes. Advertisements 6 Lectures 1.5 hours Mr. Pradeep Kshetrapal 41 Lectures 5 hours AR Shankar 11 Lectures 58 mins Musab Zayadneh 59 Lectures 15.5 hours Narendra P 11 Lectures 1 hours Sagar Mehta 39 Lectures 4 hours Vikas Yadav Print Add Notes Bookmark this page
[ { "code": null, "e": 1475, "s": 1454, "text": "C - Programming HOME" }, { "code": null, "e": 1498, "s": 1475, "text": "C - Basic Introduction" }, { "code": null, "e": 1520, "s": 1498, "text": "C - Program Structure" }, { "code": null, "e": 1542, "s": 1520, "text": "C - Reserved Keywords" }, { "code": null, "e": 1562, "s": 1542, "text": "C - Basic Datatypes" }, { "code": null, "e": 1581, "s": 1562, "text": "C - Variable Types" }, { "code": null, "e": 1601, "s": 1581, "text": "C - Storage Classes" }, { "code": null, "e": 1621, "s": 1601, "text": "C - Using Constants" }, { "code": null, "e": 1640, "s": 1621, "text": "C - Operator Types" }, { "code": null, "e": 1663, "s": 1640, "text": "C - Control Statements" }, { "code": null, "e": 1684, "s": 1663, "text": "C - Input and Output" }, { "code": null, "e": 1705, "s": 1684, "text": "C - Pointing to Data" }, { "code": null, "e": 1725, "s": 1705, "text": "C - Using Functions" }, { "code": null, "e": 1747, "s": 1725, "text": "C - Play with Strings" }, { "code": null, "e": 1770, "s": 1747, "text": "C - Structure Datatype" }, { "code": null, "e": 1793, "s": 1770, "text": "C - Working with Files" }, { "code": null, "e": 1815, "s": 1793, "text": "C - Bits Manipulation" }, { "code": null, "e": 1834, "s": 1815, "text": "C - Pre-Processors" }, { "code": null, "e": 1854, "s": 1834, "text": "C - Useful Concepts" }, { "code": null, "e": 1877, "s": 1854, "text": "C - Built-in Functions" }, { "code": null, "e": 1898, "s": 1877, "text": "C - Useful Resources" }, { "code": null, "e": 1916, "s": 1898, "text": "Computer Glossary" }, { "code": null, "e": 1927, "s": 1916, "text": "Who is Who" }, { "code": null, "e": 1962, "s": 1927, "text": "Copyright © 2014 by tutorialspoint" }, { "code": null, "e": 2116, "s": 1962, "text": "A structure in C is a collection of items of different types. You can think of a structure as a \"record\" is in Pascal or a class in Java without methods." }, { "code": null, "e": 2270, "s": 2116, "text": "A structure in C is a collection of items of different types. You can think of a structure as a \"record\" is in Pascal or a class in Java without methods." }, { "code": null, "e": 2402, "s": 2270, "text": "Structures, or structs, are very useful in creating data structures larger and more complex than the ones we have discussed so far." }, { "code": null, "e": 2534, "s": 2402, "text": "Structures, or structs, are very useful in creating data structures larger and more complex than the ones we have discussed so far." }, { "code": null, "e": 2601, "s": 2534, "text": "Simply you can group various built-in data types into a structure." }, { "code": null, "e": 2668, "s": 2601, "text": "Simply you can group various built-in data types into a structure." }, { "code": null, "e": 2803, "s": 2668, "text": "Object conepts was derived from Structure concept. You can achieve few object oriented goals using C structure but it is very complex." }, { "code": null, "e": 2938, "s": 2803, "text": "Object conepts was derived from Structure concept. You can achieve few object oriented goals using C structure but it is very complex." }, { "code": null, "e": 2990, "s": 2938, "text": "Following is the example how to define a structure." }, { "code": null, "e": 3092, "s": 2990, "text": "struct student {\n char firstName[20];\n char lastName[20];\n char SSN[9];\n float gpa;\n };\n" }, { "code": null, "e": 3204, "s": 3092, "text": "Now you have a new datatype called student and you can use this datatype define your variables of student type:" }, { "code": null, "e": 3300, "s": 3204, "text": "struct student student_a, student_b;\n\nor an array of students as\n\nstruct student students[50];\n" }, { "code": null, "e": 3342, "s": 3300, "text": "Another way to declare the same thing is:" }, { "code": null, "e": 3458, "s": 3342, "text": "struct {\n char firstName[20];\n char lastName[20];\n char SSN[10];\n float gpa;\n } student_a, student_b;\n" }, { "code": null, "e": 3636, "s": 3458, "text": "All the variables inside an structure will be accessed using these values as student_a.firstName will give value of firstName variable. Similarly we can aqccess other variables." }, { "code": null, "e": 3689, "s": 3636, "text": "Try out following example to understand the concept:" }, { "code": null, "e": 4172, "s": 3689, "text": "#include <stdio.h>\nstruct student {\n char firstName[20];\n char lastName[20];\n char SSN[10];\n float gpa;\n};\n\nmain()\n{\n struct student student_a;\n\n strcpy(student_a.firstName, \"Deo\");\n strcpy(student_a.lastName, \"Dum\");\n strcpy(student_a.SSN, \"2333234\" );\n student_a.gpa = 2009.20;\n\n printf( \"First Name: %s\\n\", student_a.firstName );\n printf( \"Last Name: %s\\n\", student_a.lastName );\n printf( \"SNN : %s\\n\", student_a.SSN );\n printf( \"GPA : %f\\n\", student_a.gpa );\n}\n" }, { "code": null, "e": 4209, "s": 4172, "text": "This will produce following results:" }, { "code": null, "e": 4269, "s": 4209, "text": "First Name: Deo\nLast Name: Dum\nSSN : 2333234\nGPA : 2009.20\n" }, { "code": null, "e": 4488, "s": 4269, "text": "Sometimes it is useful to assign pointers to structures (this will be evident in the next section with self-referential structures). Declaring pointers to structures is basically the same as declaring a normal pointer:" }, { "code": null, "e": 4516, "s": 4488, "text": "struct student *student_a;\n" }, { "code": null, "e": 4568, "s": 4516, "text": "To dereference, you can use the infix operator: ->." }, { "code": null, "e": 4601, "s": 4568, "text": "printf(\"%s\\n\", student_a->SSN);\n" }, { "code": null, "e": 4694, "s": 4601, "text": "There is an easier way to define structs or you could \"alias\" types you create. For example:" }, { "code": null, "e": 4803, "s": 4694, "text": "typedef struct{\n char firstName[20];\n char lastName[20];\n char SSN[10];\n float gpa;\n }student;\n" }, { "code": null, "e": 4929, "s": 4803, "text": "Now you can use student directly to define variables of student type without using struct keyword. Following is the example:" }, { "code": null, "e": 4949, "s": 4929, "text": "student student_a;\n" }, { "code": null, "e": 4986, "s": 4949, "text": "You can use typedef for non-structs:" }, { "code": null, "e": 5030, "s": 4986, "text": "typedef long int *pint32;\n\npint32 x, y, z;\n" }, { "code": null, "e": 5071, "s": 5030, "text": "x, y and z are all pointers to long ints" }, { "code": null, "e": 5306, "s": 5071, "text": "Unions are declared in the same fashion as structs, but have a fundamental difference. Only one item within the union can be used at any time, because the memory allocated for each item inside the union is in a shared memory location." }, { "code": null, "e": 5336, "s": 5306, "text": "Here is how we define a Union" }, { "code": null, "e": 5408, "s": 5336, "text": "union Shape {\n int circle;\n int triangle;\n int ovel;\n};\n" }, { "code": null, "e": 5511, "s": 5408, "text": "We use union in such case where only one condition will be applied and only one variable will be used." }, { "code": null, "e": 5545, "s": 5511, "text": "You can create arrays of structs." }, { "code": null, "e": 5580, "s": 5545, "text": "Structs can be copied or assigned." }, { "code": null, "e": 5639, "s": 5580, "text": "The & operator may be used with structs to show addresses." }, { "code": null, "e": 5722, "s": 5639, "text": "Structs can be passed into functions. Structs can also be returned from functions." }, { "code": null, "e": 5750, "s": 5722, "text": "Structs cannot be compared!" }, { "code": null, "e": 5910, "s": 5750, "text": "Structures can store non-homogenous data types into a single collection, much like an array does for common data (except it isn't accessed in the same manner)." }, { "code": null, "e": 5995, "s": 5910, "text": "Pointers to structs have a special infix operator: -> for dereferencing the pointer." }, { "code": null, "e": 6070, "s": 5995, "text": "typedef can help you clear your code up and can help save some keystrokes." }, { "code": null, "e": 6087, "s": 6070, "text": "\nAdvertisements\n" }, { "code": null, "e": 6121, "s": 6087, "text": "\n 6 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6145, "s": 6121, "text": " Mr. Pradeep Kshetrapal" }, { "code": null, "e": 6178, "s": 6145, "text": "\n 41 Lectures \n 5 hours \n" }, { "code": null, "e": 6190, "s": 6178, "text": " AR Shankar" }, { "code": null, "e": 6222, "s": 6190, "text": "\n 11 Lectures \n 58 mins\n" }, { "code": null, "e": 6238, "s": 6222, "text": " Musab Zayadneh" }, { "code": null, "e": 6274, "s": 6238, "text": "\n 59 Lectures \n 15.5 hours \n" }, { "code": null, "e": 6286, "s": 6274, "text": " Narendra P" }, { "code": null, "e": 6319, "s": 6286, "text": "\n 11 Lectures \n 1 hours \n" }, { "code": null, "e": 6332, "s": 6319, "text": " Sagar Mehta" }, { "code": null, "e": 6365, "s": 6332, "text": "\n 39 Lectures \n 4 hours \n" }, { "code": null, "e": 6378, "s": 6365, "text": " Vikas Yadav" }, { "code": null, "e": 6385, "s": 6378, "text": " Print" }, { "code": null, "e": 6396, "s": 6385, "text": " Add Notes" } ]
Array Basics in Shell Scripting | Set 1 - GeeksforGeeks
30 Jan, 2018 Consider a Situation if we want to store 1000 numbers and perform operations on them. If we use simple variable concept then we have to create 1000 variables and the perform operations on them. But it is difficult to handle a large number of variables. So it is good to store the same type of values in the array and then access via index number. Array in Shell ScriptingAn array is a systematic arrangement of the same type of data. But in Shell script Array is a variable which contains multiple values may be of same type or different type since by default in shell script everything is treated as a string. An array is zero-based ie indexing start with 0. How to Declare Array in Shell Scripting?We can declare an array in a shell script in different ways. 1. Indirect DeclarationIn Indirect declaration, We assigned a value in a particular index of Array Variable. No need to first declare. ARRAYNAME[INDEXNR]=value 2. Explicit DeclarationIn Explicit Declaration, First We declare array then assigned the values. declare -a ARRAYNAME 3. Compound AssignmentIn Compount Assignment, We declare array with a bunch of values. We can add other values later too. ARRAYNAME=(value1 value2 .... valueN) or[indexnumber=]string ARRAYNAME=([1]=10 [2]=20 [3]=30) To Print Array Value in Shell Script? To Print All elements[@] & [*] means All elements of Array. echo ${ARRAYNAME[*]} #! /bin/bash # To declare static Array arr=(prakhar ankit 1 rishabh manish abhinav) # To print all elements of arrayecho ${arr[@]} echo ${arr[*]} echo ${arr[@]:0} echo ${arr[*]:0} Output: prakhar ankit 1 rishabh manish abhinav prakhar ankit 1 rishabh manish abhinav prakhar ankit 1 rishabh manish abhinav prakhar ankit 1 rishabh manish abhinav To Print first element # To print first elementecho ${arr[0]} echo ${arr} Output: prakhar prakhar To Print Selected index element echo ${ARRAYNAME[INDEXNR]} # To print particular elementecho ${arr[3]} echo ${arr[1]} Output: rishabh ankit To print elements from a particular index echo ${ARRAYNAME[WHICH_ELEMENT]:STARTING_INDEX} # To print elements from a particular indexecho ${arr[@]:0} echo ${arr[@]:1}echo ${arr[@]:2} echo ${arr[0]:1} Output: prakhar ankit 1 rishabh manish abhinav ankit 1 rishabh manish abhinav 1 rishabh manish abhinav prakhar To print elements in range echo ${ARRAYNAME[WHICH_ELEMENT]:STARTING_INDEX:COUNT_ELEMENT} # To print elements in rangeecho ${arr[@]:1:4} echo ${arr[@]:2:3} echo ${arr[0]:1:3} Output: ankit 1 rishabh manish 1 rishabh manish rak To count Length of in Array To count the length of a particular element in Array.Use #(hash) to print length of particular element # Length of Particular elementecho ${#arr[0]} echo ${#arr} Output: 7 7 To count length of Array. # Size of an Arrayecho ${#arr[@]} echo ${#arr[*]} Output: 6 6 To Search in Array arr[@] : All Array Elements./Search_using_Regular_Expression/ : Search in ArraySearch Returns 1 if it found the pattern else it return zero. It does not alter the original array elements. # Search in Arrayecho ${arr[@]/*[aA]*/} Output: 1 To Search & Replace in Array //Search_using_Regular_Expression/Replace : Search & Replace Search & Replace does not change in Original Value of Array Element. It just returned the new value. So you can store this value in same or different variable. # Replacing Substring Temporaryecho ${arr[@]//a/A} echo ${arr[@]} echo ${arr[0]//r/R} Output: prAkhAr Ankit 1 rishAbh mAnish AbhinAv prakhar ankit 1 rishabh manish abhinav RakhaR To delete Array Variable in Shell Script? To delete index-1 element unset ARRAYNAME[1] To delete the whole Array unset ARRAYNAME #! /bin/bash# To declare static Array arr=(prakhar ankit 1 rishabh manish abhinav) # To print all elements of arrayecho ${arr[@]} # prakhar ankit 1 rishabh manish abhinavecho ${arr[*]} # prakhar ankit 1 rishabh manish abhinavecho ${arr[@]:0} # prakhar ankit 1 rishabh manish abhinavecho ${arr[*]:0} # prakhar ankit 1 rishabh manish abhinav # To print first elementecho ${arr[0]} # prakharecho ${arr} # prakhar # To print particular elementecho ${arr[3]} # rishabhecho ${arr[1]} # ankit # To print elements from a particular indexecho ${arr[@]:0} # prakhar ankit 1 rishabh manish abhinavecho ${arr[@]:1} # ankit 1 rishabh manish abhinavecho ${arr[@]:2} # 1 rishabh manish abhinavecho ${arr[0]:1} # rakhar # To print elements in rangeecho ${arr[@]:1:4} # ankit 1 rishabh manishecho ${arr[@]:2:3} # 1 rishabh manishecho ${arr[0]:1:3} # rak # Length of Particular elementecho ${#arr[0]} # 7echo ${#arr} # 7 # Size of an Arrayecho ${#arr[@]} # 6echo ${#arr[*]} # 6 # Search in Arrayecho ${arr[@]/*[aA]*/} # 1 # Replacing Substring Temporaryecho ${arr[@]//a/A} # prAkhAr Ankit 1 rishAbh mAnish AbhinAvecho ${arr[@]} # prakhar ankit 1 rishabh manish abhinavecho ${arr[0]//r/R} # pRakhaR Output: prakhar ankit 1 rishabh manish abhinav prakhar ankit 1 rishabh manish abhinav prakhar ankit 1 rishabh manish abhinav prakhar ankit 1 rishabh manish abhinav prakhar prakhar rishabh ankit prakhar ankit 1 rishabh manish abhinav ankit 1 rishabh manish abhinav 1 rishabh manish abhinav rakhar ankit 1 rishabh manish 1 rishabh manish rak 7 7 6 6 1 prAkhAr Ankit 1 rishAbh mAnish AbhinAv prakhar ankit 1 rishabh manish abhinav pRakhaR Reference:https://www.tecmint.com/working-with-arrays-in-linux-shell-scripting/ Shell Script Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments TCP Server-Client implementation in C tar command in Linux with examples curl command in Linux with Examples UDP Server-Client implementation in C Conditional Statements | Shell Script Cat command in Linux with examples echo command in Linux with Examples touch command in Linux with Examples Tail command in Linux with examples Compiling with g++
[ { "code": null, "e": 23685, "s": 23657, "text": "\n30 Jan, 2018" }, { "code": null, "e": 24032, "s": 23685, "text": "Consider a Situation if we want to store 1000 numbers and perform operations on them. If we use simple variable concept then we have to create 1000 variables and the perform operations on them. But it is difficult to handle a large number of variables. So it is good to store the same type of values in the array and then access via index number." }, { "code": null, "e": 24345, "s": 24032, "text": "Array in Shell ScriptingAn array is a systematic arrangement of the same type of data. But in Shell script Array is a variable which contains multiple values may be of same type or different type since by default in shell script everything is treated as a string. An array is zero-based ie indexing start with 0." }, { "code": null, "e": 24446, "s": 24345, "text": "How to Declare Array in Shell Scripting?We can declare an array in a shell script in different ways." }, { "code": null, "e": 24581, "s": 24446, "text": "1. Indirect DeclarationIn Indirect declaration, We assigned a value in a particular index of Array Variable. No need to first declare." }, { "code": null, "e": 24606, "s": 24581, "text": "ARRAYNAME[INDEXNR]=value" }, { "code": null, "e": 24703, "s": 24606, "text": "2. Explicit DeclarationIn Explicit Declaration, First We declare array then assigned the values." }, { "code": null, "e": 24724, "s": 24703, "text": "declare -a ARRAYNAME" }, { "code": null, "e": 24846, "s": 24724, "text": "3. Compound AssignmentIn Compount Assignment, We declare array with a bunch of values. We can add other values later too." }, { "code": null, "e": 24885, "s": 24846, "text": "ARRAYNAME=(value1 value2 .... valueN)" }, { "code": null, "e": 24908, "s": 24885, "text": "or[indexnumber=]string" }, { "code": null, "e": 24941, "s": 24908, "text": "ARRAYNAME=([1]=10 [2]=20 [3]=30)" }, { "code": null, "e": 24979, "s": 24941, "text": "To Print Array Value in Shell Script?" }, { "code": null, "e": 25039, "s": 24979, "text": "To Print All elements[@] & [*] means All elements of Array." }, { "code": null, "e": 25060, "s": 25039, "text": "echo ${ARRAYNAME[*]}" }, { "code": "#! /bin/bash # To declare static Array arr=(prakhar ankit 1 rishabh manish abhinav) # To print all elements of arrayecho ${arr[@]} echo ${arr[*]} echo ${arr[@]:0} echo ${arr[*]:0} ", "e": 25259, "s": 25060, "text": null }, { "code": null, "e": 25267, "s": 25259, "text": "Output:" }, { "code": null, "e": 25424, "s": 25267, "text": "prakhar ankit 1 rishabh manish abhinav\nprakhar ankit 1 rishabh manish abhinav\nprakhar ankit 1 rishabh manish abhinav\nprakhar ankit 1 rishabh manish abhinav\n" }, { "code": null, "e": 25447, "s": 25424, "text": "To Print first element" }, { "code": "# To print first elementecho ${arr[0]} echo ${arr} ", "e": 25513, "s": 25447, "text": null }, { "code": null, "e": 25521, "s": 25513, "text": "Output:" }, { "code": null, "e": 25538, "s": 25521, "text": "prakhar\nprakhar\n" }, { "code": null, "e": 25570, "s": 25538, "text": "To Print Selected index element" }, { "code": null, "e": 25597, "s": 25570, "text": "echo ${ARRAYNAME[INDEXNR]}" }, { "code": "# To print particular elementecho ${arr[3]} echo ${arr[1]} ", "e": 25671, "s": 25597, "text": null }, { "code": null, "e": 25679, "s": 25671, "text": "Output:" }, { "code": null, "e": 25694, "s": 25679, "text": "rishabh\nankit\n" }, { "code": null, "e": 25736, "s": 25694, "text": "To print elements from a particular index" }, { "code": null, "e": 25784, "s": 25736, "text": "echo ${ARRAYNAME[WHICH_ELEMENT]:STARTING_INDEX}" }, { "code": "# To print elements from a particular indexecho ${arr[@]:0} echo ${arr[@]:1}echo ${arr[@]:2} echo ${arr[0]:1} ", "e": 25906, "s": 25784, "text": null }, { "code": null, "e": 25914, "s": 25906, "text": "Output:" }, { "code": null, "e": 26018, "s": 25914, "text": "prakhar ankit 1 rishabh manish abhinav\nankit 1 rishabh manish abhinav\n1 rishabh manish abhinav\nprakhar\n" }, { "code": null, "e": 26045, "s": 26018, "text": "To print elements in range" }, { "code": null, "e": 26107, "s": 26045, "text": "echo ${ARRAYNAME[WHICH_ELEMENT]:STARTING_INDEX:COUNT_ELEMENT}" }, { "code": "# To print elements in rangeecho ${arr[@]:1:4} echo ${arr[@]:2:3} echo ${arr[0]:1:3} ", "e": 26204, "s": 26107, "text": null }, { "code": null, "e": 26212, "s": 26204, "text": "Output:" }, { "code": null, "e": 26257, "s": 26212, "text": "ankit 1 rishabh manish\n1 rishabh manish\nrak\n" }, { "code": null, "e": 26285, "s": 26257, "text": "To count Length of in Array" }, { "code": null, "e": 26388, "s": 26285, "text": "To count the length of a particular element in Array.Use #(hash) to print length of particular element" }, { "code": "# Length of Particular elementecho ${#arr[0]} echo ${#arr} ", "e": 26462, "s": 26388, "text": null }, { "code": null, "e": 26470, "s": 26462, "text": "Output:" }, { "code": null, "e": 26475, "s": 26470, "text": "7\n7\n" }, { "code": null, "e": 26501, "s": 26475, "text": "To count length of Array." }, { "code": "# Size of an Arrayecho ${#arr[@]} echo ${#arr[*]} ", "e": 26566, "s": 26501, "text": null }, { "code": null, "e": 26574, "s": 26566, "text": "Output:" }, { "code": null, "e": 26579, "s": 26574, "text": "6\n6\n" }, { "code": null, "e": 26598, "s": 26579, "text": "To Search in Array" }, { "code": null, "e": 26786, "s": 26598, "text": "arr[@] : All Array Elements./Search_using_Regular_Expression/ : Search in ArraySearch Returns 1 if it found the pattern else it return zero. It does not alter the original array elements." }, { "code": "# Search in Arrayecho ${arr[@]/*[aA]*/} ", "e": 26830, "s": 26786, "text": null }, { "code": null, "e": 26838, "s": 26830, "text": "Output:" }, { "code": null, "e": 26841, "s": 26838, "text": "1\n" }, { "code": null, "e": 26870, "s": 26841, "text": "To Search & Replace in Array" }, { "code": null, "e": 26931, "s": 26870, "text": "//Search_using_Regular_Expression/Replace : Search & Replace" }, { "code": null, "e": 27091, "s": 26931, "text": "Search & Replace does not change in Original Value of Array Element. It just returned the new value. So you can store this value in same or different variable." }, { "code": "# Replacing Substring Temporaryecho ${arr[@]//a/A} echo ${arr[@]} echo ${arr[0]//r/R} ", "e": 27205, "s": 27091, "text": null }, { "code": null, "e": 27213, "s": 27205, "text": "Output:" }, { "code": null, "e": 27299, "s": 27213, "text": "prAkhAr Ankit 1 rishAbh mAnish AbhinAv\nprakhar ankit 1 rishabh manish abhinav\nRakhaR\n" }, { "code": null, "e": 27341, "s": 27299, "text": "To delete Array Variable in Shell Script?" }, { "code": null, "e": 27367, "s": 27341, "text": "To delete index-1 element" }, { "code": null, "e": 27386, "s": 27367, "text": "unset ARRAYNAME[1]" }, { "code": null, "e": 27412, "s": 27386, "text": "To delete the whole Array" }, { "code": null, "e": 27428, "s": 27412, "text": "unset ARRAYNAME" }, { "code": "#! /bin/bash# To declare static Array arr=(prakhar ankit 1 rishabh manish abhinav) # To print all elements of arrayecho ${arr[@]} # prakhar ankit 1 rishabh manish abhinavecho ${arr[*]} # prakhar ankit 1 rishabh manish abhinavecho ${arr[@]:0} # prakhar ankit 1 rishabh manish abhinavecho ${arr[*]:0} # prakhar ankit 1 rishabh manish abhinav # To print first elementecho ${arr[0]} # prakharecho ${arr} # prakhar # To print particular elementecho ${arr[3]} # rishabhecho ${arr[1]} # ankit # To print elements from a particular indexecho ${arr[@]:0} # prakhar ankit 1 rishabh manish abhinavecho ${arr[@]:1} # ankit 1 rishabh manish abhinavecho ${arr[@]:2} # 1 rishabh manish abhinavecho ${arr[0]:1} # rakhar # To print elements in rangeecho ${arr[@]:1:4} # ankit 1 rishabh manishecho ${arr[@]:2:3} # 1 rishabh manishecho ${arr[0]:1:3} # rak # Length of Particular elementecho ${#arr[0]} # 7echo ${#arr} # 7 # Size of an Arrayecho ${#arr[@]} # 6echo ${#arr[*]} # 6 # Search in Arrayecho ${arr[@]/*[aA]*/} # 1 # Replacing Substring Temporaryecho ${arr[@]//a/A} # prAkhAr Ankit 1 rishAbh mAnish AbhinAvecho ${arr[@]} # prakhar ankit 1 rishabh manish abhinavecho ${arr[0]//r/R} # pRakhaR", "e": 28746, "s": 27428, "text": null }, { "code": null, "e": 28754, "s": 28746, "text": "Output:" }, { "code": null, "e": 29183, "s": 28754, "text": "prakhar ankit 1 rishabh manish abhinav\nprakhar ankit 1 rishabh manish abhinav\nprakhar ankit 1 rishabh manish abhinav\nprakhar ankit 1 rishabh manish abhinav\nprakhar\nprakhar\nrishabh\nankit\nprakhar ankit 1 rishabh manish abhinav\nankit 1 rishabh manish abhinav\n1 rishabh manish abhinav\nrakhar\nankit 1 rishabh manish\n1 rishabh manish\nrak\n7\n7\n6\n6\n1\nprAkhAr Ankit 1 rishAbh mAnish AbhinAv\nprakhar ankit 1 rishabh manish abhinav\npRakhaR\n" }, { "code": null, "e": 29263, "s": 29183, "text": "Reference:https://www.tecmint.com/working-with-arrays-in-linux-shell-scripting/" }, { "code": null, "e": 29276, "s": 29263, "text": "Shell Script" }, { "code": null, "e": 29287, "s": 29276, "text": "Linux-Unix" }, { "code": null, "e": 29385, "s": 29287, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29394, "s": 29385, "text": "Comments" }, { "code": null, "e": 29407, "s": 29394, "text": "Old Comments" }, { "code": null, "e": 29445, "s": 29407, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 29480, "s": 29445, "text": "tar command in Linux with examples" }, { "code": null, "e": 29516, "s": 29480, "text": "curl command in Linux with Examples" }, { "code": null, "e": 29554, "s": 29516, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 29592, "s": 29554, "text": "Conditional Statements | Shell Script" }, { "code": null, "e": 29627, "s": 29592, "text": "Cat command in Linux with examples" }, { "code": null, "e": 29663, "s": 29627, "text": "echo command in Linux with Examples" }, { "code": null, "e": 29700, "s": 29663, "text": "touch command in Linux with Examples" }, { "code": null, "e": 29736, "s": 29700, "text": "Tail command in Linux with examples" } ]
Create a similarity graph from node properties with Neo4j | by Nathan Smith | Towards Data Science
Cluster analysis helps us uncover structures hidden within data. We can use unsupervised machine learning algorithms to group data items into clusters so that items have more in common with other items inside their cluster than they do with items outside their cluster. Tasks such as customer segmentation, recommendation, and anomaly detection become easier when we organize a dataset into subsets of similar items. The concept of similarity lies at the heart of cluster analysis. The Neo4j Graph Data Science library gives us tools for discovering the similarity between nodes in a dataset based on the node’s properties, even if there aren’t preexisting relationships in our data. The Bloom graph visualization application then allows users to interactively explore similarity in an accessible, explainable way. This can help move unsupervised machine learning away from the realm of black box magic, towards being an intuitive tool for business users to employ. The Graph Data Science library subsequently allows us to find clusters of closely related nodes based on similarity relationships. This video below walks through the steps that we will follow in the rest of the article. For this example, I used data about metropolitan statistical areas (MSAs) from the 2019 American Community Survey five-year estimates provided by the United States Census Bureau. I selected four demographic features to describe each MSA: population, median household income, median home price, and the percent of the population over age 25 with a bachelors degree. In this tutorial, we will use a similarity algorithm to identify pairs of MSAs that are similar based on the four demographic features. Then, we will use the similarity relationships to identify clusters of MSAs. You can follow along with me by creating a free Neo4j sandbox. Choose to create a blank sandbox, because we will load our own data. Then click the “Open” button to launch Neo4j Browser to get started. Before we load data, we’ll create a unique constraint for the name of the MSA. CREATE CONSTRAINT msa_name ON (m:MSA) ASSERT m.name IS UNIQUE Use this command to load the MSA data from a CSV file on GitHub. LOAD CSV WITH HEADERS FROM "https://raw.githubusercontent.com/smithna/datasets/main/CensusDemographicsByMetroArea.csv" AS rowWITH row WHERE row.name CONTAINS 'Metro'MERGE (m:MSA {name:row.name})SET m.population = toInteger(row.population),m.medianHouseholdIncome = toInteger(row.medianHouseholdIncome),m.medianHomePrice = toInteger(row.medianHomePrice),m.percentOver25WithBachelors = toFloat(row.percentOver25WithBachelors)RETURN m Note that the LOAD CSV utility treats every field as a string, so we use toInteger() and toFloat() functions to convert the numeric values to the appropriate data type. After running the command, you should see that MSA nodes have been created. Unlike most Neo4j projects, we don’t have any relationships to load at the start. Instead, we’re going to use the Graph Data Science library to discover similar nodes and create relationships between them. We’ll define similarity based on Euclidean distance. The Euclidean distance formula is an extension of the Pythagorean theorem, which says that the square of the length hypotenuse of a right triangle is equal to the sum of the squares of the other two sides. In our case, we are comparing MSAs along four dimensions instead of two, but the concept is similar. The Euclidean distance between two MSAs is the square root of the sum of the squared differences along each of our demographic metrics. Before we calculate distance, we’ll want each of our four properties to have roughly the same range from the smallest value to the largest value. If there is a big difference in the ranges, then the properties with a big range will dominate the distance calculation; the properties with a small range will hardly influence the distance calculation at all. So we need to normalize all of them onto the same range. Run this query to see the range of values for each of the four properties that we loaded. MATCH (n)WITH n, ["population", "medianHouseholdIncome", "medianHomePrice", "percentOver25WithBachelors" ] AS metricsUNWIND metrics as metricWITH metric, n[metric] AS valueRETURN metric, min(value) AS minValue,percentileCont(value, 0.25) AS percentile25, percentileCont(value, 0.50) AS percentile50, percentileCont(value, 0.75) AS percentile75, max(value) AS maxValue The range of populations goes from 54,773 to 19,294,236. That’s a huge difference from the range of percent of people over 25 with a college degree, which runs from 12.9 to 67.4. We can also see that there is a much bigger difference between the 50th and 75th percentile for population (336,612 citizens) than there is between the 25th and 50th percentile (94,771.25 citizens). I downloaded the data and plotted histograms on both a standard scale and a logarithmic scale to examine the distributions. All of our metrics look like they approach a more normal distribution if we apply a log transformation. This makes sense to me on an intuitive level when I consider that adding 10,000 residents to an MSA with a population of 60,000 would be a big change to the character of the metro area, but adding 10,000 residents to an MSA with a population of 19 million would make a much smaller impact. On the other hand, a 10% change in population would be noticeable in an MSA of any scale. Run the command below to apply a log transformation to population, median home price, and percent of population over 25 with a bachelors degree. MATCH (m:MSA)SET m.logPopulation = log(m.population),m.logMedianHouseholdIncome = log(m.medianHouseholdIncome),m.logMedianHomePrice = log(m.medianHomePrice),m.logPercentOver25WithBachelors = log(m.percentOver25WithBachelors) The MinMax scaler in the Graph Data Science library will apply the formula below to rescale each property value. The minimum value is set to 0, the maximum value is set to 1, and all other values fall between 0 and 1 proportionally to their positions in the original data set. We’ll create an in-memory graph called “metro-graph” to efficiently perform the scaling calculation on all the nodes at once. We will load all nodes with the label MSA into the in-memory graph. Since we don’t have any relationships in our graph yet, we will use a * wildcard as a placeholder. CALL gds.graph.create('msa-graph', 'MSA', '*', {nodeProperties:["logPopulation", "logMedianHouseholdIncome", "logMedianHomePrice", "logPercentOver25WithBachelors"]}) Run the command below to create a new property in the in-memory graph called scaledProperties. The new property will be a vector (an ordered list) of four values: population, medianHouseholdIncome, medianHomePrice, percentOver25WithBachelors. The MinMax scaler will be applied to each property before it is added to the vector, so that all the values are within the range [0, 1]. call gds.alpha.scaleProperties.mutate('msa-graph', {nodeProperties: ["logPopulation", "logMedianHouseholdIncome", "logMedianHomePrice", "logPercentOver25WithBachelors"], scaler:"MinMax",mutateProperty: "scaledProperties"}) YIELD nodePropertiesWritten Now we’ll write those new properties from the in-memory graph back out to the main Neo4j graph. CALL gds.graph.writeNodeProperties('msa-graph',['scaledProperties']) We can use scaledProperties that we just created to calculate the distance between the nodes in our graph with the Euclidean distance procedure from the Graph Data Science library. The topK parameter tells the algorithm to create a relationship called IS_SIMILAR from each node to its 12 nearest neighbors. MATCH (m:MSA) WITH COLLECT({item:id(m), weights:m.scaledProperties}) AS dataCALL gds.alpha.similarity.euclidean.write({data:data, topK:12, writeRelationshipType:"IS_SIMILAR", writeProperty:"distance"})YIELD similarityPairs, min, max, mean, p50RETURN similarityPairs, min, max, mean, p50 The Euclidean distance algorithm tells us how far apart MSAs are in 4-dimensional space. The higher the value of the distance property, the less similar the two MSAs are. We’ll calculate a new similarity property by subtracting the distance from 1. We can see that the maximum distance was about 0.5, so we’ll always get a positive value for similarity. The higher the value of thesimilarity property, the more similar two MSAs are. MATCH (:MSA)-[s:IS_SIMILAR]->(:MSA)SET s.similarity = 1 - s.distance We added IS_SIMILAR relationships for the top 12 most similar MSAs to each MSA node. It might be convenient to be able to filter those relationships to the top 5 or some other top k. Run this query to add a ranking property to the relationships. MATCH (m:MSA)-[s:IS_SIMILAR]->()WITH m, s ORDER BY s.similarity DESCWITH m, collect(s) as similarities, range(0, 11) AS ranksUNWIND ranks AS rankWITH rank, similarities[rank] AS relSET rel.rank = rank + 1 Now let’s take a look at our graph in the Bloom graph visualization application. Go back to the Neo4j Sandbox home page and choose “Open with Bloom.” Sign in with the credentials for your Sandbox. Since this is our first time using Bloom with this dataset, click on “Create Perspective.” Then, click “Generate Perspective to let Bloom set up a perspective for you. Finally, click on your newly generated perspective to enter the Bloom scene. Let’s configure the display of the “IS_SIMILAR” relationships so that the line weight corresponds to the similarity of the nodes. Click Relationships on the panel at the right of the screen, and then click the line next to the “IS_SIMILAR” relationship. In the fly-out menu that appears, choose “Rule-based.” Then, click the plus sign to add a new rule-based style. Choose “similarity” from the property key drop down. Select the radio button for “range.” Click the “Size” button to create a rule that will control line weight. Toggle the button to apply the size rule. In the Minpoint box, enter 0.2 and set the minimum size to 0.25x. In the Maxpoint box, enter 1 and set the maximum size to 4x. Your configuration should look like the picture below. Now, let’s use Bloom to search for an MSA and its closest peers. If you start typing “New York” in the Bloom search box, Bloom’s auto-complete should suggest the “New York-Newark-Jersey City, NY-NJ-PA Metro Area.” Press tab to accept the suggestion. Once you have a node for New York’s MSA, Bloom will auto-suggest patterns involving that node. Choose the pattern that extends from the New York node with an IS_SIMILAR relationship, and press enter. Bloom will return a visualization showing the New York MSA and its 10 most similar MSAs based on the four demographic measures that we used. Based on the thickness of the outbound arrows, we can see that Los Angeles is the most similar MSA to New York. We might be surprised to see that there are relationships going both to and from New York and Los Angeles, Boston, Washington, and Seattle, but not the other cities in the visualization. We told the Euclidean distance algorithm to create relationships for the top 12 closest MSAs for each node. If I make a list of the 12 closest MSAs to New York, Atlanta is included. However, if I make a list of the 12 closest MSAs to Atlanta, New York does not make the cut. That is why there is a relationship directed from New York to Atlanta, but not a relationship directed from Atlanta to New York. Let’s filter the display to see the top 5 most similar cities to New York. Click the funnel icon on the left of the Bloom screen to expand the filter panel. Choose IS_SIMILAR in the dropdown. Select the “rank” property. Select the “less than or equal to” condition, and set the value to 5. Toggle “Apply Filter” to highlight the top 5 strongest similarity relationships for New York. We’ve explored the neighbors of a single MSA. Let’s now look at the big picture. Right click the Bloom canvas and choose “Clear scene” from the context menu. In the search box, enter “MSA” and press tab. Select the (MSA)-IS_SIMILAR-() pattern, and press enter. We’ll see the whole MSA graph. Open the filter panel again. Create a new filter on the IS_SIMILAR relationships for “similarity” greater than or equal to 0.8. Toggle “Apply Filter,” and then click the “Dismiss Filtered elements” button at the bottom of the panel. We start to see some islands and peninsulas differentiate from the main group of nodes. There are two outlier nodes where none of their 12 most similar neighbors have similarity greater than 0.8. We’ll probe the structure of the graph further with community detection algorithms. Go back to Neo4j Browser to run the following commands for community detection. Create a new in-memory graph that contains the MSA nodes and the IS_SIMILAR relationships. We also want to include the similarity property on the relationships. CALL gds.graph.create('msa-similarity','MSA','IS_SIMILAR',{relationshipProperties: ['similarity']}) Now, we will execute the Louvain community detection algorithm against the in-memory graph and write the community ids back to the main Neo4j graph. We tell the algorithm to use the similarity property to weight the relationships between nodes. By setting the consecutiveIds parameter to true, we tell the algorithm that we want the values of the communityId property that are generated to be consecutive integers. CALL gds.louvain.write('msa-similarity',{relationshipWeightProperty:"similarity", writeProperty:"communityId",consecutiveIds:true})YIELD communityCount, modularitiesRETURN communityCount, modularities The output shows us that 6 communities were detected. Successive iterations of the algorithm increased the modularity of the community partitions from 0.625 to 0.667. Run the query below to gather summary statistics about the communities we have defined. In addition to statistics, we’re adding context by listing the three MSAs in each community with the highest similarity to other MSAs in the same community. These MSAs should be typical examples of their community, as opposed to other MSAs that might have fewer or weaker in-community relationships. MATCH (m:MSA)WITH m ORDER BY apoc.coll.sum([(m)-[s:IS_SIMILAR]->(m2) WHERE m.communityId = m2.communityId | s.similarity]) descRETURN m.communityId as communityId,count(m) as msaCount, avg(m.population) as avgPopulation,avg(m.medianHomePrice) as avgHomePrice,avg(m.medianHouseholdIncome) as avgIncome,avg(m.percentOver25WithBachelors) as avgPctBachelors,collect(m.name)[..3] as exampleMSAsORDER BY avgPopulation DESC The community with id 1 has the largest MSAs, with average population over 2 million. Community 3 is mid-sized MSAs with low home prices. Community 5 is mid-sized cities with high home prices. Community 4 is smaller MSAs with highly educated populations. Community 2 is small MSAs with moderate income and home prices, and community 0 is small MSAs with low income and home prices. Let’s give the communities names that are more human friendly than the auto-generated ids. MATCH (m:MSA) SET m.communityName = CASE m.communityId WHEN 1 THEN "Large metros" WHEN 3 THEN "Medium metros" WHEN 5 THEN "Medium high-cost metros" WHEN 4 THEN "College towns" WHEN 2 THEN "Small middle-income metros" WHEN 0 THEN "Small low-income metros" ENDreturn m.communityName, m.communityId, count(*) To make the communityName property searchable in Bloom, create an index on that property. CREATE INDEX msa_community_name IF NOT EXISTSFOR (m:MSA)ON (m.communityName) Let’s take a look at the results in Bloom. We’ll configure the perspective to reflect the new communities we have added. Click the icon in the top left of the screen to open the perspectives panel. Then, click the database icon to refresh the perspective to include the new communityName property we added to the database. In the panel on the right side of the screen, click on the circle next to MSA to style the MSA nodes. In the fly-out menu that appears, choose “Rule-based.” Then, click the plus sign to add a new rule-based style. Choose “communityName” from the property key drop down. Select the radio button for “unique values.” Toggle the button to apply the color rule. Let’s add a second conditional style to set the size of the nodes based on population. Click the plus to add a new rule-based styling rule. Choose “population” from the property-key drop down. Select the radio button for “range.” Click the “size” button to create a rule that will control node size. Toggle the button to apply the size rule. In the Minpoint box, enter 55000 and set the minimum size to 1x. In the Maxpoint box, enter 19000000 and set the maximum size to 4x. Your configuration should look like the box below. Now right click and choose “Clear Scene” from the context menu. In the search box, type “College towns” and press enter. Among the results that are returned are the State College, PA Metro, the Ithaca, NY Metro, the Champaign-Urbana, IL Metro, and the Charlottesville, VA Metro. Those metro areas are home to Pennsylvania State University, Cornell University, the University of Illinois, and the University of Virginia. Based on what we know of those metro areas, it seems like the algorithm has picked up some clear commonalities. Let’s see which other metros are most similar to the college towns. Click Command-A to select all the nodes. Then right click one of the nodes and chose Expand: <-IS_SIMILAR- from the context menu. When I zoom out, I can see that we have added several large metro areas (purple), medium metro areas (orange), small middle-income areas (teal), and one medium high-cost metro (red). Double click on a node or zoom in to see the node details. Several MSAs that we have added, such as Madison, WI Metro Area and Durham-Chappel Hill, NC happen to be home to major universities. Experiment with this dataset to explore similarity graphs further. Decreasing the number of similarity relationships created by decreasing the topK parameter or setting the similarityThreshold parameter when you run gds.alpha.similarity.euclidean will tend to result in more communities when you run gds.louvain. Try scalers other than MinMax when you run gds.alpha.scaleProperties. The graph data science library supports several other similarity algorithms. The K-Nearest Neighbors algorithm provides an efficient way to generate links based on cosine similarity. Louvain community detection is one option among several community detection algorithms. See how different your results are by running the Label Propagation algorithm. The data CSV on GitHub includes micropolitan statistical areas in addition to metropolitan statistical areas. Remove WHERE row.name INCLUDES 'Metro' from the LOAD CSV script to load these nodes and explore their properties. You’ll find that graphs really are everywhere, even when relationships are not apparent in the data model at first.
[ { "code": null, "e": 442, "s": 172, "text": "Cluster analysis helps us uncover structures hidden within data. We can use unsupervised machine learning algorithms to group data items into clusters so that items have more in common with other items inside their cluster than they do with items outside their cluster." }, { "code": null, "e": 589, "s": 442, "text": "Tasks such as customer segmentation, recommendation, and anomaly detection become easier when we organize a dataset into subsets of similar items." }, { "code": null, "e": 856, "s": 589, "text": "The concept of similarity lies at the heart of cluster analysis. The Neo4j Graph Data Science library gives us tools for discovering the similarity between nodes in a dataset based on the node’s properties, even if there aren’t preexisting relationships in our data." }, { "code": null, "e": 1269, "s": 856, "text": "The Bloom graph visualization application then allows users to interactively explore similarity in an accessible, explainable way. This can help move unsupervised machine learning away from the realm of black box magic, towards being an intuitive tool for business users to employ. The Graph Data Science library subsequently allows us to find clusters of closely related nodes based on similarity relationships." }, { "code": null, "e": 1358, "s": 1269, "text": "This video below walks through the steps that we will follow in the rest of the article." }, { "code": null, "e": 1537, "s": 1358, "text": "For this example, I used data about metropolitan statistical areas (MSAs) from the 2019 American Community Survey five-year estimates provided by the United States Census Bureau." }, { "code": null, "e": 1596, "s": 1537, "text": "I selected four demographic features to describe each MSA:" }, { "code": null, "e": 1608, "s": 1596, "text": "population," }, { "code": null, "e": 1633, "s": 1608, "text": "median household income," }, { "code": null, "e": 1656, "s": 1633, "text": "median home price, and" }, { "code": null, "e": 1723, "s": 1656, "text": "the percent of the population over age 25 with a bachelors degree." }, { "code": null, "e": 1936, "s": 1723, "text": "In this tutorial, we will use a similarity algorithm to identify pairs of MSAs that are similar based on the four demographic features. Then, we will use the similarity relationships to identify clusters of MSAs." }, { "code": null, "e": 2137, "s": 1936, "text": "You can follow along with me by creating a free Neo4j sandbox. Choose to create a blank sandbox, because we will load our own data. Then click the “Open” button to launch Neo4j Browser to get started." }, { "code": null, "e": 2216, "s": 2137, "text": "Before we load data, we’ll create a unique constraint for the name of the MSA." }, { "code": null, "e": 2278, "s": 2216, "text": "CREATE CONSTRAINT msa_name ON (m:MSA) ASSERT m.name IS UNIQUE" }, { "code": null, "e": 2343, "s": 2278, "text": "Use this command to load the MSA data from a CSV file on GitHub." }, { "code": null, "e": 2775, "s": 2343, "text": "LOAD CSV WITH HEADERS FROM \"https://raw.githubusercontent.com/smithna/datasets/main/CensusDemographicsByMetroArea.csv\" AS rowWITH row WHERE row.name CONTAINS 'Metro'MERGE (m:MSA {name:row.name})SET m.population = toInteger(row.population),m.medianHouseholdIncome = toInteger(row.medianHouseholdIncome),m.medianHomePrice = toInteger(row.medianHomePrice),m.percentOver25WithBachelors = toFloat(row.percentOver25WithBachelors)RETURN m" }, { "code": null, "e": 3020, "s": 2775, "text": "Note that the LOAD CSV utility treats every field as a string, so we use toInteger() and toFloat() functions to convert the numeric values to the appropriate data type. After running the command, you should see that MSA nodes have been created." }, { "code": null, "e": 3226, "s": 3020, "text": "Unlike most Neo4j projects, we don’t have any relationships to load at the start. Instead, we’re going to use the Graph Data Science library to discover similar nodes and create relationships between them." }, { "code": null, "e": 3485, "s": 3226, "text": "We’ll define similarity based on Euclidean distance. The Euclidean distance formula is an extension of the Pythagorean theorem, which says that the square of the length hypotenuse of a right triangle is equal to the sum of the squares of the other two sides." }, { "code": null, "e": 3722, "s": 3485, "text": "In our case, we are comparing MSAs along four dimensions instead of two, but the concept is similar. The Euclidean distance between two MSAs is the square root of the sum of the squared differences along each of our demographic metrics." }, { "code": null, "e": 4135, "s": 3722, "text": "Before we calculate distance, we’ll want each of our four properties to have roughly the same range from the smallest value to the largest value. If there is a big difference in the ranges, then the properties with a big range will dominate the distance calculation; the properties with a small range will hardly influence the distance calculation at all. So we need to normalize all of them onto the same range." }, { "code": null, "e": 4225, "s": 4135, "text": "Run this query to see the range of values for each of the four properties that we loaded." }, { "code": null, "e": 4593, "s": 4225, "text": "MATCH (n)WITH n, [\"population\", \"medianHouseholdIncome\", \"medianHomePrice\", \"percentOver25WithBachelors\" ] AS metricsUNWIND metrics as metricWITH metric, n[metric] AS valueRETURN metric, min(value) AS minValue,percentileCont(value, 0.25) AS percentile25, percentileCont(value, 0.50) AS percentile50, percentileCont(value, 0.75) AS percentile75, max(value) AS maxValue" }, { "code": null, "e": 4772, "s": 4593, "text": "The range of populations goes from 54,773 to 19,294,236. That’s a huge difference from the range of percent of people over 25 with a college degree, which runs from 12.9 to 67.4." }, { "code": null, "e": 5095, "s": 4772, "text": "We can also see that there is a much bigger difference between the 50th and 75th percentile for population (336,612 citizens) than there is between the 25th and 50th percentile (94,771.25 citizens). I downloaded the data and plotted histograms on both a standard scale and a logarithmic scale to examine the distributions." }, { "code": null, "e": 5579, "s": 5095, "text": "All of our metrics look like they approach a more normal distribution if we apply a log transformation. This makes sense to me on an intuitive level when I consider that adding 10,000 residents to an MSA with a population of 60,000 would be a big change to the character of the metro area, but adding 10,000 residents to an MSA with a population of 19 million would make a much smaller impact. On the other hand, a 10% change in population would be noticeable in an MSA of any scale." }, { "code": null, "e": 5724, "s": 5579, "text": "Run the command below to apply a log transformation to population, median home price, and percent of population over 25 with a bachelors degree." }, { "code": null, "e": 5949, "s": 5724, "text": "MATCH (m:MSA)SET m.logPopulation = log(m.population),m.logMedianHouseholdIncome = log(m.medianHouseholdIncome),m.logMedianHomePrice = log(m.medianHomePrice),m.logPercentOver25WithBachelors = log(m.percentOver25WithBachelors)" }, { "code": null, "e": 6226, "s": 5949, "text": "The MinMax scaler in the Graph Data Science library will apply the formula below to rescale each property value. The minimum value is set to 0, the maximum value is set to 1, and all other values fall between 0 and 1 proportionally to their positions in the original data set." }, { "code": null, "e": 6519, "s": 6226, "text": "We’ll create an in-memory graph called “metro-graph” to efficiently perform the scaling calculation on all the nodes at once. We will load all nodes with the label MSA into the in-memory graph. Since we don’t have any relationships in our graph yet, we will use a * wildcard as a placeholder." }, { "code": null, "e": 6685, "s": 6519, "text": "CALL gds.graph.create('msa-graph', 'MSA', '*', {nodeProperties:[\"logPopulation\", \"logMedianHouseholdIncome\", \"logMedianHomePrice\", \"logPercentOver25WithBachelors\"]})" }, { "code": null, "e": 7065, "s": 6685, "text": "Run the command below to create a new property in the in-memory graph called scaledProperties. The new property will be a vector (an ordered list) of four values: population, medianHouseholdIncome, medianHomePrice, percentOver25WithBachelors. The MinMax scaler will be applied to each property before it is added to the vector, so that all the values are within the range [0, 1]." }, { "code": null, "e": 7316, "s": 7065, "text": "call gds.alpha.scaleProperties.mutate('msa-graph', {nodeProperties: [\"logPopulation\", \"logMedianHouseholdIncome\", \"logMedianHomePrice\", \"logPercentOver25WithBachelors\"], scaler:\"MinMax\",mutateProperty: \"scaledProperties\"}) YIELD nodePropertiesWritten" }, { "code": null, "e": 7412, "s": 7316, "text": "Now we’ll write those new properties from the in-memory graph back out to the main Neo4j graph." }, { "code": null, "e": 7481, "s": 7412, "text": "CALL gds.graph.writeNodeProperties('msa-graph',['scaledProperties'])" }, { "code": null, "e": 7788, "s": 7481, "text": "We can use scaledProperties that we just created to calculate the distance between the nodes in our graph with the Euclidean distance procedure from the Graph Data Science library. The topK parameter tells the algorithm to create a relationship called IS_SIMILAR from each node to its 12 nearest neighbors." }, { "code": null, "e": 8075, "s": 7788, "text": "MATCH (m:MSA) WITH COLLECT({item:id(m), weights:m.scaledProperties}) AS dataCALL gds.alpha.similarity.euclidean.write({data:data, topK:12, writeRelationshipType:\"IS_SIMILAR\", writeProperty:\"distance\"})YIELD similarityPairs, min, max, mean, p50RETURN similarityPairs, min, max, mean, p50" }, { "code": null, "e": 8508, "s": 8075, "text": "The Euclidean distance algorithm tells us how far apart MSAs are in 4-dimensional space. The higher the value of the distance property, the less similar the two MSAs are. We’ll calculate a new similarity property by subtracting the distance from 1. We can see that the maximum distance was about 0.5, so we’ll always get a positive value for similarity. The higher the value of thesimilarity property, the more similar two MSAs are." }, { "code": null, "e": 8577, "s": 8508, "text": "MATCH (:MSA)-[s:IS_SIMILAR]->(:MSA)SET s.similarity = 1 - s.distance" }, { "code": null, "e": 8823, "s": 8577, "text": "We added IS_SIMILAR relationships for the top 12 most similar MSAs to each MSA node. It might be convenient to be able to filter those relationships to the top 5 or some other top k. Run this query to add a ranking property to the relationships." }, { "code": null, "e": 9028, "s": 8823, "text": "MATCH (m:MSA)-[s:IS_SIMILAR]->()WITH m, s ORDER BY s.similarity DESCWITH m, collect(s) as similarities, range(0, 11) AS ranksUNWIND ranks AS rankWITH rank, similarities[rank] AS relSET rel.rank = rank + 1" }, { "code": null, "e": 9178, "s": 9028, "text": "Now let’s take a look at our graph in the Bloom graph visualization application. Go back to the Neo4j Sandbox home page and choose “Open with Bloom.”" }, { "code": null, "e": 9470, "s": 9178, "text": "Sign in with the credentials for your Sandbox. Since this is our first time using Bloom with this dataset, click on “Create Perspective.” Then, click “Generate Perspective to let Bloom set up a perspective for you. Finally, click on your newly generated perspective to enter the Bloom scene." }, { "code": null, "e": 9724, "s": 9470, "text": "Let’s configure the display of the “IS_SIMILAR” relationships so that the line weight corresponds to the similarity of the nodes. Click Relationships on the panel at the right of the screen, and then click the line next to the “IS_SIMILAR” relationship." }, { "code": null, "e": 9836, "s": 9724, "text": "In the fly-out menu that appears, choose “Rule-based.” Then, click the plus sign to add a new rule-based style." }, { "code": null, "e": 10040, "s": 9836, "text": "Choose “similarity” from the property key drop down. Select the radio button for “range.” Click the “Size” button to create a rule that will control line weight. Toggle the button to apply the size rule." }, { "code": null, "e": 10222, "s": 10040, "text": "In the Minpoint box, enter 0.2 and set the minimum size to 0.25x. In the Maxpoint box, enter 1 and set the maximum size to 4x. Your configuration should look like the picture below." }, { "code": null, "e": 10672, "s": 10222, "text": "Now, let’s use Bloom to search for an MSA and its closest peers. If you start typing “New York” in the Bloom search box, Bloom’s auto-complete should suggest the “New York-Newark-Jersey City, NY-NJ-PA Metro Area.” Press tab to accept the suggestion. Once you have a node for New York’s MSA, Bloom will auto-suggest patterns involving that node. Choose the pattern that extends from the New York node with an IS_SIMILAR relationship, and press enter." }, { "code": null, "e": 10813, "s": 10672, "text": "Bloom will return a visualization showing the New York MSA and its 10 most similar MSAs based on the four demographic measures that we used." }, { "code": null, "e": 10925, "s": 10813, "text": "Based on the thickness of the outbound arrows, we can see that Los Angeles is the most similar MSA to New York." }, { "code": null, "e": 11516, "s": 10925, "text": "We might be surprised to see that there are relationships going both to and from New York and Los Angeles, Boston, Washington, and Seattle, but not the other cities in the visualization. We told the Euclidean distance algorithm to create relationships for the top 12 closest MSAs for each node. If I make a list of the 12 closest MSAs to New York, Atlanta is included. However, if I make a list of the 12 closest MSAs to Atlanta, New York does not make the cut. That is why there is a relationship directed from New York to Atlanta, but not a relationship directed from Atlanta to New York." }, { "code": null, "e": 11900, "s": 11516, "text": "Let’s filter the display to see the top 5 most similar cities to New York. Click the funnel icon on the left of the Bloom screen to expand the filter panel. Choose IS_SIMILAR in the dropdown. Select the “rank” property. Select the “less than or equal to” condition, and set the value to 5. Toggle “Apply Filter” to highlight the top 5 strongest similarity relationships for New York." }, { "code": null, "e": 12192, "s": 11900, "text": "We’ve explored the neighbors of a single MSA. Let’s now look at the big picture. Right click the Bloom canvas and choose “Clear scene” from the context menu. In the search box, enter “MSA” and press tab. Select the (MSA)-IS_SIMILAR-() pattern, and press enter. We’ll see the whole MSA graph." }, { "code": null, "e": 12705, "s": 12192, "text": "Open the filter panel again. Create a new filter on the IS_SIMILAR relationships for “similarity” greater than or equal to 0.8. Toggle “Apply Filter,” and then click the “Dismiss Filtered elements” button at the bottom of the panel. We start to see some islands and peninsulas differentiate from the main group of nodes. There are two outlier nodes where none of their 12 most similar neighbors have similarity greater than 0.8. We’ll probe the structure of the graph further with community detection algorithms." }, { "code": null, "e": 12785, "s": 12705, "text": "Go back to Neo4j Browser to run the following commands for community detection." }, { "code": null, "e": 12946, "s": 12785, "text": "Create a new in-memory graph that contains the MSA nodes and the IS_SIMILAR relationships. We also want to include the similarity property on the relationships." }, { "code": null, "e": 13046, "s": 12946, "text": "CALL gds.graph.create('msa-similarity','MSA','IS_SIMILAR',{relationshipProperties: ['similarity']})" }, { "code": null, "e": 13461, "s": 13046, "text": "Now, we will execute the Louvain community detection algorithm against the in-memory graph and write the community ids back to the main Neo4j graph. We tell the algorithm to use the similarity property to weight the relationships between nodes. By setting the consecutiveIds parameter to true, we tell the algorithm that we want the values of the communityId property that are generated to be consecutive integers." }, { "code": null, "e": 13662, "s": 13461, "text": "CALL gds.louvain.write('msa-similarity',{relationshipWeightProperty:\"similarity\", writeProperty:\"communityId\",consecutiveIds:true})YIELD communityCount, modularitiesRETURN communityCount, modularities" }, { "code": null, "e": 13829, "s": 13662, "text": "The output shows us that 6 communities were detected. Successive iterations of the algorithm increased the modularity of the community partitions from 0.625 to 0.667." }, { "code": null, "e": 14217, "s": 13829, "text": "Run the query below to gather summary statistics about the communities we have defined. In addition to statistics, we’re adding context by listing the three MSAs in each community with the highest similarity to other MSAs in the same community. These MSAs should be typical examples of their community, as opposed to other MSAs that might have fewer or weaker in-community relationships." }, { "code": null, "e": 14634, "s": 14217, "text": "MATCH (m:MSA)WITH m ORDER BY apoc.coll.sum([(m)-[s:IS_SIMILAR]->(m2) WHERE m.communityId = m2.communityId | s.similarity]) descRETURN m.communityId as communityId,count(m) as msaCount, avg(m.population) as avgPopulation,avg(m.medianHomePrice) as avgHomePrice,avg(m.medianHouseholdIncome) as avgIncome,avg(m.percentOver25WithBachelors) as avgPctBachelors,collect(m.name)[..3] as exampleMSAsORDER BY avgPopulation DESC" }, { "code": null, "e": 15016, "s": 14634, "text": "The community with id 1 has the largest MSAs, with average population over 2 million. Community 3 is mid-sized MSAs with low home prices. Community 5 is mid-sized cities with high home prices. Community 4 is smaller MSAs with highly educated populations. Community 2 is small MSAs with moderate income and home prices, and community 0 is small MSAs with low income and home prices." }, { "code": null, "e": 15107, "s": 15016, "text": "Let’s give the communities names that are more human friendly than the auto-generated ids." }, { "code": null, "e": 15423, "s": 15107, "text": "MATCH (m:MSA) SET m.communityName = CASE m.communityId WHEN 1 THEN \"Large metros\" WHEN 3 THEN \"Medium metros\" WHEN 5 THEN \"Medium high-cost metros\" WHEN 4 THEN \"College towns\" WHEN 2 THEN \"Small middle-income metros\" WHEN 0 THEN \"Small low-income metros\" ENDreturn m.communityName, m.communityId, count(*)" }, { "code": null, "e": 15513, "s": 15423, "text": "To make the communityName property searchable in Bloom, create an index on that property." }, { "code": null, "e": 15590, "s": 15513, "text": "CREATE INDEX msa_community_name IF NOT EXISTSFOR (m:MSA)ON (m.communityName)" }, { "code": null, "e": 15913, "s": 15590, "text": "Let’s take a look at the results in Bloom. We’ll configure the perspective to reflect the new communities we have added. Click the icon in the top left of the screen to open the perspectives panel. Then, click the database icon to refresh the perspective to include the new communityName property we added to the database." }, { "code": null, "e": 16271, "s": 15913, "text": "In the panel on the right side of the screen, click on the circle next to MSA to style the MSA nodes. In the fly-out menu that appears, choose “Rule-based.” Then, click the plus sign to add a new rule-based style. Choose “communityName” from the property key drop down. Select the radio button for “unique values.” Toggle the button to apply the color rule." }, { "code": null, "e": 16411, "s": 16271, "text": "Let’s add a second conditional style to set the size of the nodes based on population. Click the plus to add a new rule-based styling rule." }, { "code": null, "e": 16613, "s": 16411, "text": "Choose “population” from the property-key drop down. Select the radio button for “range.” Click the “size” button to create a rule that will control node size. Toggle the button to apply the size rule." }, { "code": null, "e": 16797, "s": 16613, "text": "In the Minpoint box, enter 55000 and set the minimum size to 1x. In the Maxpoint box, enter 19000000 and set the maximum size to 4x. Your configuration should look like the box below." }, { "code": null, "e": 17329, "s": 16797, "text": "Now right click and choose “Clear Scene” from the context menu. In the search box, type “College towns” and press enter. Among the results that are returned are the State College, PA Metro, the Ithaca, NY Metro, the Champaign-Urbana, IL Metro, and the Charlottesville, VA Metro. Those metro areas are home to Pennsylvania State University, Cornell University, the University of Illinois, and the University of Virginia. Based on what we know of those metro areas, it seems like the algorithm has picked up some clear commonalities." }, { "code": null, "e": 17527, "s": 17329, "text": "Let’s see which other metros are most similar to the college towns. Click Command-A to select all the nodes. Then right click one of the nodes and chose Expand: <-IS_SIMILAR- from the context menu." }, { "code": null, "e": 17902, "s": 17527, "text": "When I zoom out, I can see that we have added several large metro areas (purple), medium metro areas (orange), small middle-income areas (teal), and one medium high-cost metro (red). Double click on a node or zoom in to see the node details. Several MSAs that we have added, such as Madison, WI Metro Area and Durham-Chappel Hill, NC happen to be home to major universities." }, { "code": null, "e": 18285, "s": 17902, "text": "Experiment with this dataset to explore similarity graphs further. Decreasing the number of similarity relationships created by decreasing the topK parameter or setting the similarityThreshold parameter when you run gds.alpha.similarity.euclidean will tend to result in more communities when you run gds.louvain. Try scalers other than MinMax when you run gds.alpha.scaleProperties." }, { "code": null, "e": 18468, "s": 18285, "text": "The graph data science library supports several other similarity algorithms. The K-Nearest Neighbors algorithm provides an efficient way to generate links based on cosine similarity." }, { "code": null, "e": 18635, "s": 18468, "text": "Louvain community detection is one option among several community detection algorithms. See how different your results are by running the Label Propagation algorithm." }, { "code": null, "e": 18859, "s": 18635, "text": "The data CSV on GitHub includes micropolitan statistical areas in addition to metropolitan statistical areas. Remove WHERE row.name INCLUDES 'Metro' from the LOAD CSV script to load these nodes and explore their properties." } ]
Linear Algebra - GeeksforGeeks
21 Jan, 2014 Which one of the following does NOT equal to C D B A First of all, you should know the basic properties of determinants before approaching For these kind of problems. 1) Applying any row or column transformation does not change the determinant 2) If you interchange any two rows, sign of the determinant will change A = | 1 x x^2 | | 1 y y^2 | | 1 z z^2 | To prove option (b) => Apply column transformation C2 -> C2+C1 C3 -> C3+C1 => det(A) = | 1 x+1 x^2+1 | | 1 y+1 y^2+1 | | 1 z+1 z^2+1 | To prove option (c), => Apply row transformations R1 -> R1-R2 R2 -> R2-R3 => det(A) = | 0 x-y x^2-y^2 | | 0 y-z y^2-z^2 | | 1 z z^2 | To prove option (d), => Apply row transformations R1 -> R1+R2 R2 -> R2+R3 => det(A) = | 2 x+y x^2+y^2 | | 2 y+z y^2+z^2 | | 1 z z^2 | A = 1 1 1 -1 A2 = 2 0 0 2 A4 = A2 X A2 A4 = 4 0 0 4 A8 = 16 0 0 16 A16 = 256 0 0 256 A18 = A16 X A2 A18 = 512 0 0 512 A19 = 512 512 512 -512 Applying Characteristic polynomial 512-lamda 512 512 -(512+lamda) = 0 -(512-lamda)(512+lamda) - 512 x 512 = 0 lamda2 = 2 x 5122 det(A) = -2. det(A^19) = (det(A))^19 = -2^19 = lambda1*lambda2. The only viable option is D. The Eigen values of a triangular matrix are given by its diagonal entries. We can also calculate (or verify given answers) using characteristic equation obtained by |M - λI| = 0. 1-λ 2 3 0 4-λ 7 = 0 0 0 3-λ Which means (1-λ)(4-λ)(3-λ) = 0 Consider the following matrix A = If the eigenvalues of A are 4 and 8, then x=-3, y=9 x= -4, y=10 x=5, y=8 x=4, y=10 How many of the following matrices have an eigenvalue 1? three four two one 1 0 0 0 1 0 1 1 1 0 0 1 1 1 0 0 1 1 1 0 1 0 0 0 1 Which one of the following statements is TRUE about every If the trace of the matrix is positive and the determinant of the matrix is negative, at least one of its eigenvalues is negative. If the product of the trace and determinant of the matrix is positive, all its eigenvalues are positive. If the trace of the matrix is positive, all its eigenvalues are positive. If the determinant of the matrix is positive, all its eigenvalues are positive. The trace of a matrix is the sum of the elements of the principal diagonal of the matrix. Fact - The sum of Eigen values of a matrix is equal to it’s trace. Fact - The product of Eigen values of a matrix is equal to its determinant value. Since it’s given that the trace is positive and the determinant is negative, there must be atleast one negative Eigen value. In general there can be an odd number of negative Eigen values in this case since the determinant value is negative. Consider the set H of all 3 × 3 matrices of the type where a, b, c, d, e and f are real numbers and abc ≠ 0. Under the matrix multiplication operation, the set H is a group a monoid but not a group a semigroup but not a monoid neither a group nor a semigroup Because identity matrix is identity & as they define abc != 0, then it is non-singular so inverse is also defined. The set of matrices is the set of Upper triangular matrices(H) of size 3*3 with non-zero determinant. Along with the multiplication operator the set forms an Algebraic Structure since it follows the Closure Property. This is because the product of Two Upper Triangular Matrices is also a Upper Triangular Matrix. The Algebraic Structure also follows the Associative Property since, multiplication of matrices in general follows the Associative Property. Therefore it is a Semi Group. The Algebraic Structure is also a Monoid, since it has an Identity element, which is the Identity Matrix- I3. The Algebraic Structure is a Group since every matrix in H has an inverse, since every matrix in H is non-singular (given in question). The Algebraic Structure is not an Abelian Group since it does not follow the Commutative Property. Therefore Option A is correct. Consider the matrix as A | A | = 2 ( 2 -20 ) +1 ( 3 + 5 ) + 3 ( 12 + 2 ) = 36 + 8+ 42 = 86 The determinant value of following matrix is non-zero, therefore we have a unique solution. 2 -1 3 3 -2 5 -1 4 1 Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between sh and bash Create a dictionary with list comprehension in Python Converting an image to a Torch Tensor in Python How to Calculate Cosine Similarity in Python? 10 Best C and C++ Books For Beginners & Advanced Programmers Show all columns of Pandas DataFrame in Jupyter Notebook How to split a Dataset into Train and Test Sets using Python How to Read JSON Files with Pandas? How to Add a Title to Seaborn Plots? How to Read Text Files with Pandas?
[ { "code": null, "e": 29928, "s": 29900, "text": "\n21 Jan, 2014" }, { "code": null, "e": 29974, "s": 29928, "text": "Which one of the following does NOT equal to " }, { "code": null, "e": 29981, "s": 29978, "text": "C " }, { "code": null, "e": 29984, "s": 29981, "text": "D " }, { "code": null, "e": 29987, "s": 29984, "text": "B " }, { "code": null, "e": 29990, "s": 29987, "text": "A " }, { "code": null, "e": 30257, "s": 29994, "text": "First of all, you should know the basic properties of determinants before approaching For these kind of problems. 1) Applying any row or column transformation does not change the determinant 2) If you interchange any two rows, sign of the determinant will change" }, { "code": null, "e": 30301, "s": 30261, "text": "A = | 1 x x^2 | | 1 y y^2 | | 1 z z^2 |" }, { "code": null, "e": 30323, "s": 30303, "text": "To prove option (b)" }, { "code": null, "e": 30368, "s": 30325, "text": "=> Apply column transformation C2 -> C2+C1" }, { "code": null, "e": 30382, "s": 30370, "text": "C3 -> C3+C1" }, { "code": null, "e": 30444, "s": 30384, "text": "=> det(A) = | 1 x+1 x^2+1 | | 1 y+1 y^2+1 | | 1 z+1 z^2+1 |" }, { "code": null, "e": 30467, "s": 30446, "text": "To prove option (c)," }, { "code": null, "e": 30510, "s": 30469, "text": "=> Apply row transformations R1 -> R1-R2" }, { "code": null, "e": 30524, "s": 30512, "text": "R2 -> R2-R3" }, { "code": null, "e": 30586, "s": 30526, "text": "=> det(A) = | 0 x-y x^2-y^2 | | 0 y-z y^2-z^2 | | 1 z z^2 |" }, { "code": null, "e": 30609, "s": 30588, "text": "To prove option (d)," }, { "code": null, "e": 30652, "s": 30611, "text": "=> Apply row transformations R1 -> R1+R2" }, { "code": null, "e": 30666, "s": 30654, "text": "R2 -> R2+R3" }, { "code": null, "e": 30728, "s": 30668, "text": "=> det(A) = | 2 x+y x^2+y^2 | | 2 y+z y^2+z^2 | | 1 z z^2 |" }, { "code": null, "e": 31160, "s": 30730, "text": "A = 1 1\n 1 -1\n\nA2 = 2 0\n 0 2\n\nA4 = A2 X A2\nA4 = 4 0\n 0 4\n\nA8 = 16 0\n 0 16\n\n\nA16 = 256 0\n 0 256\n\nA18 = A16 X A2\nA18 = 512 0\n 0 512 \n\nA19 = 512 512\n 512 -512\n\n\nApplying Characteristic polynomial\n\n512-lamda 512\n512 -(512+lamda) = 0\n\n-(512-lamda)(512+lamda) - 512 x 512 = 0\n\nlamda2 = 2 x 5122 " }, { "code": null, "e": 31254, "s": 31160, "text": "det(A) = -2.\ndet(A^19) = (det(A))^19 = -2^19 = lambda1*lambda2.\nThe only viable option is D. " }, { "code": null, "e": 31433, "s": 31254, "text": "The Eigen values of a triangular matrix are given by its diagonal entries. We can also calculate (or verify given answers) using characteristic equation obtained by |M - λI| = 0." }, { "code": null, "e": 31450, "s": 31435, "text": "1-λ 2 3" }, { "code": null, "e": 31485, "s": 31450, "text": "0 4-λ 7 = 0" }, { "code": null, "e": 31503, "s": 31485, "text": "0 0 3-λ " }, { "code": null, "e": 31515, "s": 31503, "text": "Which means" }, { "code": null, "e": 31535, "s": 31515, "text": "(1-λ)(4-λ)(3-λ) = 0" }, { "code": null, "e": 31570, "s": 31535, "text": "Consider the following matrix A = " }, { "code": null, "e": 31614, "s": 31570, "text": "If the eigenvalues of A are 4 and 8, then " }, { "code": null, "e": 31625, "s": 31614, "text": "x=-3, y=9 " }, { "code": null, "e": 31638, "s": 31625, "text": "x= -4, y=10 " }, { "code": null, "e": 31648, "s": 31638, "text": "x=5, y=8 " }, { "code": null, "e": 31659, "s": 31648, "text": "x=4, y=10 " }, { "code": null, "e": 31716, "s": 31659, "text": "How many of the following matrices have an eigenvalue 1?" }, { "code": null, "e": 31723, "s": 31716, "text": "three " }, { "code": null, "e": 31729, "s": 31723, "text": "four " }, { "code": null, "e": 31734, "s": 31729, "text": "two " }, { "code": null, "e": 31739, "s": 31734, "text": "one " }, { "code": null, "e": 31789, "s": 31739, "text": "1 0 0 0 1\n0 1 1 1 0\n0 1 1 1 0\n0 1 1 1 0\n1 0 0 0 1" }, { "code": null, "e": 31849, "s": 31789, "text": "Which one of the following statements is TRUE about every " }, { "code": null, "e": 31981, "s": 31849, "text": "If the trace of the matrix is positive and the determinant of the matrix is negative, at least one of its eigenvalues is negative. " }, { "code": null, "e": 32087, "s": 31981, "text": "If the product of the trace and determinant of the matrix is positive, all its eigenvalues are positive. " }, { "code": null, "e": 32163, "s": 32087, "text": "If the trace of the matrix is positive, all its eigenvalues are positive. " }, { "code": null, "e": 32244, "s": 32163, "text": "If the determinant of the matrix is positive, all its eigenvalues are positive. " }, { "code": null, "e": 32727, "s": 32244, "text": "The trace of a matrix is the sum of the elements of the principal diagonal of the matrix. Fact - The sum of Eigen values of a matrix is equal to it’s trace. Fact - The product of Eigen values of a matrix is equal to its determinant value. Since it’s given that the trace is positive and the determinant is negative, there must be atleast one negative Eigen value. In general there can be an odd number of negative Eigen values in this case since the determinant value is negative. " }, { "code": null, "e": 32782, "s": 32727, "text": "Consider the set H of all 3 × 3 matrices of the type " }, { "code": null, "e": 32897, "s": 32782, "text": "where a, b, c, d, e and f are real numbers and abc ≠ 0. Under the matrix multiplication operation, the set H is " }, { "code": null, "e": 32906, "s": 32897, "text": "a group " }, { "code": null, "e": 32932, "s": 32906, "text": "a monoid but not a group " }, { "code": null, "e": 32962, "s": 32932, "text": "a semigroup but not a monoid " }, { "code": null, "e": 32995, "s": 32962, "text": "neither a group nor a semigroup " }, { "code": null, "e": 33971, "s": 32995, "text": "Because identity matrix is identity & as they define abc != 0, then it is non-singular so inverse is also defined. The set of matrices is the set of Upper triangular matrices(H) of size 3*3 with non-zero determinant. Along with the multiplication operator the set forms an Algebraic Structure since it follows the Closure Property. This is because the product of Two Upper Triangular Matrices is also a Upper Triangular Matrix. The Algebraic Structure also follows the Associative Property since, multiplication of matrices in general follows the Associative Property. Therefore it is a Semi Group. The Algebraic Structure is also a Monoid, since it has an Identity element, which is the Identity Matrix- I3. The Algebraic Structure is a Group since every matrix in H has an inverse, since every matrix in H is non-singular (given in question). The Algebraic Structure is not an Abelian Group since it does not follow the Commutative Property. Therefore Option A is correct. " }, { "code": null, "e": 33996, "s": 33971, "text": "Consider the matrix as A" }, { "code": null, "e": 34044, "s": 33996, "text": "| A | = 2 ( 2 -20 ) +1 ( 3 + 5 ) + 3 ( 12 + 2 )" }, { "code": null, "e": 34063, "s": 34044, "text": " = 36 + 8+ 42" }, { "code": null, "e": 34073, "s": 34063, "text": " = 86" }, { "code": null, "e": 34166, "s": 34073, "text": "The determinant value of following matrix is non-zero, therefore we have a unique solution. " }, { "code": null, "e": 34204, "s": 34166, "text": " 2 -1 3\n 3 -2 5\n-1 4 1 " }, { "code": null, "e": 34304, "s": 34206, "text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here." }, { "code": null, "e": 34313, "s": 34304, "text": "Comments" }, { "code": null, "e": 34326, "s": 34313, "text": "Old Comments" }, { "code": null, "e": 34357, "s": 34326, "text": "Difference between sh and bash" }, { "code": null, "e": 34411, "s": 34357, "text": "Create a dictionary with list comprehension in Python" }, { "code": null, "e": 34459, "s": 34411, "text": "Converting an image to a Torch Tensor in Python" }, { "code": null, "e": 34505, "s": 34459, "text": "How to Calculate Cosine Similarity in Python?" }, { "code": null, "e": 34566, "s": 34505, "text": "10 Best C and C++ Books For Beginners & Advanced Programmers" }, { "code": null, "e": 34623, "s": 34566, "text": "Show all columns of Pandas DataFrame in Jupyter Notebook" }, { "code": null, "e": 34684, "s": 34623, "text": "How to split a Dataset into Train and Test Sets using Python" }, { "code": null, "e": 34720, "s": 34684, "text": "How to Read JSON Files with Pandas?" }, { "code": null, "e": 34757, "s": 34720, "text": "How to Add a Title to Seaborn Plots?" } ]
All about HC-05 Bluetooth Module | Connection with Android - GeeksforGeeks
28 Oct, 2021 Ever wanted to control your Mechanical Bots with an Android Phone or design the robots with custom remote, here in this tutorial we will learn about a Bluetooth Module HC-05 used for the above mentioned and many other cases. Here we will be understanding the connection and working of a HC-05 module and also its interfacing with custom android app. Basics Wireless communication is swiftly replacing the wired connection when it comes to electronics and communication. Designed to replace cable connections HC-05 uses serial communication to communicate with the electronics. Usually, it is used to connect small devices like mobile phones using a short-range wireless connection to exchange files. It uses the 2.45GHz frequency band. The transfer rate of the data can vary up to 1Mbps and is in range of 10 meters. The HC-05 module can be operated within 4-6V of power supply. It supports baud rate of 9600, 19200, 38400, 57600, etc. Most importantly it can be operated in Master-Slave mode which means it will neither send or receive data from external sources. HC-05 module Enable - This pin is used to set the Data Mode or and AT command mode (set high). VCC - This is connected to +5V power supply. Ground - Connected to ground of powering system. Tx (Transmitter) - This pin transmits the received data Serially. Rx (Receiver) - Used for broadcasting data serially over bluetooth. State -Used to check if the bluetooth is working properly. The HC-05 Bluetooth Module can be used in two modes of operation: Command Mode and Data Mode. In Command Mode, you can communicate with the Bluetooth module through AT Commands for configuring various settings and parameters of the Module like get the firmware information, changing Baud Rate, changing module name, it can be used to set it as master or slave. A point about HC-05 Module is that it can be configured as Master or Slave in a communication pair. In order to select either of the modes, you need to activate the Command Mode and sent appropriate AT Commands. Coming to the Data Mode, in this mode, the module is used for communicating with other Bluetooth device i.e. data transfer happens in this mode. Technical specs of the code: Arduino-Uno is used as the microcontroller. Name: HC-05 Password: 1234 (or 0000) Type: Slave Mode: Data Baud Rate: 9600 with 8 data bits, no parity and 1 stop bit C //Define the variable that contains the led#define ledPin 7int state = 0;void setup() { //Setting the pin mode and initial LOW pinMode(ledPin, OUTPUT); digitalWrite(ledPin, LOW); Serial.begin(9600); // Default communication rate}void loop() { // Checks if the data is coming from the serial port if(Serial.available() > 0){ state = Serial.read(); // Read the data from the serial port } Deciding functions for LED on and off if (state == '0') { digitalWrite(ledPin, LOW); // Turn LED OFF // Send back, to the phone, the String "LED: ON" Serial.println("LED: OFF"); state = 0; } else if (state == '1') { digitalWrite(ledPin, HIGH); Serial.println("LED: ON");; state = 0; }} Now, we will develop a small android application to demonstrate the connection of bluetooth module and the android app. We will be using Android Studio for this purpose and above mentioned C code on the microcontroller. Algorithm: Create an empty project on Android Studio Create a ListView containing all the available bluetooth devices. Get the name and MAC-address of HC-05 module. Open connection with HC-05 module. Instruct the module with data as bytes. This code is for the MainActivity or first activity where the list will be displayed then after that when device will be selected, Control activity will come to give the command. Java // Initializing the Adapter for bluetoothprivate BluetoothAdapter BluetoothAdap = null;private Set Devices;// comes in Oncreate method of the activityBluetoothAdap = BluetoothAdapter.getDefaultAdapter(); // Method to fill the listwith devicesprivate void pairedDevices(){ Devices = BluetoothAdap.getBondedDevices(); ArrayList list = new ArrayList(); if (Devices.size() > 0) { for (BluetoothDevice bt : Devices) { // Add all the available devices to the list list.add(bt.getName() + "\n" + bt.getAddress()); } } else { // In case no device is found Toast.makeText(getApplicationContext(), "No Paired Bluetooth Devices Found.", Toast.LENGTH_LONG).show(); } // Adding the devices to the list with ArrayAdapter class final ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, list); devicelist.setAdapter(adapter); // Method called when the device from the list is clicked devicelist.setOnItemClickListener(myListListener);} Now we will create a OnClick Listener for the list so that thename and MAC address can be extracted from the device. Java // On click listener for the Listviewprivate AdapterView.OnItemClickListener myListListener = new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView av, View v, int arg2, long arg3) { // Get the device MAC address String name = ((TextView)v).getText().toString(); String address = info.substring(info.length() - 17); // Make an intent to start next activity. Intent i = new Intent(MainActivity.this, Control.class); // Put the data got from device to the intent i.putExtra("add", address); // this will be received at control Activity startActivity(i); }}; The connect() function in the Control.java will help to make the connection between both. Java BluetoothAdapter myBluetooth = null;BluetoothSocket btSocket = null;// This UUID is unique and fix id for this devicestatic final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); // receive the address of the bluetooth deviceIntent intent = getIntent();address = intent.getStringExtra("add"); try { if (btSocket == null || !isBtConnected) { myBluetooth = BluetoothAdapter.getDefaultAdapter(); // This will connect the device with address as passed BluetoothDevice hc = myBluetooth.getRemoteDevice(address); btSocket = hc.createInsecureRfcommSocketToServiceRecord(myUUID); BluetoothAdapter.getDefaultAdapter().cancelDiscovery(); Now you will start the connection btSocket.connect(); }}catch (IOException e) { e.printStackTrace();} Here first we will check if our socket is connected, then only we will proceed to avoid the Null Pointer exception. Java // Function for commanding the moduleprivate void turnOffLed(){ if (btSocket != null) { try { // Converting the string to bytes for transferring btSocket.getOutputStream().write("0".toString().getBytes()); } catch (IOException e) { e.printStackTrace(); } }} Now finally as we have done our first basic project with the HC-05 module and the Android programming, we can move on to complex electronic bots and make there wired connection to wireless using this amazing module HC-05 and also we now know to make a custom app. adnanirshad158 Digital Electronics & Logic Design Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to memory and memory units Analog to Digital Conversion Introduction of Sequential Circuits Restoring Division Algorithm For Unsigned Integer Latches in Digital Logic Ring Counter in Digital Logic Synchronous 3 bit Up/Down counter Differences between Synchronous and Asynchronous Counter Transmission Impairment in Data Communication Counter Design using verilog HDL
[ { "code": null, "e": 25791, "s": 25763, "text": "\n28 Oct, 2021" }, { "code": null, "e": 26858, "s": 25791, "text": "Ever wanted to control your Mechanical Bots with an Android Phone or design the robots with custom remote, here in this tutorial we will learn about a Bluetooth Module HC-05 used for the above mentioned and many other cases. Here we will be understanding the connection and working of a HC-05 module and also its interfacing with custom android app. Basics Wireless communication is swiftly replacing the wired connection when it comes to electronics and communication. Designed to replace cable connections HC-05 uses serial communication to communicate with the electronics. Usually, it is used to connect small devices like mobile phones using a short-range wireless connection to exchange files. It uses the 2.45GHz frequency band. The transfer rate of the data can vary up to 1Mbps and is in range of 10 meters. The HC-05 module can be operated within 4-6V of power supply. It supports baud rate of 9600, 19200, 38400, 57600, etc. Most importantly it can be operated in Master-Slave mode which means it will neither send or receive data from external sources. " }, { "code": null, "e": 26871, "s": 26858, "text": "HC-05 module" }, { "code": null, "e": 27244, "s": 26875, "text": "Enable - This pin is used to set the Data Mode or and AT command mode (set high).\nVCC - This is connected to +5V power supply.\nGround - Connected to ground of powering system.\nTx (Transmitter) - This pin transmits the received data Serially.\nRx (Receiver) - Used for broadcasting data serially over bluetooth.\nState -Used to check if the bluetooth is working properly." }, { "code": null, "e": 27342, "s": 27246, "text": "The HC-05 Bluetooth Module can be used in two modes of operation: Command Mode and Data Mode. " }, { "code": null, "e": 27823, "s": 27342, "text": "In Command Mode, you can communicate with the Bluetooth module through AT Commands for configuring various settings and parameters of the Module like get the firmware information, changing Baud Rate, changing module name, it can be used to set it as master or slave. A point about HC-05 Module is that it can be configured as Master or Slave in a communication pair. In order to select either of the modes, you need to activate the Command Mode and sent appropriate AT Commands. " }, { "code": null, "e": 27969, "s": 27823, "text": "Coming to the Data Mode, in this mode, the module is used for communicating with other Bluetooth device i.e. data transfer happens in this mode. " }, { "code": null, "e": 27998, "s": 27969, "text": "Technical specs of the code:" }, { "code": null, "e": 28044, "s": 27998, "text": "Arduino-Uno is used as the microcontroller. " }, { "code": null, "e": 28058, "s": 28044, "text": "Name: HC-05 " }, { "code": null, "e": 28085, "s": 28058, "text": "Password: 1234 (or 0000) " }, { "code": null, "e": 28099, "s": 28085, "text": "Type: Slave " }, { "code": null, "e": 28112, "s": 28099, "text": "Mode: Data " }, { "code": null, "e": 28171, "s": 28112, "text": "Baud Rate: 9600 with 8 data bits, no parity and 1 stop bit" }, { "code": null, "e": 28175, "s": 28173, "text": "C" }, { "code": "//Define the variable that contains the led#define ledPin 7int state = 0;void setup() { //Setting the pin mode and initial LOW pinMode(ledPin, OUTPUT); digitalWrite(ledPin, LOW); Serial.begin(9600); // Default communication rate}void loop() { // Checks if the data is coming from the serial port if(Serial.available() > 0){ state = Serial.read(); // Read the data from the serial port } Deciding functions for LED on and off if (state == '0') { digitalWrite(ledPin, LOW); // Turn LED OFF // Send back, to the phone, the String \"LED: ON\" Serial.println(\"LED: OFF\"); state = 0; } else if (state == '1') { digitalWrite(ledPin, HIGH); Serial.println(\"LED: ON\");; state = 0; }}", "e": 28864, "s": 28175, "text": null }, { "code": null, "e": 29086, "s": 28864, "text": "Now, we will develop a small android application to demonstrate the connection of bluetooth module and the android app. We will be using Android Studio for this purpose and above mentioned C code on the microcontroller. " }, { "code": null, "e": 29327, "s": 29086, "text": "Algorithm:\nCreate an empty project on Android Studio\nCreate a ListView containing all the available bluetooth devices. \nGet the name and MAC-address of HC-05 module.\nOpen connection with HC-05 module.\nInstruct the module with data as bytes." }, { "code": null, "e": 29510, "s": 29331, "text": "This code is for the MainActivity or first activity where the list will be displayed then after that when device will be selected, Control activity will come to give the command." }, { "code": null, "e": 29515, "s": 29510, "text": "Java" }, { "code": "// Initializing the Adapter for bluetoothprivate BluetoothAdapter BluetoothAdap = null;private Set Devices;// comes in Oncreate method of the activityBluetoothAdap = BluetoothAdapter.getDefaultAdapter(); // Method to fill the listwith devicesprivate void pairedDevices(){ Devices = BluetoothAdap.getBondedDevices(); ArrayList list = new ArrayList(); if (Devices.size() > 0) { for (BluetoothDevice bt : Devices) { // Add all the available devices to the list list.add(bt.getName() + \"\\n\" + bt.getAddress()); } } else { // In case no device is found Toast.makeText(getApplicationContext(), \"No Paired Bluetooth Devices Found.\", Toast.LENGTH_LONG).show(); } // Adding the devices to the list with ArrayAdapter class final ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, list); devicelist.setAdapter(adapter); // Method called when the device from the list is clicked devicelist.setOnItemClickListener(myListListener);}", "e": 30552, "s": 29515, "text": null }, { "code": null, "e": 30671, "s": 30552, "text": "Now we will create a OnClick Listener for the list so that thename and MAC address can be extracted from the device. " }, { "code": null, "e": 30676, "s": 30671, "text": "Java" }, { "code": "// On click listener for the Listviewprivate AdapterView.OnItemClickListener myListListener = new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView av, View v, int arg2, long arg3) { // Get the device MAC address String name = ((TextView)v).getText().toString(); String address = info.substring(info.length() - 17); // Make an intent to start next activity. Intent i = new Intent(MainActivity.this, Control.class); // Put the data got from device to the intent i.putExtra(\"add\", address); // this will be received at control Activity startActivity(i); }};", "e": 31320, "s": 30676, "text": null }, { "code": null, "e": 31410, "s": 31320, "text": "The connect() function in the Control.java will help to make the connection between both." }, { "code": null, "e": 31415, "s": 31410, "text": "Java" }, { "code": "BluetoothAdapter myBluetooth = null;BluetoothSocket btSocket = null;// This UUID is unique and fix id for this devicestatic final UUID myUUID = UUID.fromString(\"00001101-0000-1000-8000-00805F9B34FB\"); // receive the address of the bluetooth deviceIntent intent = getIntent();address = intent.getStringExtra(\"add\"); try { if (btSocket == null || !isBtConnected) { myBluetooth = BluetoothAdapter.getDefaultAdapter(); // This will connect the device with address as passed BluetoothDevice hc = myBluetooth.getRemoteDevice(address); btSocket = hc.createInsecureRfcommSocketToServiceRecord(myUUID); BluetoothAdapter.getDefaultAdapter().cancelDiscovery(); Now you will start the connection btSocket.connect(); }}catch (IOException e) { e.printStackTrace();}", "e": 32231, "s": 31415, "text": null }, { "code": null, "e": 32347, "s": 32231, "text": "Here first we will check if our socket is connected, then only we will proceed to avoid the Null Pointer exception." }, { "code": null, "e": 32352, "s": 32347, "text": "Java" }, { "code": "// Function for commanding the moduleprivate void turnOffLed(){ if (btSocket != null) { try { // Converting the string to bytes for transferring btSocket.getOutputStream().write(\"0\".toString().getBytes()); } catch (IOException e) { e.printStackTrace(); } }}", "e": 32666, "s": 32352, "text": null }, { "code": null, "e": 32932, "s": 32666, "text": "Now finally as we have done our first basic project with the HC-05 module and the Android programming, we can move on to complex electronic bots and make there wired connection to wireless using this amazing module HC-05 and also we now know to make a custom app. " }, { "code": null, "e": 32949, "s": 32934, "text": "adnanirshad158" }, { "code": null, "e": 32984, "s": 32949, "text": "Digital Electronics & Logic Design" }, { "code": null, "e": 33082, "s": 32984, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33122, "s": 33082, "text": "Introduction to memory and memory units" }, { "code": null, "e": 33151, "s": 33122, "text": "Analog to Digital Conversion" }, { "code": null, "e": 33187, "s": 33151, "text": "Introduction of Sequential Circuits" }, { "code": null, "e": 33237, "s": 33187, "text": "Restoring Division Algorithm For Unsigned Integer" }, { "code": null, "e": 33262, "s": 33237, "text": "Latches in Digital Logic" }, { "code": null, "e": 33292, "s": 33262, "text": "Ring Counter in Digital Logic" }, { "code": null, "e": 33326, "s": 33292, "text": "Synchronous 3 bit Up/Down counter" }, { "code": null, "e": 33383, "s": 33326, "text": "Differences between Synchronous and Asynchronous Counter" }, { "code": null, "e": 33429, "s": 33383, "text": "Transmission Impairment in Data Communication" } ]
Tensorflow.js tf.layers.zeroPadding2d() Function - GeeksforGeeks
17 Feb, 2022Tensorflow.js is an open-source library developed by Google for running machine learning models and deep learning neural networks in the browser or node environment.The tf.layers.zeroPadding2d( ) function is used for adding rows and columns for zeros at the top, bottom, left, and right side of and image tensor.Syntax: tf.layers.zeroPadding2d(args); Parameters: This method accepts the args as a parameter which has the following properties:Padding: This variable accepts an integer, or an Array of 2 integers, or Array of 2 Arrays, each of which is an array of 2 integers. Interpretation of this variable is:If a variable is an integer, the same symmetric is applied to width and height.If a variable is an array of 2 integers, interpreted as two different symmetric values of height and width.If a variable is an array of 2 arrays, interpreted as topPad, bottomPad for the first array, and leftPad, rightPad for the second array.dataFormat: This variable define the format of the shape of the input Tensor. If can be channelsLast or channelsFirst. This value defines the ordering of the dimensions in the inputs. The channelsLast define shape [ batch, height, width, channels] while channelsFirst define [ batch, channels, height, width].inputShape: It can be null or an array of numbers. It is used to create an input layer to insert before the following layer. This variable is only used for the first layer of a model.batchInputShape: This variable accept null or array of number. This variable works the same as inputShape but If both inputShape and batchInputShape are defined, batchInputShape is used. This variable is only used for the first layer of a model.batchSize: It is a number, and It helps batchInputShape variable. if batchInputShape is not defined it is used for creating batchInputShape.dtype: This variable is used for defining data type for the padding layer. It is Default to ‘float32’. This variable is only used for first layer of a model.name: It defined the name of layer.trainable: It is a boolean type. It defined layer data are updatable by fit or not. Defaults value is true.weights: It is tf.Tensor type. It declares the Initial weight values of the layer.inputDType: It defines the data type of the input layer. Legacy support. Do not use for new code.Returns: It returns ZeroPadding2D object.Example 1: In this example, we add a zero-padding layer with default values.JavascriptJavascript// Importing tensorflowconst tf = require("@tensorflow/tfjs") // Input 4d Tensor const img4d = tf.tensor4d([1, 2, 3, 4], [1, 2, 2, 1]); // Adding padding in Tensorconst pad = tf.layers.zeroPadding2d();const imgpad = pad.apply(img4d); // Printing 4d Tensor with padding</div>imgpad.print() Output: Tensor [[[[0], [0], [0], [0]], [[0], [1], [2], [0]], [[0], [3], [4], [0]], [[0], [0], [0], [0]]]]Example 2: In this example, we add zero paddings in tensor of specific data type and with define data-Format. JavascriptJavascript// Importing tensorflowconst tf = require("@tensorflow/tfjs") // Input 4d Tensor const img4d = tf.tensor4d([1, 2, 3, 4], [1, 2, 2, 1]); // Adding padding in Tensorconst pad = tf.layers.zeroPadding2d({ padding: 2, dataFormat: 'channelsFirst', dtype: 'int32'}); const imgpad = pad.apply(img4d); // Printing 4d Tensor with paddingimgpad.print() Output: Tensor [[[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 2, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]], [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 3, 0, 0], [0, 0, 4, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]]] Reference: https://js.tensorflow.org/api/latest/#layers.zeroPadding2d My Personal Notes arrow_drop_upSave Like2PreviousTensorFlow.js Browser Complete ReferenceNext Tensorflow.js tf.backend() FunctionRecommended ArticlesPage :How to get the function name from within that function using JavaScript ?30, May 19How to call a function that return another function in JavaScript ?24, Jul 19How to get the function name inside a function in PHP ?25, Sep 19Python - Call function from another function04, Dec 19How to Check a Function is a Generator Function or not using JavaScript ?26, Mar 20How to implement a function that enable another function after specified time using JavaScript ?10, Mar 21How to create a function that invokes the provided function with its arguments transformed in JavaScript?18, Jul 21How to create a function that invokes each provided function with the arguments it receives using JavaScript ?25, May 21How to create a function that invokes function with partials prepended arguments in JavaScript ?26, Jul 21Difference between ‘function declaration’ and ‘function expression' in JavaScript20, Sep 21Find the power function that the graph of f resembles for large values of |x|, given the function f(x) = (x + 6)2 (x - 2)210, Oct 21Difference between Function.prototype.apply and Function.prototype.call16, Nov 21Explain the differences on the usage of foo between function foo() {} and var foo = function() {}02, Mar 22How does TypeScript support optional parameters in function as every parameter is optional for a function in JavaScript ?24, Mar 22What are the advantages of synchronous function over asynchronous function in Node.js ?28, Mar 22How to create a function that invokes function with partials appended to the arguments in JavaScript ?28, May 21PHP | imagecreatetruecolor() Function18, Sep 18p5.js | year() function07, Apr 19D3.js | d3.utcTuesdays() Function24, Jul 19PHP | ImagickDraw getTextAlignment() Function16, Dec 19PHP | Ds\Sequence last() Function24, Jan 19PHP | Imagick floodFillPaintImage() Function30, Jul 19Function to escape regex patterns before applied in PHP31, Oct 19PHP | array_udiff_uassoc() Function11, Jul 18Article Contributed By :satyam00so@satyam00soVote for difficultyEasy Normal Medium Hard ExpertImproved By :anikakapooradnanirshad158germanshephered48Article Tags :PickedTensorflow.jsJavaScriptWeb TechnologiesImprove ArticleReport IssueWriting code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Load CommentsWhat's NewInterview Series- Prepare, Practice & UpskillView DetailsData Structures & Algorithms- Self Paced CourseView DetailsComplete Interview PreparationView DetailsMost popular in JavaScriptRemove elements from a JavaScript ArrayConvert a string to an integer in JavaScriptDifference between var, let and const keywords in JavaScriptHow to calculate the number of days between two dates in javascript?Differences between Functional Components and Class Components in ReactMost visited in Web TechnologiesRemove elements from a JavaScript ArrayInstallation of Node.js on LinuxConvert a string to an integer in JavaScriptHow to fetch data from an API in ReactJS ?How to insert spaces/tabs in text using HTML/CSS?× 5th Floor, A-118,Sector-136, Noida, Uttar Pradesh - 201305 feedback@geeksforgeeks.orgCompanyAbout UsCareersIn MediaContact UsPrivacy PolicyCopyright PolicyLearnAlgorithmsData StructuresSDE Cheat SheetMachine learningCS SubjectsVideo TutorialsNewsTop NewsTechnologyWork & CareerBusinessFinanceLifestyleLanguagesPythonJavaCPPGolangC#SQLWeb DevelopmentWeb TutorialsDjango TutorialHTMLCSSJavaScriptBootstrapContributeWrite an ArticleImprove an ArticlePick Topics to WriteWrite Interview ExperienceInternshipsVideo Internship@geeksforgeeks , Some rights reserved We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy Got It ! Start Your Coding Journey Now!Login Register Tensorflow.js tf.tensor() Function Tensorflow.js tf.scalar() Function TenserFlow.js Tensors Creation Complete Reference Tensorflow.js tf.Tensor class .buffer() Method Tensorflow.js tf.Tensor class .bufferSync() Method TensorFlow.js Tensors Classes Complete Reference Tensorflow.js tf.booleanMaskAsync() Function Tensorflow.js tf.concat() Function TensorFlow.js Tensors Transformations Complete Reference TensorFlow.js Slicing and Joining Complete Reference Tensorflow.js tf.einsum() Function Tensorflow.js tf.multinomial() Function TensorFlow.js Tensor Random Complete Reference Tensorflow.js tf.layers.zeroPadding2d() Function Tensorflow.js tf.input() Function Tensorflow.js tf.loadGraphModel() Function Tensorflow.js tf.io.http() Function TensorFlow.js Models Loading Complete Reference Tensorflow.js tf.io.copyModel() Function Tensorflow.js tf.io.listModels() Function Tensorflow.js tf.io.moveModel() Function TensorFlow.js Models Management Complete Reference Tensorflow.js tf.GraphModel Class Tensorflow.js tf.GraphModel class .save() Method Tensorflow.js tf.GraphModel class .predict() Method Tensorflow.js tf.GraphModel class .execute() Method TensorFlow.js Models Classes Complete Reference Tensorflow.js tf.layers.zeroPadding2d() Function Tensorflow.js tf.layers.elu() Function Tensorflow.js tf.layers.activation() Function TensorFlow.js Layers Basic Complete Reference Tensorflow.js tf.layers.conv1d() Function TensorFlow.js Layers Convolutional Complete Reference Tensorflow.js tf.layers.add() Function TensorFlow.js Layers Merge Complete Reference Tensorflow.js tf.layers.globalAveragePooling1d() Function TensorFlow.js Layers Pooling Complete Reference TensorFlow.js Layers Noise Complete Reference Tensorflow.js tf.layers.bidirectional() Function Tensorflow.js tf.layers.timeDistributed() Function TensorFlow.js Layers Classes Complete Reference Tensorflow.js tf.layers.zeroPadding2d() Function Tensorflow.js tf.layers.masking() Function Tensorflow.js tf.layers.zeroPadding2d() Function TensorFlow.js Operations Arithmetic Complete Reference TensorFlow.js Operations Basic Math Complete Reference TensorFlow.js Operations Matrices Complete Reference TensorFlow.js Operations Normalization Complete Reference TensorFlow.js Operations Images Complete Reference TensorFlow.js Operations Logical Complete Reference TensorFlow.js Operations Evaluation Complete Reference Tensorflow.js tf.cumsum() Function TensorFlow.js Operations Slicing and Joining Complete Reference TensorFlow.js Operations Spectral Complete Reference Tensorflow.js tf.unsortedSegmentSum() Function Tensorflow.js tf.movingAverage() Function Tensorflow.js tf.dropout() Function TensorFlow.js Operations Signal Complete Reference Tensorflow.js tf.linalg.bandPart() Function Tensorflow.js tf.linalg.gramSchmidt() Function Tensorflow.js tf.linalg.qr() Function TensorFlow.js Operations Sparse Complete Reference Tensorflow.js tf.layers.zeroPadding2d() Function Tensorflow.js tf.grad() Function Tensorflow.js tf.grads() Function Tensorflow.js tf.customGrad() Function TensorFlow.js Training Gradients Complete ReferenceTensorflow.js TrainingTensorflow.js tf.train.momentum() FunctionTensorflow.js tf.train.adagrad() FunctionTensorFlow.js Training Optimizers Complete ReferenceTensorflow.js tf.losses.absoluteDifference() FunctionTensorflow.js tf.losses.computeWeightedLoss() FunctionTensorflow.js tf.losses.cosineDistance() FunctionTensorFlow.js Training Losses Complete ReferenceTensorflow.js tf.train.Optimizer ClassTensorflow.js tf.train.Optimizer class .minimize() MethodTensorFlow.js Training Classes Complete ReferenceTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.time() FunctionTensorflow.js tf.nextFrame() FunctionTensorflow.js tf.profile() FunctionTensorFlow.js Performance Memory Complete ReferenceTensorflow.js PerformanceTensorflow.js tf.disposeVariables() FunctionTensorflow.js tf.enableDebugMode() FunctionTensorflow.js tf.enableProdMode() FunctionTensorflow.js tf.engine() FunctionTensorflow.js EnvironmentTensorFlow.js Environment Complete ReferenceTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.metrics.binaryAccuracy() FunctionTensorflow.js tf.metrics.binaryCrossentropy() FunctionTensorflow.js tf.metrics.categoricalAccuracy() FunctionTensorflow.js tf.metrics.categoricalCrossentropy() FunctionTensorflow.js tf.metrics.cosineProximity() FunctionTensorflow.js ConstraintsTensorflow.js tf.metrics.meanSquaredError() FunctionTensorflow.js tf.metrics.precision() FunctionTensorflow.js tf.metrics.recall() FunctionTensorflow.js tf.metrics.sparseCategoricalAccuracy() FunctionTensorFlow.js Metrics Complete ReferenceTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.initializers.Initializer ClassTensorflow.js tf.initializers.constant() MethodTensorflow.js tf.initializers.glorotNormal() FunctionTensorflow.js tf.initializers.glorotUniform() FunctionTensorflow.js tf.initializers.heNormal() FunctionTensorflow.js tf.initializers.heUniform() FunctionTensorflow.js InitializersTensorFlow.js Initializers Complete ReferenceTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.regularizers.l1() FunctionTensorflow.js tf.regularizers.l1l2() FunctionTensorflow.js tf.regularizers.l2() FunctionTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.data.csv() FunctionTensorflow.js tf.data.generator() FunctionTensorflow.js tf.data.microphone() FunctionTensorflow.js RegularizesTensorFlow.js Data Creation Complete ReferenceTensorflow.js tf.data.zip() FunctionTensorflow.js tf.data.Dataset class .batch() MethodTensorflow.js DataTensorFlow.js Data Classes Complete ReferencesTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.util.assert() FunctionTensorflow.js tf.util.createShuffledIndices() FunctionTensorflow.js tf.decodeString() FunctionTensorflow.js tf.encodeString() FunctionTensorflow.js tf.fetch() FunctionTensorflow.js tf.util.flatten() FunctionTensorflow.js tf.util.now() FunctionTensorflow.js tf.util.shuffle() FunctionTensorflow.js tf.util.shuffleCombo() FunctionTensorflow.js UtilTensorflow.js tf.browser.fromPixels() FunctionTensorflow.js tf.browser.fromPixelsAsync() FunctionTensorflow.js tf.browser.toPixels() FunctionTensorFlow.js Browser Complete ReferenceTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.backend() FunctionTensorflow.js tf.getBackend() FunctionTensorflow.js tf.ready() FunctionTensorflow.js tf.registerBackend() FunctionTensorflow.js tf.removeBackend() FunctionTensorflow.js tf.setBackend() FunctionTensorflow.js BrowserTensorflow.js tf.callbacks.earlyStopping() FunctionTensorflow.js BackendsTensorflow.js MetricsTable of ContentsTensorFlow.jsTensorflow.js IntroductionTensorflow.js TensorsTensorflow.js tf.tensor() FunctionTensorflow.js tf.scalar() FunctionTenserFlow.js Tensors Creation Complete ReferenceTensorflow.js tf.Tensor class .buffer() MethodTensorflow.js tf.Tensor class .bufferSync() MethodTensorFlow.js Tensors Classes Complete ReferenceTensorflow.js tf.booleanMaskAsync() FunctionTensorflow.js tf.concat() FunctionTensorFlow.js Tensors Transformations Complete ReferenceTensorFlow.js Slicing and Joining Complete ReferenceTensorflow.js tf.einsum() FunctionTensorflow.js tf.multinomial() FunctionTensorFlow.js Tensor Random Complete ReferenceTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js ModelsTensorflow.js tf.input() FunctionTensorflow.js tf.loadGraphModel() FunctionTensorflow.js tf.io.http() FunctionTensorFlow.js Models Loading Complete ReferenceTensorflow.js tf.io.copyModel() FunctionTensorflow.js tf.io.listModels() FunctionTensorflow.js tf.io.moveModel() FunctionTensorFlow.js Models Management Complete ReferenceTensorflow.js tf.GraphModel ClassTensorflow.js tf.GraphModel class .save() MethodTensorflow.js tf.GraphModel class .predict() MethodTensorflow.js tf.GraphModel class .execute() MethodTensorFlow.js Models Classes Complete ReferenceTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.layers.elu() FunctionTensorflow.js LayersTensorflow.js tf.layers.activation() FunctionTensorFlow.js Layers Basic Complete ReferenceTensorflow.js tf.layers.conv1d() FunctionTensorFlow.js Layers Convolutional Complete ReferenceTensorflow.js tf.layers.add() FunctionTensorFlow.js Layers Merge Complete ReferenceTensorflow.js tf.layers.globalAveragePooling1d() FunctionTensorFlow.js Layers Pooling Complete ReferenceTensorFlow.js Layers Noise Complete ReferenceTensorflow.js tf.layers.bidirectional() FunctionTensorflow.js tf.layers.timeDistributed() FunctionTensorFlow.js Layers Classes Complete ReferenceTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.layers.masking() FunctionTensorflow.js tf.layers.zeroPadding2d() FunctionTensorFlow.js Operations Arithmetic Complete ReferenceTensorFlow.js Operations Basic Math Complete ReferenceTensorFlow.js Operations Matrices Complete ReferenceTensorflow.js OperationsTensorFlow.js Operations Normalization Complete ReferenceTensorFlow.js Operations Images Complete ReferenceTensorFlow.js Operations Logical Complete ReferenceTensorFlow.js Operations Evaluation Complete ReferenceTensorflow.js tf.cumsum() FunctionTensorFlow.js Operations Slicing and Joining Complete ReferenceTensorFlow.js Operations Spectral Complete ReferenceTensorflow.js tf.unsortedSegmentSum() FunctionTensorflow.js tf.movingAverage() FunctionTensorflow.js tf.dropout() FunctionTensorFlow.js Operations Signal Complete ReferenceTensorflow.js tf.linalg.bandPart() FunctionTensorflow.js tf.linalg.gramSchmidt() FunctionTensorflow.js tf.linalg.qr() FunctionTensorFlow.js Operations Sparse Complete ReferenceTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.grad() FunctionTensorflow.js tf.grads() FunctionTensorflow.js tf.customGrad() FunctionTensorFlow.js Training Gradients Complete ReferenceTensorflow.js TrainingTensorflow.js tf.train.momentum() FunctionTensorflow.js tf.train.adagrad() FunctionTensorFlow.js Training Optimizers Complete ReferenceTensorflow.js tf.losses.absoluteDifference() FunctionTensorflow.js tf.losses.computeWeightedLoss() FunctionTensorflow.js tf.losses.cosineDistance() FunctionTensorFlow.js Training Losses Complete ReferenceTensorflow.js tf.train.Optimizer ClassTensorflow.js tf.train.Optimizer class .minimize() MethodTensorFlow.js Training Classes Complete ReferenceTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.time() FunctionTensorflow.js tf.nextFrame() FunctionTensorflow.js tf.profile() FunctionTensorFlow.js Performance Memory Complete ReferenceTensorflow.js PerformanceTensorflow.js tf.disposeVariables() FunctionTensorflow.js tf.enableDebugMode() FunctionTensorflow.js tf.enableProdMode() FunctionTensorflow.js tf.engine() FunctionTensorflow.js EnvironmentTensorFlow.js Environment Complete ReferenceTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.metrics.binaryAccuracy() FunctionTensorflow.js tf.metrics.binaryCrossentropy() FunctionTensorflow.js tf.metrics.categoricalAccuracy() FunctionTensorflow.js tf.metrics.categoricalCrossentropy() FunctionTensorflow.js tf.metrics.cosineProximity() FunctionTensorflow.js ConstraintsTensorflow.js tf.metrics.meanSquaredError() FunctionTensorflow.js tf.metrics.precision() FunctionTensorflow.js tf.metrics.recall() FunctionTensorflow.js tf.metrics.sparseCategoricalAccuracy() FunctionTensorFlow.js Metrics Complete ReferenceTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.initializers.Initializer ClassTensorflow.js tf.initializers.constant() MethodTensorflow.js tf.initializers.glorotNormal() FunctionTensorflow.js tf.initializers.glorotUniform() FunctionTensorflow.js tf.initializers.heNormal() FunctionTensorflow.js tf.initializers.heUniform() FunctionTensorflow.js InitializersTensorFlow.js Initializers Complete ReferenceTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.regularizers.l1() FunctionTensorflow.js tf.regularizers.l1l2() FunctionTensorflow.js tf.regularizers.l2() FunctionTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.data.csv() FunctionTensorflow.js tf.data.generator() FunctionTensorflow.js tf.data.microphone() FunctionTensorflow.js RegularizesTensorFlow.js Data Creation Complete ReferenceTensorflow.js tf.data.zip() FunctionTensorflow.js tf.data.Dataset class .batch() MethodTensorflow.js DataTensorFlow.js Data Classes Complete ReferencesTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.util.assert() FunctionTensorflow.js tf.util.createShuffledIndices() FunctionTensorflow.js tf.decodeString() FunctionTensorflow.js tf.encodeString() FunctionTensorflow.js tf.fetch() FunctionTensorflow.js tf.util.flatten() FunctionTensorflow.js tf.util.now() FunctionTensorflow.js tf.util.shuffle() FunctionTensorflow.js tf.util.shuffleCombo() FunctionTensorflow.js UtilTensorflow.js tf.browser.fromPixels() FunctionTensorflow.js tf.browser.fromPixelsAsync() FunctionTensorflow.js tf.browser.toPixels() FunctionTensorFlow.js Browser Complete ReferenceTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.backend() FunctionTensorflow.js tf.getBackend() FunctionTensorflow.js tf.ready() FunctionTensorflow.js tf.registerBackend() FunctionTensorflow.js tf.removeBackend() FunctionTensorflow.js tf.setBackend() FunctionTensorflow.js BrowserTensorflow.js tf.callbacks.earlyStopping() FunctionTensorflow.js BackendsTensorflow.js MetricsImprove Article Save Article Like Article Tensorflow.js tf.layers.zeroPadding2d() FunctionLast Updated : 17 Feb, 2022Tensorflow.js is an open-source library developed by Google for running machine learning models and deep learning neural networks in the browser or node environment.The tf.layers.zeroPadding2d( ) function is used for adding rows and columns for zeros at the top, bottom, left, and right side of and image tensor.Syntax: tf.layers.zeroPadding2d(args); Parameters: This method accepts the args as a parameter which has the following properties:Padding: This variable accepts an integer, or an Array of 2 integers, or Array of 2 Arrays, each of which is an array of 2 integers. Interpretation of this variable is:If a variable is an integer, the same symmetric is applied to width and height.If a variable is an array of 2 integers, interpreted as two different symmetric values of height and width.If a variable is an array of 2 arrays, interpreted as topPad, bottomPad for the first array, and leftPad, rightPad for the second array.dataFormat: This variable define the format of the shape of the input Tensor. If can be channelsLast or channelsFirst. This value defines the ordering of the dimensions in the inputs. The channelsLast define shape [ batch, height, width, channels] while channelsFirst define [ batch, channels, height, width].inputShape: It can be null or an array of numbers. It is used to create an input layer to insert before the following layer. This variable is only used for the first layer of a model.batchInputShape: This variable accept null or array of number. This variable works the same as inputShape but If both inputShape and batchInputShape are defined, batchInputShape is used. This variable is only used for the first layer of a model.batchSize: It is a number, and It helps batchInputShape variable. if batchInputShape is not defined it is used for creating batchInputShape.dtype: This variable is used for defining data type for the padding layer. It is Default to ‘float32’. This variable is only used for first layer of a model.name: It defined the name of layer.trainable: It is a boolean type. It defined layer data are updatable by fit or not. Defaults value is true.weights: It is tf.Tensor type. It declares the Initial weight values of the layer.inputDType: It defines the data type of the input layer. Legacy support. Do not use for new code.Returns: It returns ZeroPadding2D object.Example 1: In this example, we add a zero-padding layer with default values.JavascriptJavascript// Importing tensorflowconst tf = require("@tensorflow/tfjs") // Input 4d Tensor const img4d = tf.tensor4d([1, 2, 3, 4], [1, 2, 2, 1]); // Adding padding in Tensorconst pad = tf.layers.zeroPadding2d();const imgpad = pad.apply(img4d); // Printing 4d Tensor with padding</div>imgpad.print() Output: Tensor [[[[0], [0], [0], [0]], [[0], [1], [2], [0]], [[0], [3], [4], [0]], [[0], [0], [0], [0]]]]Example 2: In this example, we add zero paddings in tensor of specific data type and with define data-Format. JavascriptJavascript// Importing tensorflowconst tf = require("@tensorflow/tfjs") // Input 4d Tensor const img4d = tf.tensor4d([1, 2, 3, 4], [1, 2, 2, 1]); // Adding padding in Tensorconst pad = tf.layers.zeroPadding2d({ padding: 2, dataFormat: 'channelsFirst', dtype: 'int32'}); const imgpad = pad.apply(img4d); // Printing 4d Tensor with paddingimgpad.print() Output: Tensor [[[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 2, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]], [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 3, 0, 0], [0, 0, 4, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]]] Reference: https://js.tensorflow.org/api/latest/#layers.zeroPadding2d My Personal Notes arrow_drop_upSave Like2PreviousTensorFlow.js Browser Complete ReferenceNext Tensorflow.js tf.backend() FunctionRecommended ArticlesPage :How to get the function name from within that function using JavaScript ?30, May 19How to call a function that return another function in JavaScript ?24, Jul 19How to get the function name inside a function in PHP ?25, Sep 19Python - Call function from another function04, Dec 19How to Check a Function is a Generator Function or not using JavaScript ?26, Mar 20How to implement a function that enable another function after specified time using JavaScript ?10, Mar 21How to create a function that invokes the provided function with its arguments transformed in JavaScript?18, Jul 21How to create a function that invokes each provided function with the arguments it receives using JavaScript ?25, May 21How to create a function that invokes function with partials prepended arguments in JavaScript ?26, Jul 21Difference between ‘function declaration’ and ‘function expression' in JavaScript20, Sep 21Find the power function that the graph of f resembles for large values of |x|, given the function f(x) = (x + 6)2 (x - 2)210, Oct 21Difference between Function.prototype.apply and Function.prototype.call16, Nov 21Explain the differences on the usage of foo between function foo() {} and var foo = function() {}02, Mar 22How does TypeScript support optional parameters in function as every parameter is optional for a function in JavaScript ?24, Mar 22What are the advantages of synchronous function over asynchronous function in Node.js ?28, Mar 22How to create a function that invokes function with partials appended to the arguments in JavaScript ?28, May 21PHP | imagecreatetruecolor() Function18, Sep 18p5.js | year() function07, Apr 19D3.js | d3.utcTuesdays() Function24, Jul 19PHP | ImagickDraw getTextAlignment() Function16, Dec 19PHP | Ds\Sequence last() Function24, Jan 19PHP | Imagick floodFillPaintImage() Function30, Jul 19Function to escape regex patterns before applied in PHP31, Oct 19PHP | array_udiff_uassoc() Function11, Jul 18Article Contributed By :satyam00so@satyam00soVote for difficultyEasy Normal Medium Hard ExpertImproved By :anikakapooradnanirshad158germanshephered48Article Tags :PickedTensorflow.jsJavaScriptWeb TechnologiesImprove ArticleReport IssueWriting code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Load CommentsWhat's NewInterview Series- Prepare, Practice & UpskillView DetailsData Structures & Algorithms- Self Paced CourseView DetailsComplete Interview PreparationView DetailsMost popular in JavaScriptRemove elements from a JavaScript ArrayConvert a string to an integer in JavaScriptDifference between var, let and const keywords in JavaScriptHow to calculate the number of days between two dates in javascript?Differences between Functional Components and Class Components in ReactMost visited in Web TechnologiesRemove elements from a JavaScript ArrayInstallation of Node.js on LinuxConvert a string to an integer in JavaScriptHow to fetch data from an API in ReactJS ?How to insert spaces/tabs in text using HTML/CSS?× 5th Floor, A-118,Sector-136, Noida, Uttar Pradesh - 201305 feedback@geeksforgeeks.orgCompanyAbout UsCareersIn MediaContact UsPrivacy PolicyCopyright PolicyLearnAlgorithmsData StructuresSDE Cheat SheetMachine learningCS SubjectsVideo TutorialsNewsTop NewsTechnologyWork & CareerBusinessFinanceLifestyleLanguagesPythonJavaCPPGolangC#SQLWeb DevelopmentWeb TutorialsDjango TutorialHTMLCSSJavaScriptBootstrapContributeWrite an ArticleImprove an ArticlePick Topics to WriteWrite Interview ExperienceInternshipsVideo Internship@geeksforgeeks , Some rights reserved We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy Got It ! Start Your Coding Journey Now!Login Register Tensorflow.js tf.train.momentum() Function Tensorflow.js tf.train.adagrad() Function TensorFlow.js Training Optimizers Complete Reference Tensorflow.js tf.losses.absoluteDifference() Function Tensorflow.js tf.losses.computeWeightedLoss() Function Tensorflow.js tf.losses.cosineDistance() Function TensorFlow.js Training Losses Complete Reference Tensorflow.js tf.train.Optimizer Class Tensorflow.js tf.train.Optimizer class .minimize() Method TensorFlow.js Training Classes Complete Reference Tensorflow.js tf.layers.zeroPadding2d() Function Tensorflow.js tf.time() Function Tensorflow.js tf.nextFrame() Function Tensorflow.js tf.profile() Function TensorFlow.js Performance Memory Complete Reference Tensorflow.js tf.disposeVariables() Function Tensorflow.js tf.enableDebugMode() Function Tensorflow.js tf.enableProdMode() Function Tensorflow.js tf.engine() FunctionTensorflow.js EnvironmentTensorFlow.js Environment Complete ReferenceTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.metrics.binaryAccuracy() FunctionTensorflow.js tf.metrics.binaryCrossentropy() FunctionTensorflow.js tf.metrics.categoricalAccuracy() FunctionTensorflow.js tf.metrics.categoricalCrossentropy() FunctionTensorflow.js tf.metrics.cosineProximity() FunctionTensorflow.js ConstraintsTensorflow.js tf.metrics.meanSquaredError() FunctionTensorflow.js tf.metrics.precision() FunctionTensorflow.js tf.metrics.recall() FunctionTensorflow.js tf.metrics.sparseCategoricalAccuracy() FunctionTensorFlow.js Metrics Complete ReferenceTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.initializers.Initializer ClassTensorflow.js tf.initializers.constant() MethodTensorflow.js tf.initializers.glorotNormal() FunctionTensorflow.js tf.initializers.glorotUniform() FunctionTensorflow.js tf.initializers.heNormal() FunctionTensorflow.js tf.initializers.heUniform() FunctionTensorflow.js InitializersTensorFlow.js Initializers Complete ReferenceTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.regularizers.l1() FunctionTensorflow.js tf.regularizers.l1l2() FunctionTensorflow.js tf.regularizers.l2() FunctionTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.data.csv() FunctionTensorflow.js tf.data.generator() FunctionTensorflow.js tf.data.microphone() FunctionTensorflow.js RegularizesTensorFlow.js Data Creation Complete ReferenceTensorflow.js tf.data.zip() FunctionTensorflow.js tf.data.Dataset class .batch() MethodTensorflow.js DataTensorFlow.js Data Classes Complete ReferencesTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.util.assert() FunctionTensorflow.js tf.util.createShuffledIndices() FunctionTensorflow.js tf.decodeString() FunctionTensorflow.js tf.encodeString() FunctionTensorflow.js tf.fetch() FunctionTensorflow.js tf.util.flatten() FunctionTensorflow.js tf.util.now() FunctionTensorflow.js tf.util.shuffle() FunctionTensorflow.js tf.util.shuffleCombo() FunctionTensorflow.js UtilTensorflow.js tf.browser.fromPixels() FunctionTensorflow.js tf.browser.fromPixelsAsync() FunctionTensorflow.js tf.browser.toPixels() FunctionTensorFlow.js Browser Complete ReferenceTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.backend() FunctionTensorflow.js tf.getBackend() FunctionTensorflow.js tf.ready() FunctionTensorflow.js tf.registerBackend() FunctionTensorflow.js tf.removeBackend() FunctionTensorflow.js tf.setBackend() FunctionTensorflow.js BrowserTensorflow.js tf.callbacks.earlyStopping() FunctionTensorflow.js BackendsTensorflow.js Metrics TensorFlow.js Environment Complete Reference Tensorflow.js tf.layers.zeroPadding2d() Function Tensorflow.js tf.metrics.binaryAccuracy() Function Tensorflow.js tf.metrics.binaryCrossentropy() Function Tensorflow.js tf.metrics.categoricalAccuracy() Function Tensorflow.js tf.metrics.categoricalCrossentropy() Function Tensorflow.js tf.metrics.cosineProximity() Function Tensorflow.js tf.metrics.meanSquaredError() Function Tensorflow.js tf.metrics.precision() Function Tensorflow.js tf.metrics.recall() Function Tensorflow.js tf.metrics.sparseCategoricalAccuracy() Function TensorFlow.js Metrics Complete Reference Tensorflow.js tf.layers.zeroPadding2d() Function Tensorflow.js tf.initializers.Initializer Class Tensorflow.js tf.initializers.constant() Method Tensorflow.js tf.initializers.glorotNormal() Function Tensorflow.js tf.initializers.glorotUniform() Function Tensorflow.js tf.initializers.heNormal() Function Tensorflow.js tf.initializers.heUniform() Function TensorFlow.js Initializers Complete Reference Tensorflow.js tf.layers.zeroPadding2d() Function Tensorflow.js tf.regularizers.l1() Function Tensorflow.js tf.regularizers.l1l2() Function Tensorflow.js tf.regularizers.l2() Function Tensorflow.js tf.layers.zeroPadding2d() Function Tensorflow.js tf.data.csv() Function Tensorflow.js tf.data.generator() Function Tensorflow.js tf.data.microphone() FunctionTensorflow.js RegularizesTensorFlow.js Data Creation Complete ReferenceTensorflow.js tf.data.zip() FunctionTensorflow.js tf.data.Dataset class .batch() MethodTensorflow.js DataTensorFlow.js Data Classes Complete ReferencesTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.util.assert() FunctionTensorflow.js tf.util.createShuffledIndices() FunctionTensorflow.js tf.decodeString() FunctionTensorflow.js tf.encodeString() FunctionTensorflow.js tf.fetch() FunctionTensorflow.js tf.util.flatten() FunctionTensorflow.js tf.util.now() FunctionTensorflow.js tf.util.shuffle() FunctionTensorflow.js tf.util.shuffleCombo() FunctionTensorflow.js UtilTensorflow.js tf.browser.fromPixels() FunctionTensorflow.js tf.browser.fromPixelsAsync() FunctionTensorflow.js tf.browser.toPixels() FunctionTensorFlow.js Browser Complete ReferenceTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.backend() FunctionTensorflow.js tf.getBackend() FunctionTensorflow.js tf.ready() FunctionTensorflow.js tf.registerBackend() FunctionTensorflow.js tf.removeBackend() FunctionTensorflow.js tf.setBackend() FunctionTensorflow.js BrowserTensorflow.js tf.callbacks.earlyStopping() FunctionTensorflow.js BackendsTensorflow.js Metrics TensorFlow.js Data Creation Complete Reference Tensorflow.js tf.data.zip() Function Tensorflow.js tf.data.Dataset class .batch() Method TensorFlow.js Data Classes Complete References Tensorflow.js tf.layers.zeroPadding2d() Function Tensorflow.js tf.util.assert() Function Tensorflow.js tf.util.createShuffledIndices() Function Tensorflow.js tf.decodeString() Function Tensorflow.js tf.encodeString() Function Tensorflow.js tf.fetch() Function Tensorflow.js tf.util.flatten() Function Tensorflow.js tf.util.now() Function Tensorflow.js tf.util.shuffle() Function Tensorflow.js tf.util.shuffleCombo() Function Tensorflow.js tf.browser.fromPixels() Function Tensorflow.js tf.browser.fromPixelsAsync() Function Tensorflow.js tf.browser.toPixels() Function TensorFlow.js Browser Complete Reference Tensorflow.js tf.layers.zeroPadding2d() Function Tensorflow.js tf.backend() Function Tensorflow.js tf.getBackend() Function Tensorflow.js tf.ready() Function Tensorflow.js tf.registerBackend() Function Tensorflow.js tf.removeBackend() Function Tensorflow.js tf.setBackend() Function Tensorflow.js tf.callbacks.earlyStopping() Function TensorFlow.js Tensorflow.js IntroductionTensorflow.js TensorsTensorflow.js tf.tensor() FunctionTensorflow.js tf.scalar() FunctionTenserFlow.js Tensors Creation Complete ReferenceTensorflow.js tf.Tensor class .buffer() MethodTensorflow.js tf.Tensor class .bufferSync() MethodTensorFlow.js Tensors Classes Complete ReferenceTensorflow.js tf.booleanMaskAsync() FunctionTensorflow.js tf.concat() FunctionTensorFlow.js Tensors Transformations Complete ReferenceTensorFlow.js Slicing and Joining Complete ReferenceTensorflow.js tf.einsum() FunctionTensorflow.js tf.multinomial() FunctionTensorFlow.js Tensor Random Complete ReferenceTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js ModelsTensorflow.js tf.input() FunctionTensorflow.js tf.loadGraphModel() FunctionTensorflow.js tf.io.http() FunctionTensorFlow.js Models Loading Complete ReferenceTensorflow.js tf.io.copyModel() FunctionTensorflow.js tf.io.listModels() FunctionTensorflow.js tf.io.moveModel() FunctionTensorFlow.js Models Management Complete ReferenceTensorflow.js tf.GraphModel ClassTensorflow.js tf.GraphModel class .save() MethodTensorflow.js tf.GraphModel class .predict() MethodTensorflow.js tf.GraphModel class .execute() MethodTensorFlow.js Models Classes Complete ReferenceTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.layers.elu() FunctionTensorflow.js LayersTensorflow.js tf.layers.activation() FunctionTensorFlow.js Layers Basic Complete ReferenceTensorflow.js tf.layers.conv1d() FunctionTensorFlow.js Layers Convolutional Complete ReferenceTensorflow.js tf.layers.add() FunctionTensorFlow.js Layers Merge Complete ReferenceTensorflow.js tf.layers.globalAveragePooling1d() FunctionTensorFlow.js Layers Pooling Complete ReferenceTensorFlow.js Layers Noise Complete ReferenceTensorflow.js tf.layers.bidirectional() FunctionTensorflow.js tf.layers.timeDistributed() FunctionTensorFlow.js Layers Classes Complete ReferenceTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.layers.masking() FunctionTensorflow.js tf.layers.zeroPadding2d() FunctionTensorFlow.js Operations Arithmetic Complete ReferenceTensorFlow.js Operations Basic Math Complete ReferenceTensorFlow.js Operations Matrices Complete ReferenceTensorflow.js OperationsTensorFlow.js Operations Normalization Complete ReferenceTensorFlow.js Operations Images Complete ReferenceTensorFlow.js Operations Logical Complete ReferenceTensorFlow.js Operations Evaluation Complete ReferenceTensorflow.js tf.cumsum() FunctionTensorFlow.js Operations Slicing and Joining Complete ReferenceTensorFlow.js Operations Spectral Complete ReferenceTensorflow.js tf.unsortedSegmentSum() FunctionTensorflow.js tf.movingAverage() FunctionTensorflow.js tf.dropout() FunctionTensorFlow.js Operations Signal Complete ReferenceTensorflow.js tf.linalg.bandPart() FunctionTensorflow.js tf.linalg.gramSchmidt() FunctionTensorflow.js tf.linalg.qr() FunctionTensorFlow.js Operations Sparse Complete ReferenceTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.grad() FunctionTensorflow.js tf.grads() FunctionTensorflow.js tf.customGrad() FunctionTensorFlow.js Training Gradients Complete ReferenceTensorflow.js TrainingTensorflow.js tf.train.momentum() FunctionTensorflow.js tf.train.adagrad() FunctionTensorFlow.js Training Optimizers Complete ReferenceTensorflow.js tf.losses.absoluteDifference() FunctionTensorflow.js tf.losses.computeWeightedLoss() FunctionTensorflow.js tf.losses.cosineDistance() FunctionTensorFlow.js Training Losses Complete ReferenceTensorflow.js tf.train.Optimizer ClassTensorflow.js tf.train.Optimizer class .minimize() MethodTensorFlow.js Training Classes Complete ReferenceTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.time() FunctionTensorflow.js tf.nextFrame() FunctionTensorflow.js tf.profile() FunctionTensorFlow.js Performance Memory Complete ReferenceTensorflow.js PerformanceTensorflow.js tf.disposeVariables() FunctionTensorflow.js tf.enableDebugMode() FunctionTensorflow.js tf.enableProdMode() FunctionTensorflow.js tf.engine() FunctionTensorflow.js EnvironmentTensorFlow.js Environment Complete ReferenceTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.metrics.binaryAccuracy() FunctionTensorflow.js tf.metrics.binaryCrossentropy() FunctionTensorflow.js tf.metrics.categoricalAccuracy() FunctionTensorflow.js tf.metrics.categoricalCrossentropy() FunctionTensorflow.js tf.metrics.cosineProximity() FunctionTensorflow.js ConstraintsTensorflow.js tf.metrics.meanSquaredError() FunctionTensorflow.js tf.metrics.precision() FunctionTensorflow.js tf.metrics.recall() FunctionTensorflow.js tf.metrics.sparseCategoricalAccuracy() FunctionTensorFlow.js Metrics Complete ReferenceTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.initializers.Initializer ClassTensorflow.js tf.initializers.constant() MethodTensorflow.js tf.initializers.glorotNormal() FunctionTensorflow.js tf.initializers.glorotUniform() FunctionTensorflow.js tf.initializers.heNormal() FunctionTensorflow.js tf.initializers.heUniform() FunctionTensorflow.js InitializersTensorFlow.js Initializers Complete ReferenceTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.regularizers.l1() FunctionTensorflow.js tf.regularizers.l1l2() FunctionTensorflow.js tf.regularizers.l2() FunctionTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.data.csv() FunctionTensorflow.js tf.data.generator() FunctionTensorflow.js tf.data.microphone() FunctionTensorflow.js RegularizesTensorFlow.js Data Creation Complete ReferenceTensorflow.js tf.data.zip() FunctionTensorflow.js tf.data.Dataset class .batch() MethodTensorflow.js DataTensorFlow.js Data Classes Complete ReferencesTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.util.assert() FunctionTensorflow.js tf.util.createShuffledIndices() FunctionTensorflow.js tf.decodeString() FunctionTensorflow.js tf.encodeString() FunctionTensorflow.js tf.fetch() FunctionTensorflow.js tf.util.flatten() FunctionTensorflow.js tf.util.now() FunctionTensorflow.js tf.util.shuffle() FunctionTensorflow.js tf.util.shuffleCombo() FunctionTensorflow.js UtilTensorflow.js tf.browser.fromPixels() FunctionTensorflow.js tf.browser.fromPixelsAsync() FunctionTensorflow.js tf.browser.toPixels() FunctionTensorFlow.js Browser Complete ReferenceTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.backend() FunctionTensorflow.js tf.getBackend() FunctionTensorflow.js tf.ready() FunctionTensorflow.js tf.registerBackend() FunctionTensorflow.js tf.removeBackend() FunctionTensorflow.js tf.setBackend() FunctionTensorflow.js BrowserTensorflow.js tf.callbacks.earlyStopping() FunctionTensorflow.js BackendsTensorflow.js MetricsImprove Article Save Article Like Article Tensorflow.js tf.layers.zeroPadding2d() FunctionLast Updated : 17 Feb, 2022Tensorflow.js is an open-source library developed by Google for running machine learning models and deep learning neural networks in the browser or node environment.The tf.layers.zeroPadding2d( ) function is used for adding rows and columns for zeros at the top, bottom, left, and right side of and image tensor.Syntax: tf.layers.zeroPadding2d(args); Parameters: This method accepts the args as a parameter which has the following properties:Padding: This variable accepts an integer, or an Array of 2 integers, or Array of 2 Arrays, each of which is an array of 2 integers. Interpretation of this variable is:If a variable is an integer, the same symmetric is applied to width and height.If a variable is an array of 2 integers, interpreted as two different symmetric values of height and width.If a variable is an array of 2 arrays, interpreted as topPad, bottomPad for the first array, and leftPad, rightPad for the second array.dataFormat: This variable define the format of the shape of the input Tensor. If can be channelsLast or channelsFirst. This value defines the ordering of the dimensions in the inputs. The channelsLast define shape [ batch, height, width, channels] while channelsFirst define [ batch, channels, height, width].inputShape: It can be null or an array of numbers. It is used to create an input layer to insert before the following layer. This variable is only used for the first layer of a model.batchInputShape: This variable accept null or array of number. This variable works the same as inputShape but If both inputShape and batchInputShape are defined, batchInputShape is used. This variable is only used for the first layer of a model.batchSize: It is a number, and It helps batchInputShape variable. if batchInputShape is not defined it is used for creating batchInputShape.dtype: This variable is used for defining data type for the padding layer. It is Default to ‘float32’. This variable is only used for first layer of a model.name: It defined the name of layer.trainable: It is a boolean type. It defined layer data are updatable by fit or not. Defaults value is true.weights: It is tf.Tensor type. It declares the Initial weight values of the layer.inputDType: It defines the data type of the input layer. Legacy support. Do not use for new code.Returns: It returns ZeroPadding2D object.Example 1: In this example, we add a zero-padding layer with default values.JavascriptJavascript// Importing tensorflowconst tf = require("@tensorflow/tfjs") // Input 4d Tensor const img4d = tf.tensor4d([1, 2, 3, 4], [1, 2, 2, 1]); // Adding padding in Tensorconst pad = tf.layers.zeroPadding2d();const imgpad = pad.apply(img4d); // Printing 4d Tensor with padding</div>imgpad.print() Output: Tensor [[[[0], [0], [0], [0]], [[0], [1], [2], [0]], [[0], [3], [4], [0]], [[0], [0], [0], [0]]]]Example 2: In this example, we add zero paddings in tensor of specific data type and with define data-Format. JavascriptJavascript// Importing tensorflowconst tf = require("@tensorflow/tfjs") // Input 4d Tensor const img4d = tf.tensor4d([1, 2, 3, 4], [1, 2, 2, 1]); // Adding padding in Tensorconst pad = tf.layers.zeroPadding2d({ padding: 2, dataFormat: 'channelsFirst', dtype: 'int32'}); const imgpad = pad.apply(img4d); // Printing 4d Tensor with paddingimgpad.print() Output: Tensor [[[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 2, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]], [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 3, 0, 0], [0, 0, 4, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]]] Reference: https://js.tensorflow.org/api/latest/#layers.zeroPadding2d My Personal Notes arrow_drop_upSave Like2PreviousTensorFlow.js Browser Complete ReferenceNext Tensorflow.js tf.backend() FunctionRecommended ArticlesPage :How to get the function name from within that function using JavaScript ?30, May 19How to call a function that return another function in JavaScript ?24, Jul 19How to get the function name inside a function in PHP ?25, Sep 19Python - Call function from another function04, Dec 19How to Check a Function is a Generator Function or not using JavaScript ?26, Mar 20How to implement a function that enable another function after specified time using JavaScript ?10, Mar 21How to create a function that invokes the provided function with its arguments transformed in JavaScript?18, Jul 21How to create a function that invokes each provided function with the arguments it receives using JavaScript ?25, May 21How to create a function that invokes function with partials prepended arguments in JavaScript ?26, Jul 21Difference between ‘function declaration’ and ‘function expression' in JavaScript20, Sep 21Find the power function that the graph of f resembles for large values of |x|, given the function f(x) = (x + 6)2 (x - 2)210, Oct 21Difference between Function.prototype.apply and Function.prototype.call16, Nov 21Explain the differences on the usage of foo between function foo() {} and var foo = function() {}02, Mar 22How does TypeScript support optional parameters in function as every parameter is optional for a function in JavaScript ?24, Mar 22What are the advantages of synchronous function over asynchronous function in Node.js ?28, Mar 22How to create a function that invokes function with partials appended to the arguments in JavaScript ?28, May 21PHP | imagecreatetruecolor() Function18, Sep 18p5.js | year() function07, Apr 19D3.js | d3.utcTuesdays() Function24, Jul 19PHP | ImagickDraw getTextAlignment() Function16, Dec 19PHP | Ds\Sequence last() Function24, Jan 19PHP | Imagick floodFillPaintImage() Function30, Jul 19Function to escape regex patterns before applied in PHP31, Oct 19PHP | array_udiff_uassoc() Function11, Jul 18Article Contributed By :satyam00so@satyam00soVote for difficultyEasy Normal Medium Hard ExpertImproved By :anikakapooradnanirshad158germanshephered48Article Tags :PickedTensorflow.jsJavaScriptWeb TechnologiesImprove ArticleReport IssueWriting code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Load CommentsWhat's NewInterview Series- Prepare, Practice & UpskillView DetailsData Structures & Algorithms- Self Paced CourseView DetailsComplete Interview PreparationView DetailsMost popular in JavaScriptRemove elements from a JavaScript ArrayConvert a string to an integer in JavaScriptDifference between var, let and const keywords in JavaScriptHow to calculate the number of days between two dates in javascript?Differences between Functional Components and Class Components in ReactMost visited in Web TechnologiesRemove elements from a JavaScript ArrayInstallation of Node.js on LinuxConvert a string to an integer in JavaScriptHow to fetch data from an API in ReactJS ?How to insert spaces/tabs in text using HTML/CSS? Tensorflow.js tf.tensor() Function Tensorflow.js tf.scalar() Function TenserFlow.js Tensors Creation Complete Reference Tensorflow.js tf.Tensor class .buffer() Method Tensorflow.js tf.Tensor class .bufferSync() Method TensorFlow.js Tensors Classes Complete Reference Tensorflow.js tf.booleanMaskAsync() Function Tensorflow.js tf.concat() Function TensorFlow.js Tensors Transformations Complete Reference TensorFlow.js Slicing and Joining Complete Reference Tensorflow.js tf.einsum() Function Tensorflow.js tf.multinomial() Function TensorFlow.js Tensor Random Complete Reference Tensorflow.js tf.layers.zeroPadding2d() Function Tensorflow.js tf.input() Function Tensorflow.js tf.loadGraphModel() Function Tensorflow.js tf.io.http() Function TensorFlow.js Models Loading Complete Reference Tensorflow.js tf.io.copyModel() Function Tensorflow.js tf.io.listModels() Function Tensorflow.js tf.io.moveModel() Function TensorFlow.js Models Management Complete Reference Tensorflow.js tf.GraphModel Class Tensorflow.js tf.GraphModel class .save() Method Tensorflow.js tf.GraphModel class .predict() Method Tensorflow.js tf.GraphModel class .execute() Method TensorFlow.js Models Classes Complete Reference Tensorflow.js tf.layers.zeroPadding2d() Function Tensorflow.js tf.layers.elu() Function Tensorflow.js tf.layers.activation() Function TensorFlow.js Layers Basic Complete Reference Tensorflow.js tf.layers.conv1d() Function TensorFlow.js Layers Convolutional Complete Reference Tensorflow.js tf.layers.add() Function TensorFlow.js Layers Merge Complete Reference Tensorflow.js tf.layers.globalAveragePooling1d() Function TensorFlow.js Layers Pooling Complete Reference TensorFlow.js Layers Noise Complete Reference Tensorflow.js tf.layers.bidirectional() Function Tensorflow.js tf.layers.timeDistributed() Function TensorFlow.js Layers Classes Complete Reference Tensorflow.js tf.layers.zeroPadding2d() Function Tensorflow.js tf.layers.masking() Function Tensorflow.js tf.layers.zeroPadding2d() Function TensorFlow.js Operations Arithmetic Complete Reference TensorFlow.js Operations Basic Math Complete Reference TensorFlow.js Operations Matrices Complete Reference TensorFlow.js Operations Normalization Complete Reference TensorFlow.js Operations Images Complete Reference TensorFlow.js Operations Logical Complete Reference TensorFlow.js Operations Evaluation Complete Reference Tensorflow.js tf.cumsum() Function TensorFlow.js Operations Slicing and Joining Complete Reference TensorFlow.js Operations Spectral Complete Reference Tensorflow.js tf.unsortedSegmentSum() Function Tensorflow.js tf.movingAverage() Function Tensorflow.js tf.dropout() Function TensorFlow.js Operations Signal Complete Reference Tensorflow.js tf.linalg.bandPart() Function Tensorflow.js tf.linalg.gramSchmidt() Function Tensorflow.js tf.linalg.qr() Function TensorFlow.js Operations Sparse Complete Reference Tensorflow.js tf.layers.zeroPadding2d() Function Tensorflow.js tf.grad() Function Tensorflow.js tf.grads() Function Tensorflow.js tf.customGrad() Function TensorFlow.js Training Gradients Complete ReferenceTensorflow.js TrainingTensorflow.js tf.train.momentum() FunctionTensorflow.js tf.train.adagrad() FunctionTensorFlow.js Training Optimizers Complete ReferenceTensorflow.js tf.losses.absoluteDifference() FunctionTensorflow.js tf.losses.computeWeightedLoss() FunctionTensorflow.js tf.losses.cosineDistance() FunctionTensorFlow.js Training Losses Complete ReferenceTensorflow.js tf.train.Optimizer ClassTensorflow.js tf.train.Optimizer class .minimize() MethodTensorFlow.js Training Classes Complete ReferenceTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.time() FunctionTensorflow.js tf.nextFrame() FunctionTensorflow.js tf.profile() FunctionTensorFlow.js Performance Memory Complete ReferenceTensorflow.js PerformanceTensorflow.js tf.disposeVariables() FunctionTensorflow.js tf.enableDebugMode() FunctionTensorflow.js tf.enableProdMode() FunctionTensorflow.js tf.engine() FunctionTensorflow.js EnvironmentTensorFlow.js Environment Complete ReferenceTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.metrics.binaryAccuracy() FunctionTensorflow.js tf.metrics.binaryCrossentropy() FunctionTensorflow.js tf.metrics.categoricalAccuracy() FunctionTensorflow.js tf.metrics.categoricalCrossentropy() FunctionTensorflow.js tf.metrics.cosineProximity() FunctionTensorflow.js ConstraintsTensorflow.js tf.metrics.meanSquaredError() FunctionTensorflow.js tf.metrics.precision() FunctionTensorflow.js tf.metrics.recall() FunctionTensorflow.js tf.metrics.sparseCategoricalAccuracy() FunctionTensorFlow.js Metrics Complete ReferenceTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.initializers.Initializer ClassTensorflow.js tf.initializers.constant() MethodTensorflow.js tf.initializers.glorotNormal() FunctionTensorflow.js tf.initializers.glorotUniform() FunctionTensorflow.js tf.initializers.heNormal() FunctionTensorflow.js tf.initializers.heUniform() FunctionTensorflow.js InitializersTensorFlow.js Initializers Complete ReferenceTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.regularizers.l1() FunctionTensorflow.js tf.regularizers.l1l2() FunctionTensorflow.js tf.regularizers.l2() FunctionTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.data.csv() FunctionTensorflow.js tf.data.generator() FunctionTensorflow.js tf.data.microphone() FunctionTensorflow.js RegularizesTensorFlow.js Data Creation Complete ReferenceTensorflow.js tf.data.zip() FunctionTensorflow.js tf.data.Dataset class .batch() MethodTensorflow.js DataTensorFlow.js Data Classes Complete ReferencesTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.util.assert() FunctionTensorflow.js tf.util.createShuffledIndices() FunctionTensorflow.js tf.decodeString() FunctionTensorflow.js tf.encodeString() FunctionTensorflow.js tf.fetch() FunctionTensorflow.js tf.util.flatten() FunctionTensorflow.js tf.util.now() FunctionTensorflow.js tf.util.shuffle() FunctionTensorflow.js tf.util.shuffleCombo() FunctionTensorflow.js UtilTensorflow.js tf.browser.fromPixels() FunctionTensorflow.js tf.browser.fromPixelsAsync() FunctionTensorflow.js tf.browser.toPixels() FunctionTensorFlow.js Browser Complete ReferenceTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.backend() FunctionTensorflow.js tf.getBackend() FunctionTensorflow.js tf.ready() FunctionTensorflow.js tf.registerBackend() FunctionTensorflow.js tf.removeBackend() FunctionTensorflow.js tf.setBackend() FunctionTensorflow.js BrowserTensorflow.js tf.callbacks.earlyStopping() FunctionTensorflow.js BackendsTensorflow.js MetricsImprove Article Save Article Like Article Tensorflow.js tf.layers.zeroPadding2d() FunctionLast Updated : 17 Feb, 2022Tensorflow.js is an open-source library developed by Google for running machine learning models and deep learning neural networks in the browser or node environment.The tf.layers.zeroPadding2d( ) function is used for adding rows and columns for zeros at the top, bottom, left, and right side of and image tensor.Syntax: tf.layers.zeroPadding2d(args); Parameters: This method accepts the args as a parameter which has the following properties:Padding: This variable accepts an integer, or an Array of 2 integers, or Array of 2 Arrays, each of which is an array of 2 integers. Interpretation of this variable is:If a variable is an integer, the same symmetric is applied to width and height.If a variable is an array of 2 integers, interpreted as two different symmetric values of height and width.If a variable is an array of 2 arrays, interpreted as topPad, bottomPad for the first array, and leftPad, rightPad for the second array.dataFormat: This variable define the format of the shape of the input Tensor. If can be channelsLast or channelsFirst. This value defines the ordering of the dimensions in the inputs. The channelsLast define shape [ batch, height, width, channels] while channelsFirst define [ batch, channels, height, width].inputShape: It can be null or an array of numbers. It is used to create an input layer to insert before the following layer. This variable is only used for the first layer of a model.batchInputShape: This variable accept null or array of number. This variable works the same as inputShape but If both inputShape and batchInputShape are defined, batchInputShape is used. This variable is only used for the first layer of a model.batchSize: It is a number, and It helps batchInputShape variable. if batchInputShape is not defined it is used for creating batchInputShape.dtype: This variable is used for defining data type for the padding layer. It is Default to ‘float32’. This variable is only used for first layer of a model.name: It defined the name of layer.trainable: It is a boolean type. It defined layer data are updatable by fit or not. Defaults value is true.weights: It is tf.Tensor type. It declares the Initial weight values of the layer.inputDType: It defines the data type of the input layer. Legacy support. Do not use for new code.Returns: It returns ZeroPadding2D object.Example 1: In this example, we add a zero-padding layer with default values.JavascriptJavascript// Importing tensorflowconst tf = require("@tensorflow/tfjs") // Input 4d Tensor const img4d = tf.tensor4d([1, 2, 3, 4], [1, 2, 2, 1]); // Adding padding in Tensorconst pad = tf.layers.zeroPadding2d();const imgpad = pad.apply(img4d); // Printing 4d Tensor with padding</div>imgpad.print() Output: Tensor [[[[0], [0], [0], [0]], [[0], [1], [2], [0]], [[0], [3], [4], [0]], [[0], [0], [0], [0]]]]Example 2: In this example, we add zero paddings in tensor of specific data type and with define data-Format. JavascriptJavascript// Importing tensorflowconst tf = require("@tensorflow/tfjs") // Input 4d Tensor const img4d = tf.tensor4d([1, 2, 3, 4], [1, 2, 2, 1]); // Adding padding in Tensorconst pad = tf.layers.zeroPadding2d({ padding: 2, dataFormat: 'channelsFirst', dtype: 'int32'}); const imgpad = pad.apply(img4d); // Printing 4d Tensor with paddingimgpad.print() Output: Tensor [[[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 2, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]], [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 3, 0, 0], [0, 0, 4, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]]] Reference: https://js.tensorflow.org/api/latest/#layers.zeroPadding2d My Personal Notes arrow_drop_upSave Like2PreviousTensorFlow.js Browser Complete ReferenceNext Tensorflow.js tf.backend() FunctionRecommended ArticlesPage :How to get the function name from within that function using JavaScript ?30, May 19How to call a function that return another function in JavaScript ?24, Jul 19How to get the function name inside a function in PHP ?25, Sep 19Python - Call function from another function04, Dec 19How to Check a Function is a Generator Function or not using JavaScript ?26, Mar 20How to implement a function that enable another function after specified time using JavaScript ?10, Mar 21How to create a function that invokes the provided function with its arguments transformed in JavaScript?18, Jul 21How to create a function that invokes each provided function with the arguments it receives using JavaScript ?25, May 21How to create a function that invokes function with partials prepended arguments in JavaScript ?26, Jul 21Difference between ‘function declaration’ and ‘function expression' in JavaScript20, Sep 21Find the power function that the graph of f resembles for large values of |x|, given the function f(x) = (x + 6)2 (x - 2)210, Oct 21Difference between Function.prototype.apply and Function.prototype.call16, Nov 21Explain the differences on the usage of foo between function foo() {} and var foo = function() {}02, Mar 22How does TypeScript support optional parameters in function as every parameter is optional for a function in JavaScript ?24, Mar 22What are the advantages of synchronous function over asynchronous function in Node.js ?28, Mar 22How to create a function that invokes function with partials appended to the arguments in JavaScript ?28, May 21PHP | imagecreatetruecolor() Function18, Sep 18p5.js | year() function07, Apr 19D3.js | d3.utcTuesdays() Function24, Jul 19PHP | ImagickDraw getTextAlignment() Function16, Dec 19PHP | Ds\Sequence last() Function24, Jan 19PHP | Imagick floodFillPaintImage() Function30, Jul 19Function to escape regex patterns before applied in PHP31, Oct 19PHP | array_udiff_uassoc() Function11, Jul 18Article Contributed By :satyam00so@satyam00soVote for difficultyEasy Normal Medium Hard ExpertImproved By :anikakapooradnanirshad158germanshephered48Article Tags :PickedTensorflow.jsJavaScriptWeb TechnologiesImprove ArticleReport IssueWriting code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Load CommentsWhat's NewInterview Series- Prepare, Practice & UpskillView DetailsData Structures & Algorithms- Self Paced CourseView DetailsComplete Interview PreparationView DetailsMost popular in JavaScriptRemove elements from a JavaScript ArrayConvert a string to an integer in JavaScriptDifference between var, let and const keywords in JavaScriptHow to calculate the number of days between two dates in javascript?Differences between Functional Components and Class Components in ReactMost visited in Web TechnologiesRemove elements from a JavaScript ArrayInstallation of Node.js on LinuxConvert a string to an integer in JavaScriptHow to fetch data from an API in ReactJS ?How to insert spaces/tabs in text using HTML/CSS? Tensorflow.js tf.train.momentum() Function Tensorflow.js tf.train.adagrad() Function TensorFlow.js Training Optimizers Complete Reference Tensorflow.js tf.losses.absoluteDifference() Function Tensorflow.js tf.losses.computeWeightedLoss() Function Tensorflow.js tf.losses.cosineDistance() Function TensorFlow.js Training Losses Complete Reference Tensorflow.js tf.train.Optimizer Class Tensorflow.js tf.train.Optimizer class .minimize() Method TensorFlow.js Training Classes Complete Reference Tensorflow.js tf.layers.zeroPadding2d() Function Tensorflow.js tf.time() Function Tensorflow.js tf.nextFrame() Function Tensorflow.js tf.profile() Function TensorFlow.js Performance Memory Complete Reference Tensorflow.js tf.disposeVariables() Function Tensorflow.js tf.enableDebugMode() Function Tensorflow.js tf.enableProdMode() Function Tensorflow.js tf.engine() FunctionTensorflow.js EnvironmentTensorFlow.js Environment Complete ReferenceTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.metrics.binaryAccuracy() FunctionTensorflow.js tf.metrics.binaryCrossentropy() FunctionTensorflow.js tf.metrics.categoricalAccuracy() FunctionTensorflow.js tf.metrics.categoricalCrossentropy() FunctionTensorflow.js tf.metrics.cosineProximity() FunctionTensorflow.js ConstraintsTensorflow.js tf.metrics.meanSquaredError() FunctionTensorflow.js tf.metrics.precision() FunctionTensorflow.js tf.metrics.recall() FunctionTensorflow.js tf.metrics.sparseCategoricalAccuracy() FunctionTensorFlow.js Metrics Complete ReferenceTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.initializers.Initializer ClassTensorflow.js tf.initializers.constant() MethodTensorflow.js tf.initializers.glorotNormal() FunctionTensorflow.js tf.initializers.glorotUniform() FunctionTensorflow.js tf.initializers.heNormal() FunctionTensorflow.js tf.initializers.heUniform() FunctionTensorflow.js InitializersTensorFlow.js Initializers Complete ReferenceTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.regularizers.l1() FunctionTensorflow.js tf.regularizers.l1l2() FunctionTensorflow.js tf.regularizers.l2() FunctionTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.data.csv() FunctionTensorflow.js tf.data.generator() FunctionTensorflow.js tf.data.microphone() FunctionTensorflow.js RegularizesTensorFlow.js Data Creation Complete ReferenceTensorflow.js tf.data.zip() FunctionTensorflow.js tf.data.Dataset class .batch() MethodTensorflow.js DataTensorFlow.js Data Classes Complete ReferencesTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.util.assert() FunctionTensorflow.js tf.util.createShuffledIndices() FunctionTensorflow.js tf.decodeString() FunctionTensorflow.js tf.encodeString() FunctionTensorflow.js tf.fetch() FunctionTensorflow.js tf.util.flatten() FunctionTensorflow.js tf.util.now() FunctionTensorflow.js tf.util.shuffle() FunctionTensorflow.js tf.util.shuffleCombo() FunctionTensorflow.js UtilTensorflow.js tf.browser.fromPixels() FunctionTensorflow.js tf.browser.fromPixelsAsync() FunctionTensorflow.js tf.browser.toPixels() FunctionTensorFlow.js Browser Complete ReferenceTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.backend() FunctionTensorflow.js tf.getBackend() FunctionTensorflow.js tf.ready() FunctionTensorflow.js tf.registerBackend() FunctionTensorflow.js tf.removeBackend() FunctionTensorflow.js tf.setBackend() FunctionTensorflow.js BrowserTensorflow.js tf.callbacks.earlyStopping() FunctionTensorflow.js BackendsTensorflow.js Metrics TensorFlow.js Environment Complete Reference Tensorflow.js tf.layers.zeroPadding2d() Function Tensorflow.js tf.metrics.binaryAccuracy() Function Tensorflow.js tf.metrics.binaryCrossentropy() Function Tensorflow.js tf.metrics.categoricalAccuracy() Function Tensorflow.js tf.metrics.categoricalCrossentropy() Function Tensorflow.js tf.metrics.cosineProximity() Function Tensorflow.js tf.metrics.meanSquaredError() Function Tensorflow.js tf.metrics.precision() Function Tensorflow.js tf.metrics.recall() Function Tensorflow.js tf.metrics.sparseCategoricalAccuracy() Function TensorFlow.js Metrics Complete Reference Tensorflow.js tf.layers.zeroPadding2d() Function Tensorflow.js tf.initializers.Initializer Class Tensorflow.js tf.initializers.constant() Method Tensorflow.js tf.initializers.glorotNormal() Function Tensorflow.js tf.initializers.glorotUniform() Function Tensorflow.js tf.initializers.heNormal() Function Tensorflow.js tf.initializers.heUniform() Function TensorFlow.js Initializers Complete Reference Tensorflow.js tf.layers.zeroPadding2d() Function Tensorflow.js tf.regularizers.l1() Function Tensorflow.js tf.regularizers.l1l2() Function Tensorflow.js tf.regularizers.l2() Function Tensorflow.js tf.layers.zeroPadding2d() Function Tensorflow.js tf.data.csv() Function Tensorflow.js tf.data.generator() Function Tensorflow.js tf.data.microphone() FunctionTensorflow.js RegularizesTensorFlow.js Data Creation Complete ReferenceTensorflow.js tf.data.zip() FunctionTensorflow.js tf.data.Dataset class .batch() MethodTensorflow.js DataTensorFlow.js Data Classes Complete ReferencesTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.util.assert() FunctionTensorflow.js tf.util.createShuffledIndices() FunctionTensorflow.js tf.decodeString() FunctionTensorflow.js tf.encodeString() FunctionTensorflow.js tf.fetch() FunctionTensorflow.js tf.util.flatten() FunctionTensorflow.js tf.util.now() FunctionTensorflow.js tf.util.shuffle() FunctionTensorflow.js tf.util.shuffleCombo() FunctionTensorflow.js UtilTensorflow.js tf.browser.fromPixels() FunctionTensorflow.js tf.browser.fromPixelsAsync() FunctionTensorflow.js tf.browser.toPixels() FunctionTensorFlow.js Browser Complete ReferenceTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.backend() FunctionTensorflow.js tf.getBackend() FunctionTensorflow.js tf.ready() FunctionTensorflow.js tf.registerBackend() FunctionTensorflow.js tf.removeBackend() FunctionTensorflow.js tf.setBackend() FunctionTensorflow.js BrowserTensorflow.js tf.callbacks.earlyStopping() FunctionTensorflow.js BackendsTensorflow.js Metrics TensorFlow.js Data Creation Complete Reference Tensorflow.js tf.data.zip() Function Tensorflow.js tf.data.Dataset class .batch() Method TensorFlow.js Data Classes Complete References Tensorflow.js tf.layers.zeroPadding2d() Function Tensorflow.js tf.util.assert() Function Tensorflow.js tf.util.createShuffledIndices() Function Tensorflow.js tf.decodeString() Function Tensorflow.js tf.encodeString() Function Tensorflow.js tf.fetch() Function Tensorflow.js tf.util.flatten() Function Tensorflow.js tf.util.now() Function Tensorflow.js tf.util.shuffle() Function Tensorflow.js tf.util.shuffleCombo() Function Tensorflow.js tf.browser.fromPixels() Function Tensorflow.js tf.browser.fromPixelsAsync() Function Tensorflow.js tf.browser.toPixels() Function TensorFlow.js Browser Complete Reference Tensorflow.js tf.layers.zeroPadding2d() Function Tensorflow.js tf.backend() Function Tensorflow.js tf.getBackend() Function Tensorflow.js tf.ready() Function Tensorflow.js tf.registerBackend() Function Tensorflow.js tf.removeBackend() Function Tensorflow.js tf.setBackend() Function Tensorflow.js tf.callbacks.earlyStopping() Function Last Updated : 17 Feb, 2022 Tensorflow.js is an open-source library developed by Google for running machine learning models and deep learning neural networks in the browser or node environment. The tf.layers.zeroPadding2d( ) function is used for adding rows and columns for zeros at the top, bottom, left, and right side of and image tensor. Syntax: tf.layers.zeroPadding2d(args); Parameters: This method accepts the args as a parameter which has the following properties: Padding: This variable accepts an integer, or an Array of 2 integers, or Array of 2 Arrays, each of which is an array of 2 integers. Interpretation of this variable is:If a variable is an integer, the same symmetric is applied to width and height.If a variable is an array of 2 integers, interpreted as two different symmetric values of height and width.If a variable is an array of 2 arrays, interpreted as topPad, bottomPad for the first array, and leftPad, rightPad for the second array. If a variable is an integer, the same symmetric is applied to width and height. If a variable is an array of 2 integers, interpreted as two different symmetric values of height and width. If a variable is an array of 2 arrays, interpreted as topPad, bottomPad for the first array, and leftPad, rightPad for the second array. dataFormat: This variable define the format of the shape of the input Tensor. If can be channelsLast or channelsFirst. This value defines the ordering of the dimensions in the inputs. The channelsLast define shape [ batch, height, width, channels] while channelsFirst define [ batch, channels, height, width]. inputShape: It can be null or an array of numbers. It is used to create an input layer to insert before the following layer. This variable is only used for the first layer of a model. batchInputShape: This variable accept null or array of number. This variable works the same as inputShape but If both inputShape and batchInputShape are defined, batchInputShape is used. This variable is only used for the first layer of a model. batchSize: It is a number, and It helps batchInputShape variable. if batchInputShape is not defined it is used for creating batchInputShape. dtype: This variable is used for defining data type for the padding layer. It is Default to ‘float32’. This variable is only used for first layer of a model. name: It defined the name of layer. trainable: It is a boolean type. It defined layer data are updatable by fit or not. Defaults value is true. weights: It is tf.Tensor type. It declares the Initial weight values of the layer. inputDType: It defines the data type of the input layer. Legacy support. Do not use for new code. Returns: It returns ZeroPadding2D object. Example 1: In this example, we add a zero-padding layer with default values. Javascript // Importing tensorflowconst tf = require("@tensorflow/tfjs") // Input 4d Tensor const img4d = tf.tensor4d([1, 2, 3, 4], [1, 2, 2, 1]); // Adding padding in Tensorconst pad = tf.layers.zeroPadding2d();const imgpad = pad.apply(img4d); // Printing 4d Tensor with padding</div>imgpad.print() Output: Tensor [[[[0], [0], [0], [0]], [[0], [1], [2], [0]], [[0], [3], [4], [0]], [[0], [0], [0], [0]]]] Example 2: In this example, we add zero paddings in tensor of specific data type and with define data-Format. Javascript // Importing tensorflowconst tf = require("@tensorflow/tfjs") // Input 4d Tensor const img4d = tf.tensor4d([1, 2, 3, 4], [1, 2, 2, 1]); // Adding padding in Tensorconst pad = tf.layers.zeroPadding2d({ padding: 2, dataFormat: 'channelsFirst', dtype: 'int32'}); const imgpad = pad.apply(img4d); // Printing 4d Tensor with paddingimgpad.print() Output: Tensor [[[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 2, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]], [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 3, 0, 0], [0, 0, 4, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]]] Reference: https://js.tensorflow.org/api/latest/#layers.zeroPadding2d anikakapoor adnanirshad158 germanshephered48 Picked Tensorflow.js JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript How to calculate the number of days between two dates in javascript? Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 44814, "s": 23613, "text": "\n17 Feb, 2022Tensorflow.js is an open-source library developed by Google for running machine learning models and deep learning neural networks in the browser or node environment.The tf.layers.zeroPadding2d( ) function is used for adding rows and columns for zeros at the top, bottom, left, and right side of and image tensor.Syntax: tf.layers.zeroPadding2d(args); Parameters: This method accepts the args as a parameter which has the following properties:Padding: This variable accepts an integer, or an Array of 2 integers, or Array of 2 Arrays, each of which is an array of 2 integers. Interpretation of this variable is:If a variable is an integer, the same symmetric is applied to width and height.If a variable is an array of 2 integers, interpreted as two different symmetric values of height and width.If a variable is an array of 2 arrays, interpreted as topPad, bottomPad for the first array, and leftPad, rightPad for the second array.dataFormat: This variable define the format of the shape of the input Tensor. If can be channelsLast or channelsFirst. This value defines the ordering of the dimensions in the inputs. The channelsLast define shape [ batch, height, width, channels] while channelsFirst define [ batch, channels, height, width].inputShape: It can be null or an array of numbers. It is used to create an input layer to insert before the following layer. This variable is only used for the first layer of a model.batchInputShape: This variable accept null or array of number. This variable works the same as inputShape but If both inputShape and batchInputShape are defined, batchInputShape is used. This variable is only used for the first layer of a model.batchSize: It is a number, and It helps batchInputShape variable. if batchInputShape is not defined it is used for creating batchInputShape.dtype: This variable is used for defining data type for the padding layer. It is Default to ‘float32’. This variable is only used for first layer of a model.name: It defined the name of layer.trainable: It is a boolean type. It defined layer data are updatable by fit or not. Defaults value is true.weights: It is tf.Tensor type. It declares the Initial weight values of the layer.inputDType: It defines the data type of the input layer. Legacy support. Do not use for new code.Returns: It returns ZeroPadding2D object.Example 1: In this example, we add a zero-padding layer with default values.JavascriptJavascript// Importing tensorflowconst tf = require(\"@tensorflow/tfjs\") // Input 4d Tensor const img4d = tf.tensor4d([1, 2, 3, 4], [1, 2, 2, 1]); // Adding padding in Tensorconst pad = tf.layers.zeroPadding2d();const imgpad = pad.apply(img4d); // Printing 4d Tensor with padding</div>imgpad.print() Output: Tensor [[[[0], [0], [0], [0]],\n [[0], [1], [2], [0]],\n [[0], [3], [4], [0]],\n [[0], [0], [0], [0]]]]Example 2: In this example, we add zero paddings in tensor of specific data type and with define data-Format. JavascriptJavascript// Importing tensorflowconst tf = require(\"@tensorflow/tfjs\") // Input 4d Tensor const img4d = tf.tensor4d([1, 2, 3, 4], [1, 2, 2, 1]); // Adding padding in Tensorconst pad = tf.layers.zeroPadding2d({ padding: 2, dataFormat: 'channelsFirst', dtype: 'int32'}); const imgpad = pad.apply(img4d); // Printing 4d Tensor with paddingimgpad.print() Output: Tensor\n [[[[0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0],\n [0, 0, 1, 0, 0],\n [0, 0, 2, 0, 0],\n [0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0]],\n\n [[0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0],\n [0, 0, 3, 0, 0],\n [0, 0, 4, 0, 0],\n [0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0]]]] Reference: https://js.tensorflow.org/api/latest/#layers.zeroPadding2d My Personal Notes\narrow_drop_upSave\n\nLike2PreviousTensorFlow.js Browser Complete ReferenceNext\nTensorflow.js tf.backend() FunctionRecommended ArticlesPage :How to get the function name from within that function using JavaScript ?30, May 19How to call a function that return another function in JavaScript ?24, Jul 19How to get the function name inside a function in PHP ?25, Sep 19Python - Call function from another function04, Dec 19How to Check a Function is a Generator Function or not using JavaScript ?26, Mar 20How to implement a function that enable another function after specified time using JavaScript ?10, Mar 21How to create a function that invokes the provided function with its arguments transformed in JavaScript?18, Jul 21How to create a function that invokes each provided function with the arguments it receives using JavaScript ?25, May 21How to create a function that invokes function with partials prepended arguments in JavaScript ?26, Jul 21Difference between ‘function declaration’ and ‘function expression' in JavaScript20, Sep 21Find the power function that the graph of f resembles for large values of |x|, given the function f(x) = (x + 6)2 (x - 2)210, Oct 21Difference between Function.prototype.apply and Function.prototype.call16, Nov 21Explain the differences on the usage of foo between function foo() {} and var foo = function() {}02, Mar 22How does TypeScript support optional parameters in function as every parameter is optional for a function in JavaScript ?24, Mar 22What are the advantages of synchronous function over asynchronous function in Node.js ?28, Mar 22How to create a function that invokes function with partials appended to the arguments in JavaScript ?28, May 21PHP | imagecreatetruecolor() Function18, Sep 18p5.js | year() function07, Apr 19D3.js | d3.utcTuesdays() Function24, Jul 19PHP | ImagickDraw getTextAlignment() Function16, Dec 19PHP | Ds\\Sequence last() Function24, Jan 19PHP | Imagick floodFillPaintImage() Function30, Jul 19Function to escape regex patterns before applied in PHP31, Oct 19PHP | array_udiff_uassoc() Function11, Jul 18Article Contributed By :satyam00so@satyam00soVote for difficultyEasy\nNormal\nMedium\nHard\nExpertImproved By :anikakapooradnanirshad158germanshephered48Article Tags :PickedTensorflow.jsJavaScriptWeb TechnologiesImprove ArticleReport IssueWriting code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here.\nLoad CommentsWhat's NewInterview Series- Prepare, Practice & UpskillView DetailsData Structures & Algorithms- Self Paced CourseView DetailsComplete Interview PreparationView DetailsMost popular in JavaScriptRemove elements from a JavaScript ArrayConvert a string to an integer in JavaScriptDifference between var, let and const keywords in JavaScriptHow to calculate the number of days between two dates in javascript?Differences between Functional Components and Class Components in ReactMost visited in Web TechnologiesRemove elements from a JavaScript ArrayInstallation of Node.js on LinuxConvert a string to an integer in JavaScriptHow to fetch data from an API in ReactJS ?How to insert spaces/tabs in text using HTML/CSS?×\n5th Floor, A-118,Sector-136, Noida, Uttar Pradesh - 201305\nfeedback@geeksforgeeks.orgCompanyAbout UsCareersIn MediaContact UsPrivacy PolicyCopyright PolicyLearnAlgorithmsData StructuresSDE Cheat SheetMachine learningCS SubjectsVideo TutorialsNewsTop NewsTechnologyWork & CareerBusinessFinanceLifestyleLanguagesPythonJavaCPPGolangC#SQLWeb DevelopmentWeb TutorialsDjango TutorialHTMLCSSJavaScriptBootstrapContributeWrite an ArticleImprove an ArticlePick Topics to WriteWrite Interview ExperienceInternshipsVideo Internship@geeksforgeeks\n, Some rights reserved \nWe use cookies to ensure you have the best browsing experience on our website. By using our site, you\nacknowledge that you have read and understood our\nCookie Policy &\n Privacy Policy\n\nGot It !\nStart Your Coding Journey Now!Login\nRegister" }, { "code": null, "e": 44849, "s": 44814, "text": "Tensorflow.js tf.tensor() Function" }, { "code": null, "e": 44884, "s": 44849, "text": "Tensorflow.js tf.scalar() Function" }, { "code": null, "e": 44934, "s": 44884, "text": "TenserFlow.js Tensors Creation Complete Reference" }, { "code": null, "e": 44981, "s": 44934, "text": "Tensorflow.js tf.Tensor class .buffer() Method" }, { "code": null, "e": 45032, "s": 44981, "text": "Tensorflow.js tf.Tensor class .bufferSync() Method" }, { "code": null, "e": 45081, "s": 45032, "text": "TensorFlow.js Tensors Classes Complete Reference" }, { "code": null, "e": 45126, "s": 45081, "text": "Tensorflow.js tf.booleanMaskAsync() Function" }, { "code": null, "e": 45161, "s": 45126, "text": "Tensorflow.js tf.concat() Function" }, { "code": null, "e": 45218, "s": 45161, "text": "TensorFlow.js Tensors Transformations Complete Reference" }, { "code": null, "e": 45271, "s": 45218, "text": "TensorFlow.js Slicing and Joining Complete Reference" }, { "code": null, "e": 45306, "s": 45271, "text": "Tensorflow.js tf.einsum() Function" }, { "code": null, "e": 45346, "s": 45306, "text": "Tensorflow.js tf.multinomial() Function" }, { "code": null, "e": 45393, "s": 45346, "text": "TensorFlow.js Tensor Random Complete Reference" }, { "code": null, "e": 45442, "s": 45393, "text": "Tensorflow.js tf.layers.zeroPadding2d() Function" }, { "code": null, "e": 45476, "s": 45442, "text": "Tensorflow.js tf.input() Function" }, { "code": null, "e": 45519, "s": 45476, "text": "Tensorflow.js tf.loadGraphModel() Function" }, { "code": null, "e": 45555, "s": 45519, "text": "Tensorflow.js tf.io.http() Function" }, { "code": null, "e": 45603, "s": 45555, "text": "TensorFlow.js Models Loading Complete Reference" }, { "code": null, "e": 45644, "s": 45603, "text": "Tensorflow.js tf.io.copyModel() Function" }, { "code": null, "e": 45686, "s": 45644, "text": "Tensorflow.js tf.io.listModels() Function" }, { "code": null, "e": 45727, "s": 45686, "text": "Tensorflow.js tf.io.moveModel() Function" }, { "code": null, "e": 45778, "s": 45727, "text": "TensorFlow.js Models Management Complete Reference" }, { "code": null, "e": 45812, "s": 45778, "text": "Tensorflow.js tf.GraphModel Class" }, { "code": null, "e": 45861, "s": 45812, "text": "Tensorflow.js tf.GraphModel class .save() Method" }, { "code": null, "e": 45913, "s": 45861, "text": "Tensorflow.js tf.GraphModel class .predict() Method" }, { "code": null, "e": 45965, "s": 45913, "text": "Tensorflow.js tf.GraphModel class .execute() Method" }, { "code": null, "e": 46013, "s": 45965, "text": "TensorFlow.js Models Classes Complete Reference" }, { "code": null, "e": 46062, "s": 46013, "text": "Tensorflow.js tf.layers.zeroPadding2d() Function" }, { "code": null, "e": 46101, "s": 46062, "text": "Tensorflow.js tf.layers.elu() Function" }, { "code": null, "e": 46147, "s": 46101, "text": "Tensorflow.js tf.layers.activation() Function" }, { "code": null, "e": 46193, "s": 46147, "text": "TensorFlow.js Layers Basic Complete Reference" }, { "code": null, "e": 46235, "s": 46193, "text": "Tensorflow.js tf.layers.conv1d() Function" }, { "code": null, "e": 46289, "s": 46235, "text": "TensorFlow.js Layers Convolutional Complete Reference" }, { "code": null, "e": 46328, "s": 46289, "text": "Tensorflow.js tf.layers.add() Function" }, { "code": null, "e": 46374, "s": 46328, "text": "TensorFlow.js Layers Merge Complete Reference" }, { "code": null, "e": 46432, "s": 46374, "text": "Tensorflow.js tf.layers.globalAveragePooling1d() Function" }, { "code": null, "e": 46480, "s": 46432, "text": "TensorFlow.js Layers Pooling Complete Reference" }, { "code": null, "e": 46526, "s": 46480, "text": "TensorFlow.js Layers Noise Complete Reference" }, { "code": null, "e": 46575, "s": 46526, "text": "Tensorflow.js tf.layers.bidirectional() Function" }, { "code": null, "e": 46626, "s": 46575, "text": "Tensorflow.js tf.layers.timeDistributed() Function" }, { "code": null, "e": 46674, "s": 46626, "text": "TensorFlow.js Layers Classes Complete Reference" }, { "code": null, "e": 46723, "s": 46674, "text": "Tensorflow.js tf.layers.zeroPadding2d() Function" }, { "code": null, "e": 46766, "s": 46723, "text": "Tensorflow.js tf.layers.masking() Function" }, { "code": null, "e": 46815, "s": 46766, "text": "Tensorflow.js tf.layers.zeroPadding2d() Function" }, { "code": null, "e": 46870, "s": 46815, "text": "TensorFlow.js Operations Arithmetic Complete Reference" }, { "code": null, "e": 46925, "s": 46870, "text": "TensorFlow.js Operations Basic Math Complete Reference" }, { "code": null, "e": 46978, "s": 46925, "text": "TensorFlow.js Operations Matrices Complete Reference" }, { "code": null, "e": 47036, "s": 46978, "text": "TensorFlow.js Operations Normalization Complete Reference" }, { "code": null, "e": 47087, "s": 47036, "text": "TensorFlow.js Operations Images Complete Reference" }, { "code": null, "e": 47139, "s": 47087, "text": "TensorFlow.js Operations Logical Complete Reference" }, { "code": null, "e": 47194, "s": 47139, "text": "TensorFlow.js Operations Evaluation Complete Reference" }, { "code": null, "e": 47229, "s": 47194, "text": "Tensorflow.js tf.cumsum() Function" }, { "code": null, "e": 47293, "s": 47229, "text": "TensorFlow.js Operations Slicing and Joining Complete Reference" }, { "code": null, "e": 47346, "s": 47293, "text": "TensorFlow.js Operations Spectral Complete Reference" }, { "code": null, "e": 47393, "s": 47346, "text": "Tensorflow.js tf.unsortedSegmentSum() Function" }, { "code": null, "e": 47435, "s": 47393, "text": "Tensorflow.js tf.movingAverage() Function" }, { "code": null, "e": 47471, "s": 47435, "text": "Tensorflow.js tf.dropout() Function" }, { "code": null, "e": 47522, "s": 47471, "text": "TensorFlow.js Operations Signal Complete Reference" }, { "code": null, "e": 47566, "s": 47522, "text": "Tensorflow.js tf.linalg.bandPart() Function" }, { "code": null, "e": 47613, "s": 47566, "text": "Tensorflow.js tf.linalg.gramSchmidt() Function" }, { "code": null, "e": 47651, "s": 47613, "text": "Tensorflow.js tf.linalg.qr() Function" }, { "code": null, "e": 47702, "s": 47651, "text": "TensorFlow.js Operations Sparse Complete Reference" }, { "code": null, "e": 47751, "s": 47702, "text": "Tensorflow.js tf.layers.zeroPadding2d() Function" }, { "code": null, "e": 47784, "s": 47751, "text": "Tensorflow.js tf.grad() Function" }, { "code": null, "e": 47818, "s": 47784, "text": "Tensorflow.js tf.grads() Function" }, { "code": null, "e": 47857, "s": 47818, "text": "Tensorflow.js tf.customGrad() Function" }, { "code": null, "e": 65970, "s": 47857, "text": "TensorFlow.js Training Gradients Complete ReferenceTensorflow.js TrainingTensorflow.js tf.train.momentum() FunctionTensorflow.js tf.train.adagrad() FunctionTensorFlow.js Training Optimizers Complete ReferenceTensorflow.js tf.losses.absoluteDifference() FunctionTensorflow.js tf.losses.computeWeightedLoss() FunctionTensorflow.js tf.losses.cosineDistance() FunctionTensorFlow.js Training Losses Complete ReferenceTensorflow.js tf.train.Optimizer ClassTensorflow.js tf.train.Optimizer class .minimize() MethodTensorFlow.js Training Classes Complete ReferenceTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.time() FunctionTensorflow.js tf.nextFrame() FunctionTensorflow.js tf.profile() FunctionTensorFlow.js Performance Memory Complete ReferenceTensorflow.js PerformanceTensorflow.js tf.disposeVariables() FunctionTensorflow.js tf.enableDebugMode() FunctionTensorflow.js tf.enableProdMode() FunctionTensorflow.js tf.engine() FunctionTensorflow.js EnvironmentTensorFlow.js Environment Complete ReferenceTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.metrics.binaryAccuracy() FunctionTensorflow.js tf.metrics.binaryCrossentropy() FunctionTensorflow.js tf.metrics.categoricalAccuracy() FunctionTensorflow.js tf.metrics.categoricalCrossentropy() FunctionTensorflow.js tf.metrics.cosineProximity() FunctionTensorflow.js ConstraintsTensorflow.js tf.metrics.meanSquaredError() FunctionTensorflow.js tf.metrics.precision() FunctionTensorflow.js tf.metrics.recall() FunctionTensorflow.js tf.metrics.sparseCategoricalAccuracy() FunctionTensorFlow.js Metrics Complete ReferenceTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.initializers.Initializer ClassTensorflow.js tf.initializers.constant() MethodTensorflow.js tf.initializers.glorotNormal() FunctionTensorflow.js tf.initializers.glorotUniform() FunctionTensorflow.js tf.initializers.heNormal() FunctionTensorflow.js tf.initializers.heUniform() FunctionTensorflow.js InitializersTensorFlow.js Initializers Complete ReferenceTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.regularizers.l1() FunctionTensorflow.js tf.regularizers.l1l2() FunctionTensorflow.js tf.regularizers.l2() FunctionTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.data.csv() FunctionTensorflow.js tf.data.generator() FunctionTensorflow.js tf.data.microphone() FunctionTensorflow.js RegularizesTensorFlow.js Data Creation Complete ReferenceTensorflow.js tf.data.zip() FunctionTensorflow.js tf.data.Dataset class .batch() MethodTensorflow.js DataTensorFlow.js Data Classes Complete ReferencesTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.util.assert() FunctionTensorflow.js tf.util.createShuffledIndices() FunctionTensorflow.js tf.decodeString() FunctionTensorflow.js tf.encodeString() FunctionTensorflow.js tf.fetch() FunctionTensorflow.js tf.util.flatten() FunctionTensorflow.js tf.util.now() FunctionTensorflow.js tf.util.shuffle() FunctionTensorflow.js tf.util.shuffleCombo() FunctionTensorflow.js UtilTensorflow.js tf.browser.fromPixels() FunctionTensorflow.js tf.browser.fromPixelsAsync() FunctionTensorflow.js tf.browser.toPixels() FunctionTensorFlow.js Browser Complete ReferenceTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.backend() FunctionTensorflow.js tf.getBackend() FunctionTensorflow.js tf.ready() FunctionTensorflow.js tf.registerBackend() FunctionTensorflow.js tf.removeBackend() FunctionTensorflow.js tf.setBackend() FunctionTensorflow.js BrowserTensorflow.js tf.callbacks.earlyStopping() FunctionTensorflow.js BackendsTensorflow.js MetricsTable of ContentsTensorFlow.jsTensorflow.js IntroductionTensorflow.js TensorsTensorflow.js tf.tensor() FunctionTensorflow.js tf.scalar() FunctionTenserFlow.js Tensors Creation Complete ReferenceTensorflow.js tf.Tensor class .buffer() MethodTensorflow.js tf.Tensor class .bufferSync() MethodTensorFlow.js Tensors Classes Complete ReferenceTensorflow.js tf.booleanMaskAsync() FunctionTensorflow.js tf.concat() FunctionTensorFlow.js Tensors Transformations Complete ReferenceTensorFlow.js Slicing and Joining Complete ReferenceTensorflow.js tf.einsum() FunctionTensorflow.js tf.multinomial() FunctionTensorFlow.js Tensor Random Complete ReferenceTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js ModelsTensorflow.js tf.input() FunctionTensorflow.js tf.loadGraphModel() FunctionTensorflow.js tf.io.http() FunctionTensorFlow.js Models Loading Complete ReferenceTensorflow.js tf.io.copyModel() FunctionTensorflow.js tf.io.listModels() FunctionTensorflow.js tf.io.moveModel() FunctionTensorFlow.js Models Management Complete ReferenceTensorflow.js tf.GraphModel ClassTensorflow.js tf.GraphModel class .save() MethodTensorflow.js tf.GraphModel class .predict() MethodTensorflow.js tf.GraphModel class .execute() MethodTensorFlow.js Models Classes Complete ReferenceTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.layers.elu() FunctionTensorflow.js LayersTensorflow.js tf.layers.activation() FunctionTensorFlow.js Layers Basic Complete ReferenceTensorflow.js tf.layers.conv1d() FunctionTensorFlow.js Layers Convolutional Complete ReferenceTensorflow.js tf.layers.add() FunctionTensorFlow.js Layers Merge Complete ReferenceTensorflow.js tf.layers.globalAveragePooling1d() FunctionTensorFlow.js Layers Pooling Complete ReferenceTensorFlow.js Layers Noise Complete ReferenceTensorflow.js tf.layers.bidirectional() FunctionTensorflow.js tf.layers.timeDistributed() FunctionTensorFlow.js Layers Classes Complete ReferenceTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.layers.masking() FunctionTensorflow.js tf.layers.zeroPadding2d() FunctionTensorFlow.js Operations Arithmetic Complete ReferenceTensorFlow.js Operations Basic Math Complete ReferenceTensorFlow.js Operations Matrices Complete ReferenceTensorflow.js OperationsTensorFlow.js Operations Normalization Complete ReferenceTensorFlow.js Operations Images Complete ReferenceTensorFlow.js Operations Logical Complete ReferenceTensorFlow.js Operations Evaluation Complete ReferenceTensorflow.js tf.cumsum() FunctionTensorFlow.js Operations Slicing and Joining Complete ReferenceTensorFlow.js Operations Spectral Complete ReferenceTensorflow.js tf.unsortedSegmentSum() FunctionTensorflow.js tf.movingAverage() FunctionTensorflow.js tf.dropout() FunctionTensorFlow.js Operations Signal Complete ReferenceTensorflow.js tf.linalg.bandPart() FunctionTensorflow.js tf.linalg.gramSchmidt() FunctionTensorflow.js tf.linalg.qr() FunctionTensorFlow.js Operations Sparse Complete ReferenceTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.grad() FunctionTensorflow.js tf.grads() FunctionTensorflow.js tf.customGrad() FunctionTensorFlow.js Training Gradients Complete ReferenceTensorflow.js TrainingTensorflow.js tf.train.momentum() FunctionTensorflow.js tf.train.adagrad() FunctionTensorFlow.js Training Optimizers Complete ReferenceTensorflow.js tf.losses.absoluteDifference() FunctionTensorflow.js tf.losses.computeWeightedLoss() FunctionTensorflow.js tf.losses.cosineDistance() FunctionTensorFlow.js Training Losses Complete ReferenceTensorflow.js tf.train.Optimizer ClassTensorflow.js tf.train.Optimizer class .minimize() MethodTensorFlow.js Training Classes Complete ReferenceTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.time() FunctionTensorflow.js tf.nextFrame() FunctionTensorflow.js tf.profile() FunctionTensorFlow.js Performance Memory Complete ReferenceTensorflow.js PerformanceTensorflow.js tf.disposeVariables() FunctionTensorflow.js tf.enableDebugMode() FunctionTensorflow.js tf.enableProdMode() FunctionTensorflow.js tf.engine() FunctionTensorflow.js EnvironmentTensorFlow.js Environment Complete ReferenceTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.metrics.binaryAccuracy() FunctionTensorflow.js tf.metrics.binaryCrossentropy() FunctionTensorflow.js tf.metrics.categoricalAccuracy() FunctionTensorflow.js tf.metrics.categoricalCrossentropy() FunctionTensorflow.js tf.metrics.cosineProximity() FunctionTensorflow.js ConstraintsTensorflow.js tf.metrics.meanSquaredError() FunctionTensorflow.js tf.metrics.precision() FunctionTensorflow.js tf.metrics.recall() FunctionTensorflow.js tf.metrics.sparseCategoricalAccuracy() FunctionTensorFlow.js Metrics Complete ReferenceTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.initializers.Initializer ClassTensorflow.js tf.initializers.constant() MethodTensorflow.js tf.initializers.glorotNormal() FunctionTensorflow.js tf.initializers.glorotUniform() FunctionTensorflow.js tf.initializers.heNormal() FunctionTensorflow.js tf.initializers.heUniform() FunctionTensorflow.js InitializersTensorFlow.js Initializers Complete ReferenceTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.regularizers.l1() FunctionTensorflow.js tf.regularizers.l1l2() FunctionTensorflow.js tf.regularizers.l2() FunctionTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.data.csv() FunctionTensorflow.js tf.data.generator() FunctionTensorflow.js tf.data.microphone() FunctionTensorflow.js RegularizesTensorFlow.js Data Creation Complete ReferenceTensorflow.js tf.data.zip() FunctionTensorflow.js tf.data.Dataset class .batch() MethodTensorflow.js DataTensorFlow.js Data Classes Complete ReferencesTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.util.assert() FunctionTensorflow.js tf.util.createShuffledIndices() FunctionTensorflow.js tf.decodeString() FunctionTensorflow.js tf.encodeString() FunctionTensorflow.js tf.fetch() FunctionTensorflow.js tf.util.flatten() FunctionTensorflow.js tf.util.now() FunctionTensorflow.js tf.util.shuffle() FunctionTensorflow.js tf.util.shuffleCombo() FunctionTensorflow.js UtilTensorflow.js tf.browser.fromPixels() FunctionTensorflow.js tf.browser.fromPixelsAsync() FunctionTensorflow.js tf.browser.toPixels() FunctionTensorFlow.js Browser Complete ReferenceTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.backend() FunctionTensorflow.js tf.getBackend() FunctionTensorflow.js tf.ready() FunctionTensorflow.js tf.registerBackend() FunctionTensorflow.js tf.removeBackend() FunctionTensorflow.js tf.setBackend() FunctionTensorflow.js BrowserTensorflow.js tf.callbacks.earlyStopping() FunctionTensorflow.js BackendsTensorflow.js MetricsImprove Article\n\nSave Article\n\nLike Article\n\nTensorflow.js tf.layers.zeroPadding2d() FunctionLast Updated :\n17 Feb, 2022Tensorflow.js is an open-source library developed by Google for running machine learning models and deep learning neural networks in the browser or node environment.The tf.layers.zeroPadding2d( ) function is used for adding rows and columns for zeros at the top, bottom, left, and right side of and image tensor.Syntax: tf.layers.zeroPadding2d(args); Parameters: This method accepts the args as a parameter which has the following properties:Padding: This variable accepts an integer, or an Array of 2 integers, or Array of 2 Arrays, each of which is an array of 2 integers. Interpretation of this variable is:If a variable is an integer, the same symmetric is applied to width and height.If a variable is an array of 2 integers, interpreted as two different symmetric values of height and width.If a variable is an array of 2 arrays, interpreted as topPad, bottomPad for the first array, and leftPad, rightPad for the second array.dataFormat: This variable define the format of the shape of the input Tensor. If can be channelsLast or channelsFirst. This value defines the ordering of the dimensions in the inputs. The channelsLast define shape [ batch, height, width, channels] while channelsFirst define [ batch, channels, height, width].inputShape: It can be null or an array of numbers. It is used to create an input layer to insert before the following layer. This variable is only used for the first layer of a model.batchInputShape: This variable accept null or array of number. This variable works the same as inputShape but If both inputShape and batchInputShape are defined, batchInputShape is used. This variable is only used for the first layer of a model.batchSize: It is a number, and It helps batchInputShape variable. if batchInputShape is not defined it is used for creating batchInputShape.dtype: This variable is used for defining data type for the padding layer. It is Default to ‘float32’. This variable is only used for first layer of a model.name: It defined the name of layer.trainable: It is a boolean type. It defined layer data are updatable by fit or not. Defaults value is true.weights: It is tf.Tensor type. It declares the Initial weight values of the layer.inputDType: It defines the data type of the input layer. Legacy support. Do not use for new code.Returns: It returns ZeroPadding2D object.Example 1: In this example, we add a zero-padding layer with default values.JavascriptJavascript// Importing tensorflowconst tf = require(\"@tensorflow/tfjs\") // Input 4d Tensor const img4d = tf.tensor4d([1, 2, 3, 4], [1, 2, 2, 1]); // Adding padding in Tensorconst pad = tf.layers.zeroPadding2d();const imgpad = pad.apply(img4d); // Printing 4d Tensor with padding</div>imgpad.print() Output: Tensor [[[[0], [0], [0], [0]],\n [[0], [1], [2], [0]],\n [[0], [3], [4], [0]],\n [[0], [0], [0], [0]]]]Example 2: In this example, we add zero paddings in tensor of specific data type and with define data-Format. JavascriptJavascript// Importing tensorflowconst tf = require(\"@tensorflow/tfjs\") // Input 4d Tensor const img4d = tf.tensor4d([1, 2, 3, 4], [1, 2, 2, 1]); // Adding padding in Tensorconst pad = tf.layers.zeroPadding2d({ padding: 2, dataFormat: 'channelsFirst', dtype: 'int32'}); const imgpad = pad.apply(img4d); // Printing 4d Tensor with paddingimgpad.print() Output: Tensor\n [[[[0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0],\n [0, 0, 1, 0, 0],\n [0, 0, 2, 0, 0],\n [0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0]],\n\n [[0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0],\n [0, 0, 3, 0, 0],\n [0, 0, 4, 0, 0],\n [0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0]]]] Reference: https://js.tensorflow.org/api/latest/#layers.zeroPadding2d My Personal Notes\narrow_drop_upSave\n\nLike2PreviousTensorFlow.js Browser Complete ReferenceNext\nTensorflow.js tf.backend() FunctionRecommended ArticlesPage :How to get the function name from within that function using JavaScript ?30, May 19How to call a function that return another function in JavaScript ?24, Jul 19How to get the function name inside a function in PHP ?25, Sep 19Python - Call function from another function04, Dec 19How to Check a Function is a Generator Function or not using JavaScript ?26, Mar 20How to implement a function that enable another function after specified time using JavaScript ?10, Mar 21How to create a function that invokes the provided function with its arguments transformed in JavaScript?18, Jul 21How to create a function that invokes each provided function with the arguments it receives using JavaScript ?25, May 21How to create a function that invokes function with partials prepended arguments in JavaScript ?26, Jul 21Difference between ‘function declaration’ and ‘function expression' in JavaScript20, Sep 21Find the power function that the graph of f resembles for large values of |x|, given the function f(x) = (x + 6)2 (x - 2)210, Oct 21Difference between Function.prototype.apply and Function.prototype.call16, Nov 21Explain the differences on the usage of foo between function foo() {} and var foo = function() {}02, Mar 22How does TypeScript support optional parameters in function as every parameter is optional for a function in JavaScript ?24, Mar 22What are the advantages of synchronous function over asynchronous function in Node.js ?28, Mar 22How to create a function that invokes function with partials appended to the arguments in JavaScript ?28, May 21PHP | imagecreatetruecolor() Function18, Sep 18p5.js | year() function07, Apr 19D3.js | d3.utcTuesdays() Function24, Jul 19PHP | ImagickDraw getTextAlignment() Function16, Dec 19PHP | Ds\\Sequence last() Function24, Jan 19PHP | Imagick floodFillPaintImage() Function30, Jul 19Function to escape regex patterns before applied in PHP31, Oct 19PHP | array_udiff_uassoc() Function11, Jul 18Article Contributed By :satyam00so@satyam00soVote for difficultyEasy\nNormal\nMedium\nHard\nExpertImproved By :anikakapooradnanirshad158germanshephered48Article Tags :PickedTensorflow.jsJavaScriptWeb TechnologiesImprove ArticleReport IssueWriting code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here.\nLoad CommentsWhat's NewInterview Series- Prepare, Practice & UpskillView DetailsData Structures & Algorithms- Self Paced CourseView DetailsComplete Interview PreparationView DetailsMost popular in JavaScriptRemove elements from a JavaScript ArrayConvert a string to an integer in JavaScriptDifference between var, let and const keywords in JavaScriptHow to calculate the number of days between two dates in javascript?Differences between Functional Components and Class Components in ReactMost visited in Web TechnologiesRemove elements from a JavaScript ArrayInstallation of Node.js on LinuxConvert a string to an integer in JavaScriptHow to fetch data from an API in ReactJS ?How to insert spaces/tabs in text using HTML/CSS?×\n5th Floor, A-118,Sector-136, Noida, Uttar Pradesh - 201305\nfeedback@geeksforgeeks.orgCompanyAbout UsCareersIn MediaContact UsPrivacy PolicyCopyright PolicyLearnAlgorithmsData StructuresSDE Cheat SheetMachine learningCS SubjectsVideo TutorialsNewsTop NewsTechnologyWork & CareerBusinessFinanceLifestyleLanguagesPythonJavaCPPGolangC#SQLWeb DevelopmentWeb TutorialsDjango TutorialHTMLCSSJavaScriptBootstrapContributeWrite an ArticleImprove an ArticlePick Topics to WriteWrite Interview ExperienceInternshipsVideo Internship@geeksforgeeks\n, Some rights reserved \nWe use cookies to ensure you have the best browsing experience on our website. By using our site, you\nacknowledge that you have read and understood our\nCookie Policy &\n Privacy Policy\n\nGot It !\nStart Your Coding Journey Now!Login\nRegister" }, { "code": null, "e": 66013, "s": 65970, "text": "Tensorflow.js tf.train.momentum() Function" }, { "code": null, "e": 66055, "s": 66013, "text": "Tensorflow.js tf.train.adagrad() Function" }, { "code": null, "e": 66108, "s": 66055, "text": "TensorFlow.js Training Optimizers Complete Reference" }, { "code": null, "e": 66162, "s": 66108, "text": "Tensorflow.js tf.losses.absoluteDifference() Function" }, { "code": null, "e": 66217, "s": 66162, "text": "Tensorflow.js tf.losses.computeWeightedLoss() Function" }, { "code": null, "e": 66267, "s": 66217, "text": "Tensorflow.js tf.losses.cosineDistance() Function" }, { "code": null, "e": 66316, "s": 66267, "text": "TensorFlow.js Training Losses Complete Reference" }, { "code": null, "e": 66355, "s": 66316, "text": "Tensorflow.js tf.train.Optimizer Class" }, { "code": null, "e": 66413, "s": 66355, "text": "Tensorflow.js tf.train.Optimizer class .minimize() Method" }, { "code": null, "e": 66463, "s": 66413, "text": "TensorFlow.js Training Classes Complete Reference" }, { "code": null, "e": 66512, "s": 66463, "text": "Tensorflow.js tf.layers.zeroPadding2d() Function" }, { "code": null, "e": 66545, "s": 66512, "text": "Tensorflow.js tf.time() Function" }, { "code": null, "e": 66583, "s": 66545, "text": "Tensorflow.js tf.nextFrame() Function" }, { "code": null, "e": 66619, "s": 66583, "text": "Tensorflow.js tf.profile() Function" }, { "code": null, "e": 66671, "s": 66619, "text": "TensorFlow.js Performance Memory Complete Reference" }, { "code": null, "e": 66716, "s": 66671, "text": "Tensorflow.js tf.disposeVariables() Function" }, { "code": null, "e": 66760, "s": 66716, "text": "Tensorflow.js tf.enableDebugMode() Function" }, { "code": null, "e": 66803, "s": 66760, "text": "Tensorflow.js tf.enableProdMode() Function" }, { "code": null, "e": 69483, "s": 66803, "text": "Tensorflow.js tf.engine() FunctionTensorflow.js EnvironmentTensorFlow.js Environment Complete ReferenceTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.metrics.binaryAccuracy() FunctionTensorflow.js tf.metrics.binaryCrossentropy() FunctionTensorflow.js tf.metrics.categoricalAccuracy() FunctionTensorflow.js tf.metrics.categoricalCrossentropy() FunctionTensorflow.js tf.metrics.cosineProximity() FunctionTensorflow.js ConstraintsTensorflow.js tf.metrics.meanSquaredError() FunctionTensorflow.js tf.metrics.precision() FunctionTensorflow.js tf.metrics.recall() FunctionTensorflow.js tf.metrics.sparseCategoricalAccuracy() FunctionTensorFlow.js Metrics Complete ReferenceTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.initializers.Initializer ClassTensorflow.js tf.initializers.constant() MethodTensorflow.js tf.initializers.glorotNormal() FunctionTensorflow.js tf.initializers.glorotUniform() FunctionTensorflow.js tf.initializers.heNormal() FunctionTensorflow.js tf.initializers.heUniform() FunctionTensorflow.js InitializersTensorFlow.js Initializers Complete ReferenceTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.regularizers.l1() FunctionTensorflow.js tf.regularizers.l1l2() FunctionTensorflow.js tf.regularizers.l2() FunctionTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.data.csv() FunctionTensorflow.js tf.data.generator() FunctionTensorflow.js tf.data.microphone() FunctionTensorflow.js RegularizesTensorFlow.js Data Creation Complete ReferenceTensorflow.js tf.data.zip() FunctionTensorflow.js tf.data.Dataset class .batch() MethodTensorflow.js DataTensorFlow.js Data Classes Complete ReferencesTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.util.assert() FunctionTensorflow.js tf.util.createShuffledIndices() FunctionTensorflow.js tf.decodeString() FunctionTensorflow.js tf.encodeString() FunctionTensorflow.js tf.fetch() FunctionTensorflow.js tf.util.flatten() FunctionTensorflow.js tf.util.now() FunctionTensorflow.js tf.util.shuffle() FunctionTensorflow.js tf.util.shuffleCombo() FunctionTensorflow.js UtilTensorflow.js tf.browser.fromPixels() FunctionTensorflow.js tf.browser.fromPixelsAsync() FunctionTensorflow.js tf.browser.toPixels() FunctionTensorFlow.js Browser Complete ReferenceTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.backend() FunctionTensorflow.js tf.getBackend() FunctionTensorflow.js tf.ready() FunctionTensorflow.js tf.registerBackend() FunctionTensorflow.js tf.removeBackend() FunctionTensorflow.js tf.setBackend() FunctionTensorflow.js BrowserTensorflow.js tf.callbacks.earlyStopping() FunctionTensorflow.js BackendsTensorflow.js Metrics" }, { "code": null, "e": 69528, "s": 69483, "text": "TensorFlow.js Environment Complete Reference" }, { "code": null, "e": 69577, "s": 69528, "text": "Tensorflow.js tf.layers.zeroPadding2d() Function" }, { "code": null, "e": 69628, "s": 69577, "text": "Tensorflow.js tf.metrics.binaryAccuracy() Function" }, { "code": null, "e": 69683, "s": 69628, "text": "Tensorflow.js tf.metrics.binaryCrossentropy() Function" }, { "code": null, "e": 69739, "s": 69683, "text": "Tensorflow.js tf.metrics.categoricalAccuracy() Function" }, { "code": null, "e": 69799, "s": 69739, "text": "Tensorflow.js tf.metrics.categoricalCrossentropy() Function" }, { "code": null, "e": 69851, "s": 69799, "text": "Tensorflow.js tf.metrics.cosineProximity() Function" }, { "code": null, "e": 69904, "s": 69851, "text": "Tensorflow.js tf.metrics.meanSquaredError() Function" }, { "code": null, "e": 69950, "s": 69904, "text": "Tensorflow.js tf.metrics.precision() Function" }, { "code": null, "e": 69993, "s": 69950, "text": "Tensorflow.js tf.metrics.recall() Function" }, { "code": null, "e": 70055, "s": 69993, "text": "Tensorflow.js tf.metrics.sparseCategoricalAccuracy() Function" }, { "code": null, "e": 70096, "s": 70055, "text": "TensorFlow.js Metrics Complete Reference" }, { "code": null, "e": 70145, "s": 70096, "text": "Tensorflow.js tf.layers.zeroPadding2d() Function" }, { "code": null, "e": 70193, "s": 70145, "text": "Tensorflow.js tf.initializers.Initializer Class" }, { "code": null, "e": 70241, "s": 70193, "text": "Tensorflow.js tf.initializers.constant() Method" }, { "code": null, "e": 70295, "s": 70241, "text": "Tensorflow.js tf.initializers.glorotNormal() Function" }, { "code": null, "e": 70350, "s": 70295, "text": "Tensorflow.js tf.initializers.glorotUniform() Function" }, { "code": null, "e": 70400, "s": 70350, "text": "Tensorflow.js tf.initializers.heNormal() Function" }, { "code": null, "e": 70451, "s": 70400, "text": "Tensorflow.js tf.initializers.heUniform() Function" }, { "code": null, "e": 70497, "s": 70451, "text": "TensorFlow.js Initializers Complete Reference" }, { "code": null, "e": 70546, "s": 70497, "text": "Tensorflow.js tf.layers.zeroPadding2d() Function" }, { "code": null, "e": 70590, "s": 70546, "text": "Tensorflow.js tf.regularizers.l1() Function" }, { "code": null, "e": 70636, "s": 70590, "text": "Tensorflow.js tf.regularizers.l1l2() Function" }, { "code": null, "e": 70680, "s": 70636, "text": "Tensorflow.js tf.regularizers.l2() Function" }, { "code": null, "e": 70729, "s": 70680, "text": "Tensorflow.js tf.layers.zeroPadding2d() Function" }, { "code": null, "e": 70766, "s": 70729, "text": "Tensorflow.js tf.data.csv() Function" }, { "code": null, "e": 70809, "s": 70766, "text": "Tensorflow.js tf.data.generator() Function" }, { "code": null, "e": 72080, "s": 70809, "text": "Tensorflow.js tf.data.microphone() FunctionTensorflow.js RegularizesTensorFlow.js Data Creation Complete ReferenceTensorflow.js tf.data.zip() FunctionTensorflow.js tf.data.Dataset class .batch() MethodTensorflow.js DataTensorFlow.js Data Classes Complete ReferencesTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.util.assert() FunctionTensorflow.js tf.util.createShuffledIndices() FunctionTensorflow.js tf.decodeString() FunctionTensorflow.js tf.encodeString() FunctionTensorflow.js tf.fetch() FunctionTensorflow.js tf.util.flatten() FunctionTensorflow.js tf.util.now() FunctionTensorflow.js tf.util.shuffle() FunctionTensorflow.js tf.util.shuffleCombo() FunctionTensorflow.js UtilTensorflow.js tf.browser.fromPixels() FunctionTensorflow.js tf.browser.fromPixelsAsync() FunctionTensorflow.js tf.browser.toPixels() FunctionTensorFlow.js Browser Complete ReferenceTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.backend() FunctionTensorflow.js tf.getBackend() FunctionTensorflow.js tf.ready() FunctionTensorflow.js tf.registerBackend() FunctionTensorflow.js tf.removeBackend() FunctionTensorflow.js tf.setBackend() FunctionTensorflow.js BrowserTensorflow.js tf.callbacks.earlyStopping() FunctionTensorflow.js BackendsTensorflow.js Metrics" }, { "code": null, "e": 72127, "s": 72080, "text": "TensorFlow.js Data Creation Complete Reference" }, { "code": null, "e": 72164, "s": 72127, "text": "Tensorflow.js tf.data.zip() Function" }, { "code": null, "e": 72216, "s": 72164, "text": "Tensorflow.js tf.data.Dataset class .batch() Method" }, { "code": null, "e": 72263, "s": 72216, "text": "TensorFlow.js Data Classes Complete References" }, { "code": null, "e": 72312, "s": 72263, "text": "Tensorflow.js tf.layers.zeroPadding2d() Function" }, { "code": null, "e": 72352, "s": 72312, "text": "Tensorflow.js tf.util.assert() Function" }, { "code": null, "e": 72407, "s": 72352, "text": "Tensorflow.js tf.util.createShuffledIndices() Function" }, { "code": null, "e": 72448, "s": 72407, "text": "Tensorflow.js tf.decodeString() Function" }, { "code": null, "e": 72489, "s": 72448, "text": "Tensorflow.js tf.encodeString() Function" }, { "code": null, "e": 72523, "s": 72489, "text": "Tensorflow.js tf.fetch() Function" }, { "code": null, "e": 72564, "s": 72523, "text": "Tensorflow.js tf.util.flatten() Function" }, { "code": null, "e": 72601, "s": 72564, "text": "Tensorflow.js tf.util.now() Function" }, { "code": null, "e": 72642, "s": 72601, "text": "Tensorflow.js tf.util.shuffle() Function" }, { "code": null, "e": 72688, "s": 72642, "text": "Tensorflow.js tf.util.shuffleCombo() Function" }, { "code": null, "e": 72735, "s": 72688, "text": "Tensorflow.js tf.browser.fromPixels() Function" }, { "code": null, "e": 72787, "s": 72735, "text": "Tensorflow.js tf.browser.fromPixelsAsync() Function" }, { "code": null, "e": 72832, "s": 72787, "text": "Tensorflow.js tf.browser.toPixels() Function" }, { "code": null, "e": 72873, "s": 72832, "text": "TensorFlow.js Browser Complete Reference" }, { "code": null, "e": 72922, "s": 72873, "text": "Tensorflow.js tf.layers.zeroPadding2d() Function" }, { "code": null, "e": 72958, "s": 72922, "text": "Tensorflow.js tf.backend() Function" }, { "code": null, "e": 72997, "s": 72958, "text": "Tensorflow.js tf.getBackend() Function" }, { "code": null, "e": 73031, "s": 72997, "text": "Tensorflow.js tf.ready() Function" }, { "code": null, "e": 73075, "s": 73031, "text": "Tensorflow.js tf.registerBackend() Function" }, { "code": null, "e": 73117, "s": 73075, "text": "Tensorflow.js tf.removeBackend() Function" }, { "code": null, "e": 73156, "s": 73117, "text": "Tensorflow.js tf.setBackend() Function" }, { "code": null, "e": 73208, "s": 73156, "text": "Tensorflow.js tf.callbacks.earlyStopping() Function" }, { "code": null, "e": 73222, "s": 73208, "text": "TensorFlow.js" }, { "code": null, "e": 86907, "s": 73222, "text": "Tensorflow.js IntroductionTensorflow.js TensorsTensorflow.js tf.tensor() FunctionTensorflow.js tf.scalar() FunctionTenserFlow.js Tensors Creation Complete ReferenceTensorflow.js tf.Tensor class .buffer() MethodTensorflow.js tf.Tensor class .bufferSync() MethodTensorFlow.js Tensors Classes Complete ReferenceTensorflow.js tf.booleanMaskAsync() FunctionTensorflow.js tf.concat() FunctionTensorFlow.js Tensors Transformations Complete ReferenceTensorFlow.js Slicing and Joining Complete ReferenceTensorflow.js tf.einsum() FunctionTensorflow.js tf.multinomial() FunctionTensorFlow.js Tensor Random Complete ReferenceTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js ModelsTensorflow.js tf.input() FunctionTensorflow.js tf.loadGraphModel() FunctionTensorflow.js tf.io.http() FunctionTensorFlow.js Models Loading Complete ReferenceTensorflow.js tf.io.copyModel() FunctionTensorflow.js tf.io.listModels() FunctionTensorflow.js tf.io.moveModel() FunctionTensorFlow.js Models Management Complete ReferenceTensorflow.js tf.GraphModel ClassTensorflow.js tf.GraphModel class .save() MethodTensorflow.js tf.GraphModel class .predict() MethodTensorflow.js tf.GraphModel class .execute() MethodTensorFlow.js Models Classes Complete ReferenceTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.layers.elu() FunctionTensorflow.js LayersTensorflow.js tf.layers.activation() FunctionTensorFlow.js Layers Basic Complete ReferenceTensorflow.js tf.layers.conv1d() FunctionTensorFlow.js Layers Convolutional Complete ReferenceTensorflow.js tf.layers.add() FunctionTensorFlow.js Layers Merge Complete ReferenceTensorflow.js tf.layers.globalAveragePooling1d() FunctionTensorFlow.js Layers Pooling Complete ReferenceTensorFlow.js Layers Noise Complete ReferenceTensorflow.js tf.layers.bidirectional() FunctionTensorflow.js tf.layers.timeDistributed() FunctionTensorFlow.js Layers Classes Complete ReferenceTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.layers.masking() FunctionTensorflow.js tf.layers.zeroPadding2d() FunctionTensorFlow.js Operations Arithmetic Complete ReferenceTensorFlow.js Operations Basic Math Complete ReferenceTensorFlow.js Operations Matrices Complete ReferenceTensorflow.js OperationsTensorFlow.js Operations Normalization Complete ReferenceTensorFlow.js Operations Images Complete ReferenceTensorFlow.js Operations Logical Complete ReferenceTensorFlow.js Operations Evaluation Complete ReferenceTensorflow.js tf.cumsum() FunctionTensorFlow.js Operations Slicing and Joining Complete ReferenceTensorFlow.js Operations Spectral Complete ReferenceTensorflow.js tf.unsortedSegmentSum() FunctionTensorflow.js tf.movingAverage() FunctionTensorflow.js tf.dropout() FunctionTensorFlow.js Operations Signal Complete ReferenceTensorflow.js tf.linalg.bandPart() FunctionTensorflow.js tf.linalg.gramSchmidt() FunctionTensorflow.js tf.linalg.qr() FunctionTensorFlow.js Operations Sparse Complete ReferenceTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.grad() FunctionTensorflow.js tf.grads() FunctionTensorflow.js tf.customGrad() FunctionTensorFlow.js Training Gradients Complete ReferenceTensorflow.js TrainingTensorflow.js tf.train.momentum() FunctionTensorflow.js tf.train.adagrad() FunctionTensorFlow.js Training Optimizers Complete ReferenceTensorflow.js tf.losses.absoluteDifference() FunctionTensorflow.js tf.losses.computeWeightedLoss() FunctionTensorflow.js tf.losses.cosineDistance() FunctionTensorFlow.js Training Losses Complete ReferenceTensorflow.js tf.train.Optimizer ClassTensorflow.js tf.train.Optimizer class .minimize() MethodTensorFlow.js Training Classes Complete ReferenceTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.time() FunctionTensorflow.js tf.nextFrame() FunctionTensorflow.js tf.profile() FunctionTensorFlow.js Performance Memory Complete ReferenceTensorflow.js PerformanceTensorflow.js tf.disposeVariables() FunctionTensorflow.js tf.enableDebugMode() FunctionTensorflow.js tf.enableProdMode() FunctionTensorflow.js tf.engine() FunctionTensorflow.js EnvironmentTensorFlow.js Environment Complete ReferenceTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.metrics.binaryAccuracy() FunctionTensorflow.js tf.metrics.binaryCrossentropy() FunctionTensorflow.js tf.metrics.categoricalAccuracy() FunctionTensorflow.js tf.metrics.categoricalCrossentropy() FunctionTensorflow.js tf.metrics.cosineProximity() FunctionTensorflow.js ConstraintsTensorflow.js tf.metrics.meanSquaredError() FunctionTensorflow.js tf.metrics.precision() FunctionTensorflow.js tf.metrics.recall() FunctionTensorflow.js tf.metrics.sparseCategoricalAccuracy() FunctionTensorFlow.js Metrics Complete ReferenceTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.initializers.Initializer ClassTensorflow.js tf.initializers.constant() MethodTensorflow.js tf.initializers.glorotNormal() FunctionTensorflow.js tf.initializers.glorotUniform() FunctionTensorflow.js tf.initializers.heNormal() FunctionTensorflow.js tf.initializers.heUniform() FunctionTensorflow.js InitializersTensorFlow.js Initializers Complete ReferenceTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.regularizers.l1() FunctionTensorflow.js tf.regularizers.l1l2() FunctionTensorflow.js tf.regularizers.l2() FunctionTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.data.csv() FunctionTensorflow.js tf.data.generator() FunctionTensorflow.js tf.data.microphone() FunctionTensorflow.js RegularizesTensorFlow.js Data Creation Complete ReferenceTensorflow.js tf.data.zip() FunctionTensorflow.js tf.data.Dataset class .batch() MethodTensorflow.js DataTensorFlow.js Data Classes Complete ReferencesTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.util.assert() FunctionTensorflow.js tf.util.createShuffledIndices() FunctionTensorflow.js tf.decodeString() FunctionTensorflow.js tf.encodeString() FunctionTensorflow.js tf.fetch() FunctionTensorflow.js tf.util.flatten() FunctionTensorflow.js tf.util.now() FunctionTensorflow.js tf.util.shuffle() FunctionTensorflow.js tf.util.shuffleCombo() FunctionTensorflow.js UtilTensorflow.js tf.browser.fromPixels() FunctionTensorflow.js tf.browser.fromPixelsAsync() FunctionTensorflow.js tf.browser.toPixels() FunctionTensorFlow.js Browser Complete ReferenceTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.backend() FunctionTensorflow.js tf.getBackend() FunctionTensorflow.js tf.ready() FunctionTensorflow.js tf.registerBackend() FunctionTensorflow.js tf.removeBackend() FunctionTensorflow.js tf.setBackend() FunctionTensorflow.js BrowserTensorflow.js tf.callbacks.earlyStopping() FunctionTensorflow.js BackendsTensorflow.js MetricsImprove Article\n\nSave Article\n\nLike Article\n\nTensorflow.js tf.layers.zeroPadding2d() FunctionLast Updated :\n17 Feb, 2022Tensorflow.js is an open-source library developed by Google for running machine learning models and deep learning neural networks in the browser or node environment.The tf.layers.zeroPadding2d( ) function is used for adding rows and columns for zeros at the top, bottom, left, and right side of and image tensor.Syntax: tf.layers.zeroPadding2d(args); Parameters: This method accepts the args as a parameter which has the following properties:Padding: This variable accepts an integer, or an Array of 2 integers, or Array of 2 Arrays, each of which is an array of 2 integers. Interpretation of this variable is:If a variable is an integer, the same symmetric is applied to width and height.If a variable is an array of 2 integers, interpreted as two different symmetric values of height and width.If a variable is an array of 2 arrays, interpreted as topPad, bottomPad for the first array, and leftPad, rightPad for the second array.dataFormat: This variable define the format of the shape of the input Tensor. If can be channelsLast or channelsFirst. This value defines the ordering of the dimensions in the inputs. The channelsLast define shape [ batch, height, width, channels] while channelsFirst define [ batch, channels, height, width].inputShape: It can be null or an array of numbers. It is used to create an input layer to insert before the following layer. This variable is only used for the first layer of a model.batchInputShape: This variable accept null or array of number. This variable works the same as inputShape but If both inputShape and batchInputShape are defined, batchInputShape is used. This variable is only used for the first layer of a model.batchSize: It is a number, and It helps batchInputShape variable. if batchInputShape is not defined it is used for creating batchInputShape.dtype: This variable is used for defining data type for the padding layer. It is Default to ‘float32’. This variable is only used for first layer of a model.name: It defined the name of layer.trainable: It is a boolean type. It defined layer data are updatable by fit or not. Defaults value is true.weights: It is tf.Tensor type. It declares the Initial weight values of the layer.inputDType: It defines the data type of the input layer. Legacy support. Do not use for new code.Returns: It returns ZeroPadding2D object.Example 1: In this example, we add a zero-padding layer with default values.JavascriptJavascript// Importing tensorflowconst tf = require(\"@tensorflow/tfjs\") // Input 4d Tensor const img4d = tf.tensor4d([1, 2, 3, 4], [1, 2, 2, 1]); // Adding padding in Tensorconst pad = tf.layers.zeroPadding2d();const imgpad = pad.apply(img4d); // Printing 4d Tensor with padding</div>imgpad.print() Output: Tensor [[[[0], [0], [0], [0]],\n [[0], [1], [2], [0]],\n [[0], [3], [4], [0]],\n [[0], [0], [0], [0]]]]Example 2: In this example, we add zero paddings in tensor of specific data type and with define data-Format. JavascriptJavascript// Importing tensorflowconst tf = require(\"@tensorflow/tfjs\") // Input 4d Tensor const img4d = tf.tensor4d([1, 2, 3, 4], [1, 2, 2, 1]); // Adding padding in Tensorconst pad = tf.layers.zeroPadding2d({ padding: 2, dataFormat: 'channelsFirst', dtype: 'int32'}); const imgpad = pad.apply(img4d); // Printing 4d Tensor with paddingimgpad.print() Output: Tensor\n [[[[0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0],\n [0, 0, 1, 0, 0],\n [0, 0, 2, 0, 0],\n [0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0]],\n\n [[0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0],\n [0, 0, 3, 0, 0],\n [0, 0, 4, 0, 0],\n [0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0]]]] Reference: https://js.tensorflow.org/api/latest/#layers.zeroPadding2d My Personal Notes\narrow_drop_upSave\n\nLike2PreviousTensorFlow.js Browser Complete ReferenceNext\nTensorflow.js tf.backend() FunctionRecommended ArticlesPage :How to get the function name from within that function using JavaScript ?30, May 19How to call a function that return another function in JavaScript ?24, Jul 19How to get the function name inside a function in PHP ?25, Sep 19Python - Call function from another function04, Dec 19How to Check a Function is a Generator Function or not using JavaScript ?26, Mar 20How to implement a function that enable another function after specified time using JavaScript ?10, Mar 21How to create a function that invokes the provided function with its arguments transformed in JavaScript?18, Jul 21How to create a function that invokes each provided function with the arguments it receives using JavaScript ?25, May 21How to create a function that invokes function with partials prepended arguments in JavaScript ?26, Jul 21Difference between ‘function declaration’ and ‘function expression' in JavaScript20, Sep 21Find the power function that the graph of f resembles for large values of |x|, given the function f(x) = (x + 6)2 (x - 2)210, Oct 21Difference between Function.prototype.apply and Function.prototype.call16, Nov 21Explain the differences on the usage of foo between function foo() {} and var foo = function() {}02, Mar 22How does TypeScript support optional parameters in function as every parameter is optional for a function in JavaScript ?24, Mar 22What are the advantages of synchronous function over asynchronous function in Node.js ?28, Mar 22How to create a function that invokes function with partials appended to the arguments in JavaScript ?28, May 21PHP | imagecreatetruecolor() Function18, Sep 18p5.js | year() function07, Apr 19D3.js | d3.utcTuesdays() Function24, Jul 19PHP | ImagickDraw getTextAlignment() Function16, Dec 19PHP | Ds\\Sequence last() Function24, Jan 19PHP | Imagick floodFillPaintImage() Function30, Jul 19Function to escape regex patterns before applied in PHP31, Oct 19PHP | array_udiff_uassoc() Function11, Jul 18Article Contributed By :satyam00so@satyam00soVote for difficultyEasy\nNormal\nMedium\nHard\nExpertImproved By :anikakapooradnanirshad158germanshephered48Article Tags :PickedTensorflow.jsJavaScriptWeb TechnologiesImprove ArticleReport IssueWriting code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here.\nLoad CommentsWhat's NewInterview Series- Prepare, Practice & UpskillView DetailsData Structures & Algorithms- Self Paced CourseView DetailsComplete Interview PreparationView DetailsMost popular in JavaScriptRemove elements from a JavaScript ArrayConvert a string to an integer in JavaScriptDifference between var, let and const keywords in JavaScriptHow to calculate the number of days between two dates in javascript?Differences between Functional Components and Class Components in ReactMost visited in Web TechnologiesRemove elements from a JavaScript ArrayInstallation of Node.js on LinuxConvert a string to an integer in JavaScriptHow to fetch data from an API in ReactJS ?How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 86942, "s": 86907, "text": "Tensorflow.js tf.tensor() Function" }, { "code": null, "e": 86977, "s": 86942, "text": "Tensorflow.js tf.scalar() Function" }, { "code": null, "e": 87027, "s": 86977, "text": "TenserFlow.js Tensors Creation Complete Reference" }, { "code": null, "e": 87074, "s": 87027, "text": "Tensorflow.js tf.Tensor class .buffer() Method" }, { "code": null, "e": 87125, "s": 87074, "text": "Tensorflow.js tf.Tensor class .bufferSync() Method" }, { "code": null, "e": 87174, "s": 87125, "text": "TensorFlow.js Tensors Classes Complete Reference" }, { "code": null, "e": 87219, "s": 87174, "text": "Tensorflow.js tf.booleanMaskAsync() Function" }, { "code": null, "e": 87254, "s": 87219, "text": "Tensorflow.js tf.concat() Function" }, { "code": null, "e": 87311, "s": 87254, "text": "TensorFlow.js Tensors Transformations Complete Reference" }, { "code": null, "e": 87364, "s": 87311, "text": "TensorFlow.js Slicing and Joining Complete Reference" }, { "code": null, "e": 87399, "s": 87364, "text": "Tensorflow.js tf.einsum() Function" }, { "code": null, "e": 87439, "s": 87399, "text": "Tensorflow.js tf.multinomial() Function" }, { "code": null, "e": 87486, "s": 87439, "text": "TensorFlow.js Tensor Random Complete Reference" }, { "code": null, "e": 87535, "s": 87486, "text": "Tensorflow.js tf.layers.zeroPadding2d() Function" }, { "code": null, "e": 87569, "s": 87535, "text": "Tensorflow.js tf.input() Function" }, { "code": null, "e": 87612, "s": 87569, "text": "Tensorflow.js tf.loadGraphModel() Function" }, { "code": null, "e": 87648, "s": 87612, "text": "Tensorflow.js tf.io.http() Function" }, { "code": null, "e": 87696, "s": 87648, "text": "TensorFlow.js Models Loading Complete Reference" }, { "code": null, "e": 87737, "s": 87696, "text": "Tensorflow.js tf.io.copyModel() Function" }, { "code": null, "e": 87779, "s": 87737, "text": "Tensorflow.js tf.io.listModels() Function" }, { "code": null, "e": 87820, "s": 87779, "text": "Tensorflow.js tf.io.moveModel() Function" }, { "code": null, "e": 87871, "s": 87820, "text": "TensorFlow.js Models Management Complete Reference" }, { "code": null, "e": 87905, "s": 87871, "text": "Tensorflow.js tf.GraphModel Class" }, { "code": null, "e": 87954, "s": 87905, "text": "Tensorflow.js tf.GraphModel class .save() Method" }, { "code": null, "e": 88006, "s": 87954, "text": "Tensorflow.js tf.GraphModel class .predict() Method" }, { "code": null, "e": 88058, "s": 88006, "text": "Tensorflow.js tf.GraphModel class .execute() Method" }, { "code": null, "e": 88106, "s": 88058, "text": "TensorFlow.js Models Classes Complete Reference" }, { "code": null, "e": 88155, "s": 88106, "text": "Tensorflow.js tf.layers.zeroPadding2d() Function" }, { "code": null, "e": 88194, "s": 88155, "text": "Tensorflow.js tf.layers.elu() Function" }, { "code": null, "e": 88240, "s": 88194, "text": "Tensorflow.js tf.layers.activation() Function" }, { "code": null, "e": 88286, "s": 88240, "text": "TensorFlow.js Layers Basic Complete Reference" }, { "code": null, "e": 88328, "s": 88286, "text": "Tensorflow.js tf.layers.conv1d() Function" }, { "code": null, "e": 88382, "s": 88328, "text": "TensorFlow.js Layers Convolutional Complete Reference" }, { "code": null, "e": 88421, "s": 88382, "text": "Tensorflow.js tf.layers.add() Function" }, { "code": null, "e": 88467, "s": 88421, "text": "TensorFlow.js Layers Merge Complete Reference" }, { "code": null, "e": 88525, "s": 88467, "text": "Tensorflow.js tf.layers.globalAveragePooling1d() Function" }, { "code": null, "e": 88573, "s": 88525, "text": "TensorFlow.js Layers Pooling Complete Reference" }, { "code": null, "e": 88619, "s": 88573, "text": "TensorFlow.js Layers Noise Complete Reference" }, { "code": null, "e": 88668, "s": 88619, "text": "Tensorflow.js tf.layers.bidirectional() Function" }, { "code": null, "e": 88719, "s": 88668, "text": "Tensorflow.js tf.layers.timeDistributed() Function" }, { "code": null, "e": 88767, "s": 88719, "text": "TensorFlow.js Layers Classes Complete Reference" }, { "code": null, "e": 88816, "s": 88767, "text": "Tensorflow.js tf.layers.zeroPadding2d() Function" }, { "code": null, "e": 88859, "s": 88816, "text": "Tensorflow.js tf.layers.masking() Function" }, { "code": null, "e": 88908, "s": 88859, "text": "Tensorflow.js tf.layers.zeroPadding2d() Function" }, { "code": null, "e": 88963, "s": 88908, "text": "TensorFlow.js Operations Arithmetic Complete Reference" }, { "code": null, "e": 89018, "s": 88963, "text": "TensorFlow.js Operations Basic Math Complete Reference" }, { "code": null, "e": 89071, "s": 89018, "text": "TensorFlow.js Operations Matrices Complete Reference" }, { "code": null, "e": 89129, "s": 89071, "text": "TensorFlow.js Operations Normalization Complete Reference" }, { "code": null, "e": 89180, "s": 89129, "text": "TensorFlow.js Operations Images Complete Reference" }, { "code": null, "e": 89232, "s": 89180, "text": "TensorFlow.js Operations Logical Complete Reference" }, { "code": null, "e": 89287, "s": 89232, "text": "TensorFlow.js Operations Evaluation Complete Reference" }, { "code": null, "e": 89322, "s": 89287, "text": "Tensorflow.js tf.cumsum() Function" }, { "code": null, "e": 89386, "s": 89322, "text": "TensorFlow.js Operations Slicing and Joining Complete Reference" }, { "code": null, "e": 89439, "s": 89386, "text": "TensorFlow.js Operations Spectral Complete Reference" }, { "code": null, "e": 89486, "s": 89439, "text": "Tensorflow.js tf.unsortedSegmentSum() Function" }, { "code": null, "e": 89528, "s": 89486, "text": "Tensorflow.js tf.movingAverage() Function" }, { "code": null, "e": 89564, "s": 89528, "text": "Tensorflow.js tf.dropout() Function" }, { "code": null, "e": 89615, "s": 89564, "text": "TensorFlow.js Operations Signal Complete Reference" }, { "code": null, "e": 89659, "s": 89615, "text": "Tensorflow.js tf.linalg.bandPart() Function" }, { "code": null, "e": 89706, "s": 89659, "text": "Tensorflow.js tf.linalg.gramSchmidt() Function" }, { "code": null, "e": 89744, "s": 89706, "text": "Tensorflow.js tf.linalg.qr() Function" }, { "code": null, "e": 89795, "s": 89744, "text": "TensorFlow.js Operations Sparse Complete Reference" }, { "code": null, "e": 89844, "s": 89795, "text": "Tensorflow.js tf.layers.zeroPadding2d() Function" }, { "code": null, "e": 89877, "s": 89844, "text": "Tensorflow.js tf.grad() Function" }, { "code": null, "e": 89911, "s": 89877, "text": "Tensorflow.js tf.grads() Function" }, { "code": null, "e": 89950, "s": 89911, "text": "Tensorflow.js tf.customGrad() Function" }, { "code": null, "e": 100547, "s": 89950, "text": "TensorFlow.js Training Gradients Complete ReferenceTensorflow.js TrainingTensorflow.js tf.train.momentum() FunctionTensorflow.js tf.train.adagrad() FunctionTensorFlow.js Training Optimizers Complete ReferenceTensorflow.js tf.losses.absoluteDifference() FunctionTensorflow.js tf.losses.computeWeightedLoss() FunctionTensorflow.js tf.losses.cosineDistance() FunctionTensorFlow.js Training Losses Complete ReferenceTensorflow.js tf.train.Optimizer ClassTensorflow.js tf.train.Optimizer class .minimize() MethodTensorFlow.js Training Classes Complete ReferenceTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.time() FunctionTensorflow.js tf.nextFrame() FunctionTensorflow.js tf.profile() FunctionTensorFlow.js Performance Memory Complete ReferenceTensorflow.js PerformanceTensorflow.js tf.disposeVariables() FunctionTensorflow.js tf.enableDebugMode() FunctionTensorflow.js tf.enableProdMode() FunctionTensorflow.js tf.engine() FunctionTensorflow.js EnvironmentTensorFlow.js Environment Complete ReferenceTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.metrics.binaryAccuracy() FunctionTensorflow.js tf.metrics.binaryCrossentropy() FunctionTensorflow.js tf.metrics.categoricalAccuracy() FunctionTensorflow.js tf.metrics.categoricalCrossentropy() FunctionTensorflow.js tf.metrics.cosineProximity() FunctionTensorflow.js ConstraintsTensorflow.js tf.metrics.meanSquaredError() FunctionTensorflow.js tf.metrics.precision() FunctionTensorflow.js tf.metrics.recall() FunctionTensorflow.js tf.metrics.sparseCategoricalAccuracy() FunctionTensorFlow.js Metrics Complete ReferenceTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.initializers.Initializer ClassTensorflow.js tf.initializers.constant() MethodTensorflow.js tf.initializers.glorotNormal() FunctionTensorflow.js tf.initializers.glorotUniform() FunctionTensorflow.js tf.initializers.heNormal() FunctionTensorflow.js tf.initializers.heUniform() FunctionTensorflow.js InitializersTensorFlow.js Initializers Complete ReferenceTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.regularizers.l1() FunctionTensorflow.js tf.regularizers.l1l2() FunctionTensorflow.js tf.regularizers.l2() FunctionTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.data.csv() FunctionTensorflow.js tf.data.generator() FunctionTensorflow.js tf.data.microphone() FunctionTensorflow.js RegularizesTensorFlow.js Data Creation Complete ReferenceTensorflow.js tf.data.zip() FunctionTensorflow.js tf.data.Dataset class .batch() MethodTensorflow.js DataTensorFlow.js Data Classes Complete ReferencesTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.util.assert() FunctionTensorflow.js tf.util.createShuffledIndices() FunctionTensorflow.js tf.decodeString() FunctionTensorflow.js tf.encodeString() FunctionTensorflow.js tf.fetch() FunctionTensorflow.js tf.util.flatten() FunctionTensorflow.js tf.util.now() FunctionTensorflow.js tf.util.shuffle() FunctionTensorflow.js tf.util.shuffleCombo() FunctionTensorflow.js UtilTensorflow.js tf.browser.fromPixels() FunctionTensorflow.js tf.browser.fromPixelsAsync() FunctionTensorflow.js tf.browser.toPixels() FunctionTensorFlow.js Browser Complete ReferenceTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.backend() FunctionTensorflow.js tf.getBackend() FunctionTensorflow.js tf.ready() FunctionTensorflow.js tf.registerBackend() FunctionTensorflow.js tf.removeBackend() FunctionTensorflow.js tf.setBackend() FunctionTensorflow.js BrowserTensorflow.js tf.callbacks.earlyStopping() FunctionTensorflow.js BackendsTensorflow.js MetricsImprove Article\n\nSave Article\n\nLike Article\n\nTensorflow.js tf.layers.zeroPadding2d() FunctionLast Updated :\n17 Feb, 2022Tensorflow.js is an open-source library developed by Google for running machine learning models and deep learning neural networks in the browser or node environment.The tf.layers.zeroPadding2d( ) function is used for adding rows and columns for zeros at the top, bottom, left, and right side of and image tensor.Syntax: tf.layers.zeroPadding2d(args); Parameters: This method accepts the args as a parameter which has the following properties:Padding: This variable accepts an integer, or an Array of 2 integers, or Array of 2 Arrays, each of which is an array of 2 integers. Interpretation of this variable is:If a variable is an integer, the same symmetric is applied to width and height.If a variable is an array of 2 integers, interpreted as two different symmetric values of height and width.If a variable is an array of 2 arrays, interpreted as topPad, bottomPad for the first array, and leftPad, rightPad for the second array.dataFormat: This variable define the format of the shape of the input Tensor. If can be channelsLast or channelsFirst. This value defines the ordering of the dimensions in the inputs. The channelsLast define shape [ batch, height, width, channels] while channelsFirst define [ batch, channels, height, width].inputShape: It can be null or an array of numbers. It is used to create an input layer to insert before the following layer. This variable is only used for the first layer of a model.batchInputShape: This variable accept null or array of number. This variable works the same as inputShape but If both inputShape and batchInputShape are defined, batchInputShape is used. This variable is only used for the first layer of a model.batchSize: It is a number, and It helps batchInputShape variable. if batchInputShape is not defined it is used for creating batchInputShape.dtype: This variable is used for defining data type for the padding layer. It is Default to ‘float32’. This variable is only used for first layer of a model.name: It defined the name of layer.trainable: It is a boolean type. It defined layer data are updatable by fit or not. Defaults value is true.weights: It is tf.Tensor type. It declares the Initial weight values of the layer.inputDType: It defines the data type of the input layer. Legacy support. Do not use for new code.Returns: It returns ZeroPadding2D object.Example 1: In this example, we add a zero-padding layer with default values.JavascriptJavascript// Importing tensorflowconst tf = require(\"@tensorflow/tfjs\") // Input 4d Tensor const img4d = tf.tensor4d([1, 2, 3, 4], [1, 2, 2, 1]); // Adding padding in Tensorconst pad = tf.layers.zeroPadding2d();const imgpad = pad.apply(img4d); // Printing 4d Tensor with padding</div>imgpad.print() Output: Tensor [[[[0], [0], [0], [0]],\n [[0], [1], [2], [0]],\n [[0], [3], [4], [0]],\n [[0], [0], [0], [0]]]]Example 2: In this example, we add zero paddings in tensor of specific data type and with define data-Format. JavascriptJavascript// Importing tensorflowconst tf = require(\"@tensorflow/tfjs\") // Input 4d Tensor const img4d = tf.tensor4d([1, 2, 3, 4], [1, 2, 2, 1]); // Adding padding in Tensorconst pad = tf.layers.zeroPadding2d({ padding: 2, dataFormat: 'channelsFirst', dtype: 'int32'}); const imgpad = pad.apply(img4d); // Printing 4d Tensor with paddingimgpad.print() Output: Tensor\n [[[[0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0],\n [0, 0, 1, 0, 0],\n [0, 0, 2, 0, 0],\n [0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0]],\n\n [[0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0],\n [0, 0, 3, 0, 0],\n [0, 0, 4, 0, 0],\n [0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0]]]] Reference: https://js.tensorflow.org/api/latest/#layers.zeroPadding2d My Personal Notes\narrow_drop_upSave\n\nLike2PreviousTensorFlow.js Browser Complete ReferenceNext\nTensorflow.js tf.backend() FunctionRecommended ArticlesPage :How to get the function name from within that function using JavaScript ?30, May 19How to call a function that return another function in JavaScript ?24, Jul 19How to get the function name inside a function in PHP ?25, Sep 19Python - Call function from another function04, Dec 19How to Check a Function is a Generator Function or not using JavaScript ?26, Mar 20How to implement a function that enable another function after specified time using JavaScript ?10, Mar 21How to create a function that invokes the provided function with its arguments transformed in JavaScript?18, Jul 21How to create a function that invokes each provided function with the arguments it receives using JavaScript ?25, May 21How to create a function that invokes function with partials prepended arguments in JavaScript ?26, Jul 21Difference between ‘function declaration’ and ‘function expression' in JavaScript20, Sep 21Find the power function that the graph of f resembles for large values of |x|, given the function f(x) = (x + 6)2 (x - 2)210, Oct 21Difference between Function.prototype.apply and Function.prototype.call16, Nov 21Explain the differences on the usage of foo between function foo() {} and var foo = function() {}02, Mar 22How does TypeScript support optional parameters in function as every parameter is optional for a function in JavaScript ?24, Mar 22What are the advantages of synchronous function over asynchronous function in Node.js ?28, Mar 22How to create a function that invokes function with partials appended to the arguments in JavaScript ?28, May 21PHP | imagecreatetruecolor() Function18, Sep 18p5.js | year() function07, Apr 19D3.js | d3.utcTuesdays() Function24, Jul 19PHP | ImagickDraw getTextAlignment() Function16, Dec 19PHP | Ds\\Sequence last() Function24, Jan 19PHP | Imagick floodFillPaintImage() Function30, Jul 19Function to escape regex patterns before applied in PHP31, Oct 19PHP | array_udiff_uassoc() Function11, Jul 18Article Contributed By :satyam00so@satyam00soVote for difficultyEasy\nNormal\nMedium\nHard\nExpertImproved By :anikakapooradnanirshad158germanshephered48Article Tags :PickedTensorflow.jsJavaScriptWeb TechnologiesImprove ArticleReport IssueWriting code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here.\nLoad CommentsWhat's NewInterview Series- Prepare, Practice & UpskillView DetailsData Structures & Algorithms- Self Paced CourseView DetailsComplete Interview PreparationView DetailsMost popular in JavaScriptRemove elements from a JavaScript ArrayConvert a string to an integer in JavaScriptDifference between var, let and const keywords in JavaScriptHow to calculate the number of days between two dates in javascript?Differences between Functional Components and Class Components in ReactMost visited in Web TechnologiesRemove elements from a JavaScript ArrayInstallation of Node.js on LinuxConvert a string to an integer in JavaScriptHow to fetch data from an API in ReactJS ?How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 100590, "s": 100547, "text": "Tensorflow.js tf.train.momentum() Function" }, { "code": null, "e": 100632, "s": 100590, "text": "Tensorflow.js tf.train.adagrad() Function" }, { "code": null, "e": 100685, "s": 100632, "text": "TensorFlow.js Training Optimizers Complete Reference" }, { "code": null, "e": 100739, "s": 100685, "text": "Tensorflow.js tf.losses.absoluteDifference() Function" }, { "code": null, "e": 100794, "s": 100739, "text": "Tensorflow.js tf.losses.computeWeightedLoss() Function" }, { "code": null, "e": 100844, "s": 100794, "text": "Tensorflow.js tf.losses.cosineDistance() Function" }, { "code": null, "e": 100893, "s": 100844, "text": "TensorFlow.js Training Losses Complete Reference" }, { "code": null, "e": 100932, "s": 100893, "text": "Tensorflow.js tf.train.Optimizer Class" }, { "code": null, "e": 100990, "s": 100932, "text": "Tensorflow.js tf.train.Optimizer class .minimize() Method" }, { "code": null, "e": 101040, "s": 100990, "text": "TensorFlow.js Training Classes Complete Reference" }, { "code": null, "e": 101089, "s": 101040, "text": "Tensorflow.js tf.layers.zeroPadding2d() Function" }, { "code": null, "e": 101122, "s": 101089, "text": "Tensorflow.js tf.time() Function" }, { "code": null, "e": 101160, "s": 101122, "text": "Tensorflow.js tf.nextFrame() Function" }, { "code": null, "e": 101196, "s": 101160, "text": "Tensorflow.js tf.profile() Function" }, { "code": null, "e": 101248, "s": 101196, "text": "TensorFlow.js Performance Memory Complete Reference" }, { "code": null, "e": 101293, "s": 101248, "text": "Tensorflow.js tf.disposeVariables() Function" }, { "code": null, "e": 101337, "s": 101293, "text": "Tensorflow.js tf.enableDebugMode() Function" }, { "code": null, "e": 101380, "s": 101337, "text": "Tensorflow.js tf.enableProdMode() Function" }, { "code": null, "e": 104060, "s": 101380, "text": "Tensorflow.js tf.engine() FunctionTensorflow.js EnvironmentTensorFlow.js Environment Complete ReferenceTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.metrics.binaryAccuracy() FunctionTensorflow.js tf.metrics.binaryCrossentropy() FunctionTensorflow.js tf.metrics.categoricalAccuracy() FunctionTensorflow.js tf.metrics.categoricalCrossentropy() FunctionTensorflow.js tf.metrics.cosineProximity() FunctionTensorflow.js ConstraintsTensorflow.js tf.metrics.meanSquaredError() FunctionTensorflow.js tf.metrics.precision() FunctionTensorflow.js tf.metrics.recall() FunctionTensorflow.js tf.metrics.sparseCategoricalAccuracy() FunctionTensorFlow.js Metrics Complete ReferenceTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.initializers.Initializer ClassTensorflow.js tf.initializers.constant() MethodTensorflow.js tf.initializers.glorotNormal() FunctionTensorflow.js tf.initializers.glorotUniform() FunctionTensorflow.js tf.initializers.heNormal() FunctionTensorflow.js tf.initializers.heUniform() FunctionTensorflow.js InitializersTensorFlow.js Initializers Complete ReferenceTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.regularizers.l1() FunctionTensorflow.js tf.regularizers.l1l2() FunctionTensorflow.js tf.regularizers.l2() FunctionTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.data.csv() FunctionTensorflow.js tf.data.generator() FunctionTensorflow.js tf.data.microphone() FunctionTensorflow.js RegularizesTensorFlow.js Data Creation Complete ReferenceTensorflow.js tf.data.zip() FunctionTensorflow.js tf.data.Dataset class .batch() MethodTensorflow.js DataTensorFlow.js Data Classes Complete ReferencesTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.util.assert() FunctionTensorflow.js tf.util.createShuffledIndices() FunctionTensorflow.js tf.decodeString() FunctionTensorflow.js tf.encodeString() FunctionTensorflow.js tf.fetch() FunctionTensorflow.js tf.util.flatten() FunctionTensorflow.js tf.util.now() FunctionTensorflow.js tf.util.shuffle() FunctionTensorflow.js tf.util.shuffleCombo() FunctionTensorflow.js UtilTensorflow.js tf.browser.fromPixels() FunctionTensorflow.js tf.browser.fromPixelsAsync() FunctionTensorflow.js tf.browser.toPixels() FunctionTensorFlow.js Browser Complete ReferenceTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.backend() FunctionTensorflow.js tf.getBackend() FunctionTensorflow.js tf.ready() FunctionTensorflow.js tf.registerBackend() FunctionTensorflow.js tf.removeBackend() FunctionTensorflow.js tf.setBackend() FunctionTensorflow.js BrowserTensorflow.js tf.callbacks.earlyStopping() FunctionTensorflow.js BackendsTensorflow.js Metrics" }, { "code": null, "e": 104105, "s": 104060, "text": "TensorFlow.js Environment Complete Reference" }, { "code": null, "e": 104154, "s": 104105, "text": "Tensorflow.js tf.layers.zeroPadding2d() Function" }, { "code": null, "e": 104205, "s": 104154, "text": "Tensorflow.js tf.metrics.binaryAccuracy() Function" }, { "code": null, "e": 104260, "s": 104205, "text": "Tensorflow.js tf.metrics.binaryCrossentropy() Function" }, { "code": null, "e": 104316, "s": 104260, "text": "Tensorflow.js tf.metrics.categoricalAccuracy() Function" }, { "code": null, "e": 104376, "s": 104316, "text": "Tensorflow.js tf.metrics.categoricalCrossentropy() Function" }, { "code": null, "e": 104428, "s": 104376, "text": "Tensorflow.js tf.metrics.cosineProximity() Function" }, { "code": null, "e": 104481, "s": 104428, "text": "Tensorflow.js tf.metrics.meanSquaredError() Function" }, { "code": null, "e": 104527, "s": 104481, "text": "Tensorflow.js tf.metrics.precision() Function" }, { "code": null, "e": 104570, "s": 104527, "text": "Tensorflow.js tf.metrics.recall() Function" }, { "code": null, "e": 104632, "s": 104570, "text": "Tensorflow.js tf.metrics.sparseCategoricalAccuracy() Function" }, { "code": null, "e": 104673, "s": 104632, "text": "TensorFlow.js Metrics Complete Reference" }, { "code": null, "e": 104722, "s": 104673, "text": "Tensorflow.js tf.layers.zeroPadding2d() Function" }, { "code": null, "e": 104770, "s": 104722, "text": "Tensorflow.js tf.initializers.Initializer Class" }, { "code": null, "e": 104818, "s": 104770, "text": "Tensorflow.js tf.initializers.constant() Method" }, { "code": null, "e": 104872, "s": 104818, "text": "Tensorflow.js tf.initializers.glorotNormal() Function" }, { "code": null, "e": 104927, "s": 104872, "text": "Tensorflow.js tf.initializers.glorotUniform() Function" }, { "code": null, "e": 104977, "s": 104927, "text": "Tensorflow.js tf.initializers.heNormal() Function" }, { "code": null, "e": 105028, "s": 104977, "text": "Tensorflow.js tf.initializers.heUniform() Function" }, { "code": null, "e": 105074, "s": 105028, "text": "TensorFlow.js Initializers Complete Reference" }, { "code": null, "e": 105123, "s": 105074, "text": "Tensorflow.js tf.layers.zeroPadding2d() Function" }, { "code": null, "e": 105167, "s": 105123, "text": "Tensorflow.js tf.regularizers.l1() Function" }, { "code": null, "e": 105213, "s": 105167, "text": "Tensorflow.js tf.regularizers.l1l2() Function" }, { "code": null, "e": 105257, "s": 105213, "text": "Tensorflow.js tf.regularizers.l2() Function" }, { "code": null, "e": 105306, "s": 105257, "text": "Tensorflow.js tf.layers.zeroPadding2d() Function" }, { "code": null, "e": 105343, "s": 105306, "text": "Tensorflow.js tf.data.csv() Function" }, { "code": null, "e": 105386, "s": 105343, "text": "Tensorflow.js tf.data.generator() Function" }, { "code": null, "e": 106657, "s": 105386, "text": "Tensorflow.js tf.data.microphone() FunctionTensorflow.js RegularizesTensorFlow.js Data Creation Complete ReferenceTensorflow.js tf.data.zip() FunctionTensorflow.js tf.data.Dataset class .batch() MethodTensorflow.js DataTensorFlow.js Data Classes Complete ReferencesTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.util.assert() FunctionTensorflow.js tf.util.createShuffledIndices() FunctionTensorflow.js tf.decodeString() FunctionTensorflow.js tf.encodeString() FunctionTensorflow.js tf.fetch() FunctionTensorflow.js tf.util.flatten() FunctionTensorflow.js tf.util.now() FunctionTensorflow.js tf.util.shuffle() FunctionTensorflow.js tf.util.shuffleCombo() FunctionTensorflow.js UtilTensorflow.js tf.browser.fromPixels() FunctionTensorflow.js tf.browser.fromPixelsAsync() FunctionTensorflow.js tf.browser.toPixels() FunctionTensorFlow.js Browser Complete ReferenceTensorflow.js tf.layers.zeroPadding2d() FunctionTensorflow.js tf.backend() FunctionTensorflow.js tf.getBackend() FunctionTensorflow.js tf.ready() FunctionTensorflow.js tf.registerBackend() FunctionTensorflow.js tf.removeBackend() FunctionTensorflow.js tf.setBackend() FunctionTensorflow.js BrowserTensorflow.js tf.callbacks.earlyStopping() FunctionTensorflow.js BackendsTensorflow.js Metrics" }, { "code": null, "e": 106704, "s": 106657, "text": "TensorFlow.js Data Creation Complete Reference" }, { "code": null, "e": 106741, "s": 106704, "text": "Tensorflow.js tf.data.zip() Function" }, { "code": null, "e": 106793, "s": 106741, "text": "Tensorflow.js tf.data.Dataset class .batch() Method" }, { "code": null, "e": 106840, "s": 106793, "text": "TensorFlow.js Data Classes Complete References" }, { "code": null, "e": 106889, "s": 106840, "text": "Tensorflow.js tf.layers.zeroPadding2d() Function" }, { "code": null, "e": 106929, "s": 106889, "text": "Tensorflow.js tf.util.assert() Function" }, { "code": null, "e": 106984, "s": 106929, "text": "Tensorflow.js tf.util.createShuffledIndices() Function" }, { "code": null, "e": 107025, "s": 106984, "text": "Tensorflow.js tf.decodeString() Function" }, { "code": null, "e": 107066, "s": 107025, "text": "Tensorflow.js tf.encodeString() Function" }, { "code": null, "e": 107100, "s": 107066, "text": "Tensorflow.js tf.fetch() Function" }, { "code": null, "e": 107141, "s": 107100, "text": "Tensorflow.js tf.util.flatten() Function" }, { "code": null, "e": 107178, "s": 107141, "text": "Tensorflow.js tf.util.now() Function" }, { "code": null, "e": 107219, "s": 107178, "text": "Tensorflow.js tf.util.shuffle() Function" }, { "code": null, "e": 107265, "s": 107219, "text": "Tensorflow.js tf.util.shuffleCombo() Function" }, { "code": null, "e": 107312, "s": 107265, "text": "Tensorflow.js tf.browser.fromPixels() Function" }, { "code": null, "e": 107364, "s": 107312, "text": "Tensorflow.js tf.browser.fromPixelsAsync() Function" }, { "code": null, "e": 107409, "s": 107364, "text": "Tensorflow.js tf.browser.toPixels() Function" }, { "code": null, "e": 107450, "s": 107409, "text": "TensorFlow.js Browser Complete Reference" }, { "code": null, "e": 107499, "s": 107450, "text": "Tensorflow.js tf.layers.zeroPadding2d() Function" }, { "code": null, "e": 107535, "s": 107499, "text": "Tensorflow.js tf.backend() Function" }, { "code": null, "e": 107574, "s": 107535, "text": "Tensorflow.js tf.getBackend() Function" }, { "code": null, "e": 107608, "s": 107574, "text": "Tensorflow.js tf.ready() Function" }, { "code": null, "e": 107652, "s": 107608, "text": "Tensorflow.js tf.registerBackend() Function" }, { "code": null, "e": 107694, "s": 107652, "text": "Tensorflow.js tf.removeBackend() Function" }, { "code": null, "e": 107733, "s": 107694, "text": "Tensorflow.js tf.setBackend() Function" }, { "code": null, "e": 107785, "s": 107733, "text": "Tensorflow.js tf.callbacks.earlyStopping() Function" }, { "code": null, "e": 107813, "s": 107785, "text": "Last Updated :\n17 Feb, 2022" }, { "code": null, "e": 107979, "s": 107813, "text": "Tensorflow.js is an open-source library developed by Google for running machine learning models and deep learning neural networks in the browser or node environment." }, { "code": null, "e": 108127, "s": 107979, "text": "The tf.layers.zeroPadding2d( ) function is used for adding rows and columns for zeros at the top, bottom, left, and right side of and image tensor." }, { "code": null, "e": 108136, "s": 108127, "text": "Syntax: " }, { "code": null, "e": 108167, "s": 108136, "text": "tf.layers.zeroPadding2d(args);" }, { "code": null, "e": 108260, "s": 108167, "text": " Parameters: This method accepts the args as a parameter which has the following properties:" }, { "code": null, "e": 108751, "s": 108260, "text": "Padding: This variable accepts an integer, or an Array of 2 integers, or Array of 2 Arrays, each of which is an array of 2 integers. Interpretation of this variable is:If a variable is an integer, the same symmetric is applied to width and height.If a variable is an array of 2 integers, interpreted as two different symmetric values of height and width.If a variable is an array of 2 arrays, interpreted as topPad, bottomPad for the first array, and leftPad, rightPad for the second array." }, { "code": null, "e": 108831, "s": 108751, "text": "If a variable is an integer, the same symmetric is applied to width and height." }, { "code": null, "e": 108939, "s": 108831, "text": "If a variable is an array of 2 integers, interpreted as two different symmetric values of height and width." }, { "code": null, "e": 109076, "s": 108939, "text": "If a variable is an array of 2 arrays, interpreted as topPad, bottomPad for the first array, and leftPad, rightPad for the second array." }, { "code": null, "e": 109388, "s": 109076, "text": "dataFormat: This variable define the format of the shape of the input Tensor. If can be channelsLast or channelsFirst. This value defines the ordering of the dimensions in the inputs. The channelsLast define shape [ batch, height, width, channels] while channelsFirst define [ batch, channels, height, width]." }, { "code": null, "e": 109572, "s": 109388, "text": "inputShape: It can be null or an array of numbers. It is used to create an input layer to insert before the following layer. This variable is only used for the first layer of a model." }, { "code": null, "e": 109818, "s": 109572, "text": "batchInputShape: This variable accept null or array of number. This variable works the same as inputShape but If both inputShape and batchInputShape are defined, batchInputShape is used. This variable is only used for the first layer of a model." }, { "code": null, "e": 109959, "s": 109818, "text": "batchSize: It is a number, and It helps batchInputShape variable. if batchInputShape is not defined it is used for creating batchInputShape." }, { "code": null, "e": 110117, "s": 109959, "text": "dtype: This variable is used for defining data type for the padding layer. It is Default to ‘float32’. This variable is only used for first layer of a model." }, { "code": null, "e": 110153, "s": 110117, "text": "name: It defined the name of layer." }, { "code": null, "e": 110261, "s": 110153, "text": "trainable: It is a boolean type. It defined layer data are updatable by fit or not. Defaults value is true." }, { "code": null, "e": 110344, "s": 110261, "text": "weights: It is tf.Tensor type. It declares the Initial weight values of the layer." }, { "code": null, "e": 110442, "s": 110344, "text": "inputDType: It defines the data type of the input layer. Legacy support. Do not use for new code." }, { "code": null, "e": 110484, "s": 110442, "text": "Returns: It returns ZeroPadding2D object." }, { "code": null, "e": 110561, "s": 110484, "text": "Example 1: In this example, we add a zero-padding layer with default values." }, { "code": null, "e": 110572, "s": 110561, "text": "Javascript" }, { "code": "// Importing tensorflowconst tf = require(\"@tensorflow/tfjs\") // Input 4d Tensor const img4d = tf.tensor4d([1, 2, 3, 4], [1, 2, 2, 1]); // Adding padding in Tensorconst pad = tf.layers.zeroPadding2d();const imgpad = pad.apply(img4d); // Printing 4d Tensor with padding</div>imgpad.print()", "e": 110864, "s": 110572, "text": null }, { "code": null, "e": 110875, "s": 110867, "text": "Output:" }, { "code": null, "e": 111014, "s": 110877, "text": "Tensor [[[[0], [0], [0], [0]],\n [[0], [1], [2], [0]],\n [[0], [3], [4], [0]],\n [[0], [0], [0], [0]]]]" }, { "code": null, "e": 111124, "s": 111014, "text": "Example 2: In this example, we add zero paddings in tensor of specific data type and with define data-Format." }, { "code": null, "e": 111137, "s": 111126, "text": "Javascript" }, { "code": "// Importing tensorflowconst tf = require(\"@tensorflow/tfjs\") // Input 4d Tensor const img4d = tf.tensor4d([1, 2, 3, 4], [1, 2, 2, 1]); // Adding padding in Tensorconst pad = tf.layers.zeroPadding2d({ padding: 2, dataFormat: 'channelsFirst', dtype: 'int32'}); const imgpad = pad.apply(img4d); // Printing 4d Tensor with paddingimgpad.print()", "e": 111488, "s": 111137, "text": null }, { "code": null, "e": 111500, "s": 111491, "text": "Output: " }, { "code": null, "e": 111801, "s": 111502, "text": "Tensor\n [[[[0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0],\n [0, 0, 1, 0, 0],\n [0, 0, 2, 0, 0],\n [0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0]],\n\n [[0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0],\n [0, 0, 3, 0, 0],\n [0, 0, 4, 0, 0],\n [0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0]]]]" }, { "code": null, "e": 111872, "s": 111801, "text": " Reference: https://js.tensorflow.org/api/latest/#layers.zeroPadding2d" }, { "code": null, "e": 111886, "s": 111874, "text": "anikakapoor" }, { "code": null, "e": 111901, "s": 111886, "text": "adnanirshad158" }, { "code": null, "e": 111919, "s": 111901, "text": "germanshephered48" }, { "code": null, "e": 111926, "s": 111919, "text": "Picked" }, { "code": null, "e": 111940, "s": 111926, "text": "Tensorflow.js" }, { "code": null, "e": 111951, "s": 111940, "text": "JavaScript" }, { "code": null, "e": 111968, "s": 111951, "text": "Web Technologies" }, { "code": null, "e": 112066, "s": 111968, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 112106, "s": 112066, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 112151, "s": 112106, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 112212, "s": 112151, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 112281, "s": 112212, "text": "How to calculate the number of days between two dates in javascript?" }, { "code": null, "e": 112353, "s": 112281, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 112393, "s": 112353, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 112426, "s": 112393, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 112471, "s": 112426, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 112514, "s": 112471, "text": "How to fetch data from an API in ReactJS ?" } ]
Java Program for Decimal to Binary Conversion - GeeksforGeeks
17 Oct, 2021 Given a decimal number as input, we need to write a program to convert the given decimal number into an equivalent binary number. Examples: Input : 7 Output : 111 s Input : 10 Output : 1010 Input: 33 Output: 100001 Binary to decimal conversion is done to convert a number given in the binary system to its equivalent in the decimal number system. A number system is a format to represent numbers in a certain way. Binary Number System – The binary number system is used in computers and electronic systems to represent data, and it consists of only two digits which are 0 and 1. Decimal Number System – The decimal number system is the most commonly used number system worldwide, which is easily understandable to people. It consists of digits from 0 to 9. There are numerous approaches to convert the given decimal number into an equivalent binary number in Java. A few of them are listed below. Using Arrays Using Bitwise Operators Using Math.pow() Function (Without using arrays) Store the remainder when the number is divided by 2 in an array.Divide the number by 2Repeat the above two steps until the number is greater than zero.Print the array in reverse order now. Store the remainder when the number is divided by 2 in an array. Divide the number by 2 Repeat the above two steps until the number is greater than zero. Print the array in reverse order now. The below diagram shows an example of converting the decimal number 17 to an equivalent binary number. Java // Java program to convert a decimal// number to binary numberimport java.io.*; class GFG { // function to convert decimal to binary static void decToBinary(int n) { // array to store binary number int[] binaryNum = new int[1000]; // counter for binary array int i = 0; while (n > 0) { // storing remainder in binary array binaryNum[i] = n % 2; n = n / 2; i++; } // printing binary array in reverse order for (int j = i - 1; j >= 0; j--) System.out.print(binaryNum[j]); } // driver program public static void main (String[] args) { int n = 17; System.out.println("Decimal - " + n); System.out.print("Binary - "); decToBinary(n); }} // Contributed by Pramod Kumar Decimal - 17 Binary - 10001 We can use bitwise operators to do the above job. Note – Bitwise operators work faster than arithmetic operators used above. Java // Java program to Decimal to binary conversion// using bitwise operator// Size of an integer is assumed to be 32 bits class gfg { // Function that convert Decimal to binary public void decToBinary(int n) { // Size of an integer is assumed to be 32 bits for (int i = 31; i >= 0; i--) { int k = n >> i; if ((k & 1) > 0) System.out.print("1"); else System.out.print("0"); } }} class geek { // driver code public static void main(String[] args) { gfg g = new gfg(); int n = 32; System.out.println("Decimal - " + n); System.out.print("Binary - "); g.decToBinary(n); }}// This code is contributed by mits Decimal - 32 Binary - 00000000000000000000000000100000 Decimal to binary conversion can also be done without using arrays. Java // Java implementation of the approachimport java.io.*; class GFG { // Function to return the binary // equivalent of decimal value N static int decimalToBinary(int N) { // To store the binary number int B_Number = 0; int cnt = 0; while (N != 0) { int rem = N % 2; double c = Math.pow(10, cnt); B_Number += rem * c; N /= 2; // Count used to store exponent value cnt++; } return B_Number; } // Driver code public static void main(String[] args) { int N = 17; System.out.println("Decimal - " + N); System.out.print("Binary - "); System.out.println(decimalToBinary(N)); }} // This code is contributed by ajit. Decimal - 17 Binary - 10001 Please refer complete article on Program for Decimal to Binary Conversion for more details! nishkarshgandhi Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Interfaces in Java How to iterate any Map in Java Initializing a List in Java Convert a String to Character Array in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class
[ { "code": null, "e": 26186, "s": 26158, "text": "\n17 Oct, 2021" }, { "code": null, "e": 26316, "s": 26186, "text": "Given a decimal number as input, we need to write a program to convert the given decimal number into an equivalent binary number." }, { "code": null, "e": 26327, "s": 26316, "text": "Examples: " }, { "code": null, "e": 26403, "s": 26327, "text": "Input : 7\nOutput : 111\ns\nInput : 10\nOutput : 1010\n\nInput: 33\nOutput: 100001" }, { "code": null, "e": 26603, "s": 26403, "text": "Binary to decimal conversion is done to convert a number given in the binary system to its equivalent in the decimal number system. A number system is a format to represent numbers in a certain way. " }, { "code": null, "e": 26769, "s": 26603, "text": "Binary Number System – The binary number system is used in computers and electronic systems to represent data, and it consists of only two digits which are 0 and 1. " }, { "code": null, "e": 26947, "s": 26769, "text": "Decimal Number System – The decimal number system is the most commonly used number system worldwide, which is easily understandable to people. It consists of digits from 0 to 9." }, { "code": null, "e": 27087, "s": 26947, "text": "There are numerous approaches to convert the given decimal number into an equivalent binary number in Java. A few of them are listed below." }, { "code": null, "e": 27100, "s": 27087, "text": "Using Arrays" }, { "code": null, "e": 27124, "s": 27100, "text": "Using Bitwise Operators" }, { "code": null, "e": 27173, "s": 27124, "text": "Using Math.pow() Function (Without using arrays)" }, { "code": null, "e": 27362, "s": 27173, "text": "Store the remainder when the number is divided by 2 in an array.Divide the number by 2Repeat the above two steps until the number is greater than zero.Print the array in reverse order now." }, { "code": null, "e": 27427, "s": 27362, "text": "Store the remainder when the number is divided by 2 in an array." }, { "code": null, "e": 27450, "s": 27427, "text": "Divide the number by 2" }, { "code": null, "e": 27516, "s": 27450, "text": "Repeat the above two steps until the number is greater than zero." }, { "code": null, "e": 27554, "s": 27516, "text": "Print the array in reverse order now." }, { "code": null, "e": 27658, "s": 27554, "text": "The below diagram shows an example of converting the decimal number 17 to an equivalent binary number. " }, { "code": null, "e": 27663, "s": 27658, "text": "Java" }, { "code": "// Java program to convert a decimal// number to binary numberimport java.io.*; class GFG { // function to convert decimal to binary static void decToBinary(int n) { // array to store binary number int[] binaryNum = new int[1000]; // counter for binary array int i = 0; while (n > 0) { // storing remainder in binary array binaryNum[i] = n % 2; n = n / 2; i++; } // printing binary array in reverse order for (int j = i - 1; j >= 0; j--) System.out.print(binaryNum[j]); } // driver program public static void main (String[] args) { int n = 17; System.out.println(\"Decimal - \" + n); System.out.print(\"Binary - \"); decToBinary(n); }} // Contributed by Pramod Kumar", "e": 28516, "s": 27663, "text": null }, { "code": null, "e": 28544, "s": 28516, "text": "Decimal - 17\nBinary - 10001" }, { "code": null, "e": 28595, "s": 28544, "text": "We can use bitwise operators to do the above job. " }, { "code": null, "e": 28670, "s": 28595, "text": "Note – Bitwise operators work faster than arithmetic operators used above." }, { "code": null, "e": 28675, "s": 28670, "text": "Java" }, { "code": "// Java program to Decimal to binary conversion// using bitwise operator// Size of an integer is assumed to be 32 bits class gfg { // Function that convert Decimal to binary public void decToBinary(int n) { // Size of an integer is assumed to be 32 bits for (int i = 31; i >= 0; i--) { int k = n >> i; if ((k & 1) > 0) System.out.print(\"1\"); else System.out.print(\"0\"); } }} class geek { // driver code public static void main(String[] args) { gfg g = new gfg(); int n = 32; System.out.println(\"Decimal - \" + n); System.out.print(\"Binary - \"); g.decToBinary(n); }}// This code is contributed by mits", "e": 29423, "s": 28675, "text": null }, { "code": null, "e": 29478, "s": 29423, "text": "Decimal - 32\nBinary - 00000000000000000000000000100000" }, { "code": null, "e": 29547, "s": 29478, "text": "Decimal to binary conversion can also be done without using arrays. " }, { "code": null, "e": 29552, "s": 29547, "text": "Java" }, { "code": "// Java implementation of the approachimport java.io.*; class GFG { // Function to return the binary // equivalent of decimal value N static int decimalToBinary(int N) { // To store the binary number int B_Number = 0; int cnt = 0; while (N != 0) { int rem = N % 2; double c = Math.pow(10, cnt); B_Number += rem * c; N /= 2; // Count used to store exponent value cnt++; } return B_Number; } // Driver code public static void main(String[] args) { int N = 17; System.out.println(\"Decimal - \" + N); System.out.print(\"Binary - \"); System.out.println(decimalToBinary(N)); }} // This code is contributed by ajit.", "e": 30340, "s": 29552, "text": null }, { "code": null, "e": 30368, "s": 30340, "text": "Decimal - 17\nBinary - 10001" }, { "code": null, "e": 30460, "s": 30368, "text": "Please refer complete article on Program for Decimal to Binary Conversion for more details!" }, { "code": null, "e": 30476, "s": 30460, "text": "nishkarshgandhi" }, { "code": null, "e": 30481, "s": 30476, "text": "Java" }, { "code": null, "e": 30495, "s": 30481, "text": "Java Programs" }, { "code": null, "e": 30500, "s": 30495, "text": "Java" }, { "code": null, "e": 30598, "s": 30500, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30613, "s": 30598, "text": "Stream In Java" }, { "code": null, "e": 30664, "s": 30613, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 30694, "s": 30664, "text": "HashMap in Java with Examples" }, { "code": null, "e": 30713, "s": 30694, "text": "Interfaces in Java" }, { "code": null, "e": 30744, "s": 30713, "text": "How to iterate any Map in Java" }, { "code": null, "e": 30772, "s": 30744, "text": "Initializing a List in Java" }, { "code": null, "e": 30816, "s": 30772, "text": "Convert a String to Character Array in Java" }, { "code": null, "e": 30842, "s": 30816, "text": "Java Programming Examples" }, { "code": null, "e": 30876, "s": 30842, "text": "Convert Double to Integer in Java" } ]
Find k pairs with smallest sums in two arrays | Set 2 - GeeksforGeeks
26 May, 2021 Given two arrays arr1[] and arr2[] sorted in ascending order and an integer K. The task is to find k pairs with the smallest sums such that one element of a pair belongs to arr1[] and another element belongs to arr2[]. The sizes of arrays may be different. Assume all the elements to be distinct in each array. Examples: Input: a1[] = {1, 7, 11} a2[] = {2, 4, 6} k = 3 Output: [1, 2], [1, 4], [1, 6] The first 3 pairs are returned from the sequence [1, 2], [1, 4], [1, 6], [7, 2], [7, 4], [11, 2], [7, 6], [11, 4], [11, 6]. Input: a1[] = { 2, 3, 4 } a2[] = { 1, 6, 5, 8 } k = 4 Output: [1, 2] [1, 3] [1, 4] [2, 6] An approach with time complexity O(k*n1) has been discussed here. Efficient Approach: Since the array is already sorted. The given below algorithm can be followed to solve this problem: The idea is to maintain two pointers, one pointer pointing to one pair in (a1, a2) and the other in (a2, a1). Each time, compare the sums of the elements pointed by the two pairs and print the minimum one. After this, increment the pointer to the element in the printed pair which was larger than the other. This helps to get the next possible k smallest pair. Once the pointer has been updated to the element such that it starts pointing to the first element of the array again, update the other pointer to the next value. This update is done cyclically. Also, when both the pairs are pointing to the same element, update pointers in both the pairs to avoid extra pair’s printing. Update one pair’s pointer according to rule1 and other’s opposite to rule1. This is done to ensure that all the permutations are considered and no repetitions of pairs are there. Below is the working of the algorithm for example 1: a1[] = {1, 7, 11}, a2[] = {2, 4}, k = 3Let the pairs of pointers be _one, _two_one.first points to 1, _one.second points to 2 ; _two.first points to 2, _two.second points to 11st pair: Since _one and _two are pointing to same elements, print the pair once and update print [1, 2] then update _one.first to 1, _one.second to 4 (following rule 1) ; _two.first points to 2, _two.second points to 7 (opposite to rule 1). If rule 1 was followed for both, then both of them would have been pointing to 1 and 4, and it is not possible to get all possible permutations.2nd pair: Since a1[_one.first] + a2[_one.second] < a1[_two.second] + a2[_two.first], print them and update print [1, 4] then update _one.first to 1, _one.second to 2 Since _one.second came to the first element of the array once again, therefore _one.first points to 7Repeat the above process for remaining K pairs Below is the C++ implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to print the k smallest// pairs | Set 2#include <bits/stdc++.h>using namespace std; typedef struct _pair { int first, second;} _pair; // Function to print the K smallest pairsvoid printKPairs(int a1[], int a2[], int size1, int size2, int k){ // if k is greater than total pairs if (k > (size2 * size1)) { cout << "k pairs don't exist\n"; return; } // _pair _one keeps track of // 'first' in a1 and 'second' in a2 // in _two, _two.first keeps track of // element in the a2[] and _two.second in a1[] _pair _one, _two; _one.first = _one.second = _two.first = _two.second = 0; int cnt = 0; // Repeat the above process till // all K pairs are printed while (cnt < k) { // when both the pointers are pointing // to the same elements (point 3) if (_one.first == _two.second && _two.first == _one.second) { if (a1[_one.first] < a2[_one.second]) { cout << "[" << a1[_one.first] << ", " << a2[_one.second] << "] "; // updates according to step 1 _one.second = (_one.second + 1) % size2; if (_one.second == 0) // see point 2 _one.first = (_one.first + 1) % size1; // updates opposite to step 1 _two.second = (_two.second + 1) % size2; if (_two.second == 0) _two.first = (_two.first + 1) % size2; } else { cout << "[" << a2[_one.second] << ", " << a1[_one.first] << "] "; // updates according to rule 1 _one.first = (_one.first + 1) % size1; if (_one.first == 0) // see point 2 _one.second = (_one.second + 1) % size2; // updates opposite to rule 1 _two.first = (_two.first + 1) % size2; if (_two.first == 0) // see point 2 _two.second = (_two.second + 1) % size1; } } // else update as necessary (point 1) else if (a1[_one.first] + a2[_one.second] <= a2[_two.first] + a1[_two.second]) { if (a1[_one.first] < a2[_one.second]) { cout << "[" << a1[_one.first] << ", " << a2[_one.second] << "] "; // updating according to rule 1 _one.second = ((_one.second + 1) % size2); if (_one.second == 0) // see point 2 _one.first = (_one.first + 1) % size1; } else { cout << "[" << a2[_one.second] << ", " << a1[_one.first] << "] "; // updating according to rule 1 _one.first = ((_one.first + 1) % size1); if (_one.first == 0) // see point 2 _one.second = (_one.second + 1) % size2; } } else if (a1[_one.first] + a2[_one.second] > a2[_two.first] + a1[_two.second]) { if (a2[_two.first] < a1[_two.second]) { cout << "[" << a2[_two.first] << ", " << a1[_two.second] << "] "; // updating according to rule 1 _two.first = ((_two.first + 1) % size2); if (_two.first == 0) // see point 2 _two.second = (_two.second + 1) % size1; } else { cout << "[" << a1[_two.second] << ", " << a2[_two.first] << "] "; // updating according to rule 1 _two.second = ((_two.second + 1) % size1); if (_two.second == 0) // see point 2 _two.first = (_two.first + 1) % size1; } } cnt++; }} // Driver Codeint main(){ int a1[] = { 2, 3, 4 }; int a2[] = { 1, 6, 5, 8 }; int size1 = sizeof(a1) / sizeof(a1[0]); int size2 = sizeof(a2) / sizeof(a2[0]); int k = 4; printKPairs(a1, a2, size1, size2, k); return 0;} // Java program to print// the k smallest pairs// | Set 2import java.util.*;class GFG{ static class _pair{ int first, second;}; // Function to print the K// smallest pairsstatic void printKPairs(int a1[], int a2[], int size1, int size2, int k){ // if k is greater than // total pairs if (k > (size2 * size1)) { System.out.print("k pairs don't exist\n"); return; } // _pair _one keeps track of // 'first' in a1 and 'second' in a2 // in _two, _two.first keeps track of // element in the a2[] and _two.second // in a1[] _pair _one = new _pair(); _pair _two = new _pair(); _one.first = _one.second = _two.first = _two.second = 0; int cnt = 0; // Repeat the above process // till all K pairs are printed while (cnt < k) { // when both the pointers are // pointing to the same elements // (point 3) if (_one.first == _two.second && _two.first == _one.second) { if (a1[_one.first] < a2[_one.second]) { System.out.print("[" + a1[_one.first] + ", " + a2[_one.second] + "] "); // updates according to step 1 _one.second = (_one.second + 1) % size2; // see point 2 if (_one.second == 0) _one.first = (_one.first + 1) % size1; // updates opposite to step 1 _two.second = (_two.second + 1) % size2; if (_two.second == 0) _two.first = (_two.first + 1) % size2; } else { System.out.print("[" + a2[_one.second] + ", " + a1[_one.first] + "] "); // updates according to rule 1 _one.first = (_one.first + 1) % size1; // see point 2 if (_one.first == 0) _one.second = (_one.second + 1) % size2; // updates opposite to rule 1 _two.first = (_two.first + 1) % size2; // see point 2 if (_two.first == 0) _two.second = (_two.second + 1) % size1; } } // else update as // necessary (point 1) else if (a1[_one.first] + a2[_one.second] <= a2[_two.first] + a1[_two.second]) { if (a1[_one.first] < a2[_one.second]) { System.out.print("[" + a1[_one.first] + ", " + a2[_one.second] + "] "); // updating according to rule 1 _one.second = ((_one.second + 1) % size2); // see point 2 if (_one.second == 0) _one.first = (_one.first + 1) % size1; } else { System.out.print("[" + a2[_one.second] + ", " + a1[_one.first] + "] "); // updating according to rule 1 _one.first = ((_one.first + 1) % size1); // see point 2 if (_one.first == 0) _one.second = (_one.second + 1) % size2; } } else if (a1[_one.first] + a2[_one.second] > a2[_two.first] + a1[_two.second]) { if (a2[_two.first] < a1[_two.second]) { System.out.print("[" + a2[_two.first] + ", " + a1[_two.second] + "] "); // updating according to rule 1 _two.first = ((_two.first + 1) % size2); // see point 2 if (_two.first == 0) _two.second = (_two.second + 1) % size1; } else { System.out.print("[" + a1[_two.second] + ", " + a2[_two.first] + "] "); // updating according to rule 1 _two.second = ((_two.second + 1) % size1); // see point 2 if (_two.second == 0) _two.first = (_two.first + 1) % size1; } } cnt++; }} // Driver Codepublic static void main(String[] args){ int a1[] = {2, 3, 4}; int a2[] = {1, 6, 5, 8}; int size1 = a1.length; int size2 = a2.length; int k = 4; printKPairs(a1, a2, size1, size2, k);}} // This code is contributed by gauravrajput1 # Python3 program to print the k smallest# pairs | Set 2 # Function to print the K smallest pairsdef printKPairs(a1, a,size1, size2, k): # if k is greater than total pairs if (k > (size2 * size1)): print("k pairs don't exist\n") return # _pair _one keeps track of # 'first' in a1 and 'second' in a2 # in _two, _two[0] keeps track of # element in the a2and _two[1] in a1[] _one, _two = [0, 0], [0, 0] cnt = 0 # Repeat the above process till # all K pairs are printed while (cnt < k): # when both the pointers are pointing # to the same elements (po3) if (_one[0] == _two[1] and _two[0] == _one[1]): if (a1[_one[0]] < a2[_one[1]]): print("[", a1[_one[0]], ", ", a2[_one[1]],"] ", end=" ") # updates according to step 1 _one[1] = (_one[1] + 1) % size2 if (_one[1] == 0): #see po2 _one[0] = (_one[0] + 1) % size1 # updates opposite to step 1 _two[1] = (_two[1] + 1) % size2 if (_two[1] == 0): _two[0] = (_two[0] + 1) % size2 else: print("[",a2[_one[1]] ,", ",a1[_one[0]],"] ",end=" ") # updates according to rule 1 _one[0] = (_one[0] + 1) % size1 if (_one[0] == 0): #see po2 _one[1] = (_one[1] + 1) % size2 # updates opposite to rule 1 _two[0] = (_two[0] + 1) % size2 if (_two[0] == 0): #see po2 _two[1] = (_two[1] + 1) % size1 # else update as necessary (po1) elif (a1[_one[0]] + a2[_one[1]] <= a2[_two[0]] + a1[_two[1]]): if (a1[_one[0]] < a2[_one[1]]): print("[",a1[_one[0]],", ", a2[_one[1]],"] ",end=" ") # updating according to rule 1 _one[1] = ((_one[1] + 1) % size2) if (_one[1] == 0): # see po2 _one[0] = (_one[0] + 1) % size1 else: print("[",a2[_one[1]],", ", a1[_one[0]],"] ", end=" ") # updating according to rule 1 _one[0] = ((_one[0] + 1) % size1) if (_one[0] == 0): # see po2 _one[1] = (_one[1] + 1) % size2 elif (a1[_one[0]] + a2[_one[1]] > a2[_two[0]] + a1[_two[1]]): if (a2[_two[0]] < a1[_two[1]]): print("[",a2[_two[0]],", ",a1[_two[1]],"] ",end=" ") # updating according to rule 1 _two[0] = ((_two[0] + 1) % size2) if (_two[0] == 0): #see po2 _two[1] = (_two[1] + 1) % size1 else: print("[",a1[_two[1]] ,", ",a2[_two[0]],"] ",end=" ") # updating according to rule 1 _two[1] = ((_two[1] + 1) % size1) if (_two[1] == 0): #see po2 _two[0] = (_two[0] + 1) % size1 cnt += 1 # Driver Codeif __name__ == '__main__': a1= [2, 3, 4] a2= [1, 6, 5, 8] size1 = len(a1) size2 = len(a2) k = 4 printKPairs(a1, a2, size1, size2, k) # This code is contributed by mohit kumar 29 // C# program to print// the k smallest pairs// | Set 2using System;class GFG{ public class _pair{ public int first, second;}; // Function to print the K// smallest pairsstatic void printKPairs(int []a1, int []a2, int size1, int size2, int k){ // if k is greater than // total pairs if (k > (size2 * size1)) { Console.Write("k pairs don't exist\n"); return; } // _pair _one keeps track of // 'first' in a1 and 'second' in a2 // in _two, _two.first keeps track of // element in the a2[] and _two.second // in a1[] _pair _one = new _pair(); _pair _two = new _pair(); _one.first = _one.second = _two.first = _two.second = 0; int cnt = 0; // Repeat the above process // till all K pairs are printed while (cnt < k) { // when both the pointers are // pointing to the same elements // (point 3) if (_one.first == _two.second && _two.first == _one.second) { if (a1[_one.first] < a2[_one.second]) { Console.Write("[" + a1[_one.first] + ", " + a2[_one.second] + "] "); // updates according to step 1 _one.second = (_one.second + 1) % size2; // see point 2 if (_one.second == 0) _one.first = (_one.first + 1) % size1; // updates opposite to step 1 _two.second = (_two.second + 1) % size2; if (_two.second == 0) _two.first = (_two.first + 1) % size2; } else { Console.Write("[" + a2[_one.second] + ", " + a1[_one.first] + "] "); // updates according to rule 1 _one.first = (_one.first + 1) % size1; // see point 2 if (_one.first == 0) _one.second = (_one.second + 1) % size2; // updates opposite to rule 1 _two.first = (_two.first + 1) % size2; // see point 2 if (_two.first == 0) _two.second = (_two.second + 1) % size1; } } // else update as // necessary (point 1) else if (a1[_one.first] + a2[_one.second] <= a2[_two.first] + a1[_two.second]) { if (a1[_one.first] < a2[_one.second]) { Console.Write("[" + a1[_one.first] + ", " + a2[_one.second] + "] "); // updating according to rule 1 _one.second = ((_one.second + 1) % size2); // see point 2 if (_one.second == 0) _one.first = (_one.first + 1) % size1; } else { Console.Write("[" + a2[_one.second] + ", " + a1[_one.first] + "] "); // updating according to rule 1 _one.first = ((_one.first + 1) % size1); // see point 2 if (_one.first == 0) _one.second = (_one.second + 1) % size2; } } else if (a1[_one.first] + a2[_one.second] > a2[_two.first] + a1[_two.second]) { if (a2[_two.first] < a1[_two.second]) { Console.Write("[" + a2[_two.first] + ", " + a1[_two.second] + "] "); // updating according to rule 1 _two.first = ((_two.first + 1) % size2); // see point 2 if (_two.first == 0) _two.second = (_two.second + 1) % size1; } else { Console.Write("[" + a1[_two.second] + ", " + a2[_two.first] + "] "); // updating according to rule 1 _two.second = ((_two.second + 1) % size1); // see point 2 if (_two.second == 0) _two.first = (_two.first + 1) % size1; } } cnt++; }} // Driver Codepublic static void Main(String[] args){ int []a1 = {2, 3, 4}; int []a2 = {1, 6, 5, 8}; int size1 = a1.Length; int size2 = a2.Length; int k = 4; printKPairs(a1, a2, size1, size2, k);}} // This code is contributed by gauravrajput1 <script>// Javascript program to print// the k smallest pairs// | Set 2 // Function to print the K// smallest pairsfunction printKPairs(a1,a2,size1,size2,k){ // if k is greater than // total pairs if (k > (size2 * size1)) { document.write("k pairs don't exist\n"); return; } // _pair _one keeps track of // 'first' in a1 and 'second' in a2 // in _two, _two[0] keeps track of // element in the a2[] and _two[1] // in a1[] let _one = [0,0]; let _two = [0,0]; let cnt = 0; // Repeat the above process // till all K pairs are printed while (cnt < k) { // when both the pointers are // pointing to the same elements // (point 3) if (_one[0] == _two[1] && _two[0] == _one[1]) { if (a1[_one[0]] < a2[_one[1]]) { document.write("[" + a1[_one[0]] + ", " + a2[_one[1]] + "] "); // updates according to step 1 _one[1] = (_one[1] + 1) % size2; // see point 2 if (_one[1] == 0) _one[0] = (_one[0] + 1) % size1; // updates opposite to step 1 _two[1] = (_two[1] + 1) % size2; if (_two[1] == 0) _two[0] = (_two[0] + 1) % size2; } else { document.write("[" + a2[_one[1]] + ", " + a1[_one[0]] + "] "); // updates according to rule 1 _one[0] = (_one[0] + 1) % size1; // see point 2 if (_one[0] == 0) _one[1] = (_one[1] + 1) % size2; // updates opposite to rule 1 _two[0] = (_two[0] + 1) % size2; // see point 2 if (_two[0] == 0) _two[1] = (_two[1] + 1) % size1; } } // else update as // necessary (point 1) else if (a1[_one[0]] + a2[_one[1]] <= a2[_two[0]] + a1[_two[1]]) { if (a1[_one[0]] < a2[_one[1]]) { document.write("[" + a1[_one[0]] + ", " + a2[_one[1]] + "] "); // updating according to rule 1 _one[1] = ((_one[1] + 1) % size2); // see point 2 if (_one[1] == 0) _one[0] = (_one[0] + 1) % size1; } else { document.write("[" + a2[_one[1]] + ", " + a1[_one[0]] + "] "); // updating according to rule 1 _one[0] = ((_one[0] + 1) % size1); // see point 2 if (_one[0] == 0) _one[1] = (_one[1] + 1) % size2; } } else if (a1[_one[0]] + a2[_one[1]] > a2[_two[0]] + a1[_two[1]]) { if (a2[_two[0]] < a1[_two[1]]) { document.write("[" + a2[_two[0]] + ", " + a1[_two[1]] + "] "); // updating according to rule 1 _two[0] = ((_two[0] + 1) % size2); // see point 2 if (_two[0] == 0) _two[1] = (_two[1] + 1) % size1; } else { document.write("[" + a1[_two[1]] + ", " + a2[_two[0]] + "] "); // updating according to rule 1 _two[1] = ((_two[1] + 1) % size1); // see point 2 if (_two[1] == 0) _two[0] = (_two[0] + 1) % size1; } } cnt++; }} // Driver Codelet a1=[2, 3, 4];let a2=[1, 6, 5, 8];let size1 = a1.length;let size2 = a2.length;let k = 4;printKPairs(a1, a2, size1, size2, k); // This code is contributed by unknown2108</script> [1, 2] [1, 3] [1, 4] [2, 6] Time complexity: O(K) mohit kumar 29 Code_Mech GauravRajput1 unknown2108 Arrays cpp-pair cpp-structure Pointers Algorithms Greedy Arrays Greedy Pointers Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. DSA Sheet by Love Babbar How to Start Learning DSA? K means Clustering - Introduction Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete Quadratic Probing in Hashing Dijkstra's shortest path algorithm | Greedy Algo-7 Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2 Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5 Program for array rotation Write a program to print all permutations of a given string
[ { "code": null, "e": 26051, "s": 26023, "text": "\n26 May, 2021" }, { "code": null, "e": 26372, "s": 26051, "text": "Given two arrays arr1[] and arr2[] sorted in ascending order and an integer K. The task is to find k pairs with the smallest sums such that one element of a pair belongs to arr1[] and another element belongs to arr2[]. The sizes of arrays may be different. Assume all the elements to be distinct in each array. Examples:" }, { "code": null, "e": 26698, "s": 26372, "text": "Input: a1[] = {1, 7, 11}\n a2[] = {2, 4, 6}\n k = 3\nOutput: [1, 2], [1, 4], [1, 6]\nThe first 3 pairs are returned \nfrom the sequence [1, 2], [1, 4], [1, 6], [7, 2],\n[7, 4], [11, 2], [7, 6], [11, 4], [11, 6].\n\nInput: a1[] = { 2, 3, 4 }\n a2[] = { 1, 6, 5, 8 } \n k = 4\nOutput: [1, 2] [1, 3] [1, 4] [2, 6] " }, { "code": null, "e": 26886, "s": 26698, "text": "An approach with time complexity O(k*n1) has been discussed here. Efficient Approach: Since the array is already sorted. The given below algorithm can be followed to solve this problem: " }, { "code": null, "e": 27247, "s": 26886, "text": "The idea is to maintain two pointers, one pointer pointing to one pair in (a1, a2) and the other in (a2, a1). Each time, compare the sums of the elements pointed by the two pairs and print the minimum one. After this, increment the pointer to the element in the printed pair which was larger than the other. This helps to get the next possible k smallest pair." }, { "code": null, "e": 27442, "s": 27247, "text": "Once the pointer has been updated to the element such that it starts pointing to the first element of the array again, update the other pointer to the next value. This update is done cyclically." }, { "code": null, "e": 27747, "s": 27442, "text": "Also, when both the pairs are pointing to the same element, update pointers in both the pairs to avoid extra pair’s printing. Update one pair’s pointer according to rule1 and other’s opposite to rule1. This is done to ensure that all the permutations are considered and no repetitions of pairs are there." }, { "code": null, "e": 27802, "s": 27747, "text": "Below is the working of the algorithm for example 1: " }, { "code": null, "e": 28071, "s": 27802, "text": "a1[] = {1, 7, 11}, a2[] = {2, 4}, k = 3Let the pairs of pointers be _one, _two_one.first points to 1, _one.second points to 2 ; _two.first points to 2, _two.second points to 11st pair: Since _one and _two are pointing to same elements, print the pair once and update " }, { "code": null, "e": 28084, "s": 28071, "text": "print [1, 2]" }, { "code": null, "e": 28474, "s": 28084, "text": "then update _one.first to 1, _one.second to 4 (following rule 1) ; _two.first points to 2, _two.second points to 7 (opposite to rule 1). If rule 1 was followed for both, then both of them would have been pointing to 1 and 4, and it is not possible to get all possible permutations.2nd pair: Since a1[_one.first] + a2[_one.second] < a1[_two.second] + a2[_two.first], print them and update " }, { "code": null, "e": 28487, "s": 28474, "text": "print [1, 4]" }, { "code": null, "e": 28681, "s": 28487, "text": "then update _one.first to 1, _one.second to 2 Since _one.second came to the first element of the array once again, therefore _one.first points to 7Repeat the above process for remaining K pairs" }, { "code": null, "e": 28738, "s": 28681, "text": "Below is the C++ implementation of the above approach: " }, { "code": null, "e": 28742, "s": 28738, "text": "C++" }, { "code": null, "e": 28747, "s": 28742, "text": "Java" }, { "code": null, "e": 28755, "s": 28747, "text": "Python3" }, { "code": null, "e": 28758, "s": 28755, "text": "C#" }, { "code": null, "e": 28769, "s": 28758, "text": "Javascript" }, { "code": "// C++ program to print the k smallest// pairs | Set 2#include <bits/stdc++.h>using namespace std; typedef struct _pair { int first, second;} _pair; // Function to print the K smallest pairsvoid printKPairs(int a1[], int a2[], int size1, int size2, int k){ // if k is greater than total pairs if (k > (size2 * size1)) { cout << \"k pairs don't exist\\n\"; return; } // _pair _one keeps track of // 'first' in a1 and 'second' in a2 // in _two, _two.first keeps track of // element in the a2[] and _two.second in a1[] _pair _one, _two; _one.first = _one.second = _two.first = _two.second = 0; int cnt = 0; // Repeat the above process till // all K pairs are printed while (cnt < k) { // when both the pointers are pointing // to the same elements (point 3) if (_one.first == _two.second && _two.first == _one.second) { if (a1[_one.first] < a2[_one.second]) { cout << \"[\" << a1[_one.first] << \", \" << a2[_one.second] << \"] \"; // updates according to step 1 _one.second = (_one.second + 1) % size2; if (_one.second == 0) // see point 2 _one.first = (_one.first + 1) % size1; // updates opposite to step 1 _two.second = (_two.second + 1) % size2; if (_two.second == 0) _two.first = (_two.first + 1) % size2; } else { cout << \"[\" << a2[_one.second] << \", \" << a1[_one.first] << \"] \"; // updates according to rule 1 _one.first = (_one.first + 1) % size1; if (_one.first == 0) // see point 2 _one.second = (_one.second + 1) % size2; // updates opposite to rule 1 _two.first = (_two.first + 1) % size2; if (_two.first == 0) // see point 2 _two.second = (_two.second + 1) % size1; } } // else update as necessary (point 1) else if (a1[_one.first] + a2[_one.second] <= a2[_two.first] + a1[_two.second]) { if (a1[_one.first] < a2[_one.second]) { cout << \"[\" << a1[_one.first] << \", \" << a2[_one.second] << \"] \"; // updating according to rule 1 _one.second = ((_one.second + 1) % size2); if (_one.second == 0) // see point 2 _one.first = (_one.first + 1) % size1; } else { cout << \"[\" << a2[_one.second] << \", \" << a1[_one.first] << \"] \"; // updating according to rule 1 _one.first = ((_one.first + 1) % size1); if (_one.first == 0) // see point 2 _one.second = (_one.second + 1) % size2; } } else if (a1[_one.first] + a2[_one.second] > a2[_two.first] + a1[_two.second]) { if (a2[_two.first] < a1[_two.second]) { cout << \"[\" << a2[_two.first] << \", \" << a1[_two.second] << \"] \"; // updating according to rule 1 _two.first = ((_two.first + 1) % size2); if (_two.first == 0) // see point 2 _two.second = (_two.second + 1) % size1; } else { cout << \"[\" << a1[_two.second] << \", \" << a2[_two.first] << \"] \"; // updating according to rule 1 _two.second = ((_two.second + 1) % size1); if (_two.second == 0) // see point 2 _two.first = (_two.first + 1) % size1; } } cnt++; }} // Driver Codeint main(){ int a1[] = { 2, 3, 4 }; int a2[] = { 1, 6, 5, 8 }; int size1 = sizeof(a1) / sizeof(a1[0]); int size2 = sizeof(a2) / sizeof(a2[0]); int k = 4; printKPairs(a1, a2, size1, size2, k); return 0;}", "e": 32796, "s": 28769, "text": null }, { "code": "// Java program to print// the k smallest pairs// | Set 2import java.util.*;class GFG{ static class _pair{ int first, second;}; // Function to print the K// smallest pairsstatic void printKPairs(int a1[], int a2[], int size1, int size2, int k){ // if k is greater than // total pairs if (k > (size2 * size1)) { System.out.print(\"k pairs don't exist\\n\"); return; } // _pair _one keeps track of // 'first' in a1 and 'second' in a2 // in _two, _two.first keeps track of // element in the a2[] and _two.second // in a1[] _pair _one = new _pair(); _pair _two = new _pair(); _one.first = _one.second = _two.first = _two.second = 0; int cnt = 0; // Repeat the above process // till all K pairs are printed while (cnt < k) { // when both the pointers are // pointing to the same elements // (point 3) if (_one.first == _two.second && _two.first == _one.second) { if (a1[_one.first] < a2[_one.second]) { System.out.print(\"[\" + a1[_one.first] + \", \" + a2[_one.second] + \"] \"); // updates according to step 1 _one.second = (_one.second + 1) % size2; // see point 2 if (_one.second == 0) _one.first = (_one.first + 1) % size1; // updates opposite to step 1 _two.second = (_two.second + 1) % size2; if (_two.second == 0) _two.first = (_two.first + 1) % size2; } else { System.out.print(\"[\" + a2[_one.second] + \", \" + a1[_one.first] + \"] \"); // updates according to rule 1 _one.first = (_one.first + 1) % size1; // see point 2 if (_one.first == 0) _one.second = (_one.second + 1) % size2; // updates opposite to rule 1 _two.first = (_two.first + 1) % size2; // see point 2 if (_two.first == 0) _two.second = (_two.second + 1) % size1; } } // else update as // necessary (point 1) else if (a1[_one.first] + a2[_one.second] <= a2[_two.first] + a1[_two.second]) { if (a1[_one.first] < a2[_one.second]) { System.out.print(\"[\" + a1[_one.first] + \", \" + a2[_one.second] + \"] \"); // updating according to rule 1 _one.second = ((_one.second + 1) % size2); // see point 2 if (_one.second == 0) _one.first = (_one.first + 1) % size1; } else { System.out.print(\"[\" + a2[_one.second] + \", \" + a1[_one.first] + \"] \"); // updating according to rule 1 _one.first = ((_one.first + 1) % size1); // see point 2 if (_one.first == 0) _one.second = (_one.second + 1) % size2; } } else if (a1[_one.first] + a2[_one.second] > a2[_two.first] + a1[_two.second]) { if (a2[_two.first] < a1[_two.second]) { System.out.print(\"[\" + a2[_two.first] + \", \" + a1[_two.second] + \"] \"); // updating according to rule 1 _two.first = ((_two.first + 1) % size2); // see point 2 if (_two.first == 0) _two.second = (_two.second + 1) % size1; } else { System.out.print(\"[\" + a1[_two.second] + \", \" + a2[_two.first] + \"] \"); // updating according to rule 1 _two.second = ((_two.second + 1) % size1); // see point 2 if (_two.second == 0) _two.first = (_two.first + 1) % size1; } } cnt++; }} // Driver Codepublic static void main(String[] args){ int a1[] = {2, 3, 4}; int a2[] = {1, 6, 5, 8}; int size1 = a1.length; int size2 = a2.length; int k = 4; printKPairs(a1, a2, size1, size2, k);}} // This code is contributed by gauravrajput1", "e": 37293, "s": 32796, "text": null }, { "code": "# Python3 program to print the k smallest# pairs | Set 2 # Function to print the K smallest pairsdef printKPairs(a1, a,size1, size2, k): # if k is greater than total pairs if (k > (size2 * size1)): print(\"k pairs don't exist\\n\") return # _pair _one keeps track of # 'first' in a1 and 'second' in a2 # in _two, _two[0] keeps track of # element in the a2and _two[1] in a1[] _one, _two = [0, 0], [0, 0] cnt = 0 # Repeat the above process till # all K pairs are printed while (cnt < k): # when both the pointers are pointing # to the same elements (po3) if (_one[0] == _two[1] and _two[0] == _one[1]): if (a1[_one[0]] < a2[_one[1]]): print(\"[\", a1[_one[0]], \", \", a2[_one[1]],\"] \", end=\" \") # updates according to step 1 _one[1] = (_one[1] + 1) % size2 if (_one[1] == 0): #see po2 _one[0] = (_one[0] + 1) % size1 # updates opposite to step 1 _two[1] = (_two[1] + 1) % size2 if (_two[1] == 0): _two[0] = (_two[0] + 1) % size2 else: print(\"[\",a2[_one[1]] ,\", \",a1[_one[0]],\"] \",end=\" \") # updates according to rule 1 _one[0] = (_one[0] + 1) % size1 if (_one[0] == 0): #see po2 _one[1] = (_one[1] + 1) % size2 # updates opposite to rule 1 _two[0] = (_two[0] + 1) % size2 if (_two[0] == 0): #see po2 _two[1] = (_two[1] + 1) % size1 # else update as necessary (po1) elif (a1[_one[0]] + a2[_one[1]] <= a2[_two[0]] + a1[_two[1]]): if (a1[_one[0]] < a2[_one[1]]): print(\"[\",a1[_one[0]],\", \", a2[_one[1]],\"] \",end=\" \") # updating according to rule 1 _one[1] = ((_one[1] + 1) % size2) if (_one[1] == 0): # see po2 _one[0] = (_one[0] + 1) % size1 else: print(\"[\",a2[_one[1]],\", \", a1[_one[0]],\"] \", end=\" \") # updating according to rule 1 _one[0] = ((_one[0] + 1) % size1) if (_one[0] == 0): # see po2 _one[1] = (_one[1] + 1) % size2 elif (a1[_one[0]] + a2[_one[1]] > a2[_two[0]] + a1[_two[1]]): if (a2[_two[0]] < a1[_two[1]]): print(\"[\",a2[_two[0]],\", \",a1[_two[1]],\"] \",end=\" \") # updating according to rule 1 _two[0] = ((_two[0] + 1) % size2) if (_two[0] == 0): #see po2 _two[1] = (_two[1] + 1) % size1 else: print(\"[\",a1[_two[1]] ,\", \",a2[_two[0]],\"] \",end=\" \") # updating according to rule 1 _two[1] = ((_two[1] + 1) % size1) if (_two[1] == 0): #see po2 _two[0] = (_two[0] + 1) % size1 cnt += 1 # Driver Codeif __name__ == '__main__': a1= [2, 3, 4] a2= [1, 6, 5, 8] size1 = len(a1) size2 = len(a2) k = 4 printKPairs(a1, a2, size1, size2, k) # This code is contributed by mohit kumar 29", "e": 40610, "s": 37293, "text": null }, { "code": "// C# program to print// the k smallest pairs// | Set 2using System;class GFG{ public class _pair{ public int first, second;}; // Function to print the K// smallest pairsstatic void printKPairs(int []a1, int []a2, int size1, int size2, int k){ // if k is greater than // total pairs if (k > (size2 * size1)) { Console.Write(\"k pairs don't exist\\n\"); return; } // _pair _one keeps track of // 'first' in a1 and 'second' in a2 // in _two, _two.first keeps track of // element in the a2[] and _two.second // in a1[] _pair _one = new _pair(); _pair _two = new _pair(); _one.first = _one.second = _two.first = _two.second = 0; int cnt = 0; // Repeat the above process // till all K pairs are printed while (cnt < k) { // when both the pointers are // pointing to the same elements // (point 3) if (_one.first == _two.second && _two.first == _one.second) { if (a1[_one.first] < a2[_one.second]) { Console.Write(\"[\" + a1[_one.first] + \", \" + a2[_one.second] + \"] \"); // updates according to step 1 _one.second = (_one.second + 1) % size2; // see point 2 if (_one.second == 0) _one.first = (_one.first + 1) % size1; // updates opposite to step 1 _two.second = (_two.second + 1) % size2; if (_two.second == 0) _two.first = (_two.first + 1) % size2; } else { Console.Write(\"[\" + a2[_one.second] + \", \" + a1[_one.first] + \"] \"); // updates according to rule 1 _one.first = (_one.first + 1) % size1; // see point 2 if (_one.first == 0) _one.second = (_one.second + 1) % size2; // updates opposite to rule 1 _two.first = (_two.first + 1) % size2; // see point 2 if (_two.first == 0) _two.second = (_two.second + 1) % size1; } } // else update as // necessary (point 1) else if (a1[_one.first] + a2[_one.second] <= a2[_two.first] + a1[_two.second]) { if (a1[_one.first] < a2[_one.second]) { Console.Write(\"[\" + a1[_one.first] + \", \" + a2[_one.second] + \"] \"); // updating according to rule 1 _one.second = ((_one.second + 1) % size2); // see point 2 if (_one.second == 0) _one.first = (_one.first + 1) % size1; } else { Console.Write(\"[\" + a2[_one.second] + \", \" + a1[_one.first] + \"] \"); // updating according to rule 1 _one.first = ((_one.first + 1) % size1); // see point 2 if (_one.first == 0) _one.second = (_one.second + 1) % size2; } } else if (a1[_one.first] + a2[_one.second] > a2[_two.first] + a1[_two.second]) { if (a2[_two.first] < a1[_two.second]) { Console.Write(\"[\" + a2[_two.first] + \", \" + a1[_two.second] + \"] \"); // updating according to rule 1 _two.first = ((_two.first + 1) % size2); // see point 2 if (_two.first == 0) _two.second = (_two.second + 1) % size1; } else { Console.Write(\"[\" + a1[_two.second] + \", \" + a2[_two.first] + \"] \"); // updating according to rule 1 _two.second = ((_two.second + 1) % size1); // see point 2 if (_two.second == 0) _two.first = (_two.first + 1) % size1; } } cnt++; }} // Driver Codepublic static void Main(String[] args){ int []a1 = {2, 3, 4}; int []a2 = {1, 6, 5, 8}; int size1 = a1.Length; int size2 = a2.Length; int k = 4; printKPairs(a1, a2, size1, size2, k);}} // This code is contributed by gauravrajput1", "e": 45011, "s": 40610, "text": null }, { "code": "<script>// Javascript program to print// the k smallest pairs// | Set 2 // Function to print the K// smallest pairsfunction printKPairs(a1,a2,size1,size2,k){ // if k is greater than // total pairs if (k > (size2 * size1)) { document.write(\"k pairs don't exist\\n\"); return; } // _pair _one keeps track of // 'first' in a1 and 'second' in a2 // in _two, _two[0] keeps track of // element in the a2[] and _two[1] // in a1[] let _one = [0,0]; let _two = [0,0]; let cnt = 0; // Repeat the above process // till all K pairs are printed while (cnt < k) { // when both the pointers are // pointing to the same elements // (point 3) if (_one[0] == _two[1] && _two[0] == _one[1]) { if (a1[_one[0]] < a2[_one[1]]) { document.write(\"[\" + a1[_one[0]] + \", \" + a2[_one[1]] + \"] \"); // updates according to step 1 _one[1] = (_one[1] + 1) % size2; // see point 2 if (_one[1] == 0) _one[0] = (_one[0] + 1) % size1; // updates opposite to step 1 _two[1] = (_two[1] + 1) % size2; if (_two[1] == 0) _two[0] = (_two[0] + 1) % size2; } else { document.write(\"[\" + a2[_one[1]] + \", \" + a1[_one[0]] + \"] \"); // updates according to rule 1 _one[0] = (_one[0] + 1) % size1; // see point 2 if (_one[0] == 0) _one[1] = (_one[1] + 1) % size2; // updates opposite to rule 1 _two[0] = (_two[0] + 1) % size2; // see point 2 if (_two[0] == 0) _two[1] = (_two[1] + 1) % size1; } } // else update as // necessary (point 1) else if (a1[_one[0]] + a2[_one[1]] <= a2[_two[0]] + a1[_two[1]]) { if (a1[_one[0]] < a2[_one[1]]) { document.write(\"[\" + a1[_one[0]] + \", \" + a2[_one[1]] + \"] \"); // updating according to rule 1 _one[1] = ((_one[1] + 1) % size2); // see point 2 if (_one[1] == 0) _one[0] = (_one[0] + 1) % size1; } else { document.write(\"[\" + a2[_one[1]] + \", \" + a1[_one[0]] + \"] \"); // updating according to rule 1 _one[0] = ((_one[0] + 1) % size1); // see point 2 if (_one[0] == 0) _one[1] = (_one[1] + 1) % size2; } } else if (a1[_one[0]] + a2[_one[1]] > a2[_two[0]] + a1[_two[1]]) { if (a2[_two[0]] < a1[_two[1]]) { document.write(\"[\" + a2[_two[0]] + \", \" + a1[_two[1]] + \"] \"); // updating according to rule 1 _two[0] = ((_two[0] + 1) % size2); // see point 2 if (_two[0] == 0) _two[1] = (_two[1] + 1) % size1; } else { document.write(\"[\" + a1[_two[1]] + \", \" + a2[_two[0]] + \"] \"); // updating according to rule 1 _two[1] = ((_two[1] + 1) % size1); // see point 2 if (_two[1] == 0) _two[0] = (_two[0] + 1) % size1; } } cnt++; }} // Driver Codelet a1=[2, 3, 4];let a2=[1, 6, 5, 8];let size1 = a1.length;let size2 = a2.length;let k = 4;printKPairs(a1, a2, size1, size2, k); // This code is contributed by unknown2108</script>", "e": 49006, "s": 45011, "text": null }, { "code": null, "e": 49034, "s": 49006, "text": "[1, 2] [1, 3] [1, 4] [2, 6]" }, { "code": null, "e": 49058, "s": 49036, "text": "Time complexity: O(K)" }, { "code": null, "e": 49073, "s": 49058, "text": "mohit kumar 29" }, { "code": null, "e": 49083, "s": 49073, "text": "Code_Mech" }, { "code": null, "e": 49097, "s": 49083, "text": "GauravRajput1" }, { "code": null, "e": 49109, "s": 49097, "text": "unknown2108" }, { "code": null, "e": 49116, "s": 49109, "text": "Arrays" }, { "code": null, "e": 49125, "s": 49116, "text": "cpp-pair" }, { "code": null, "e": 49139, "s": 49125, "text": "cpp-structure" }, { "code": null, "e": 49148, "s": 49139, "text": "Pointers" }, { "code": null, "e": 49159, "s": 49148, "text": "Algorithms" }, { "code": null, "e": 49166, "s": 49159, "text": "Greedy" }, { "code": null, "e": 49173, "s": 49166, "text": "Arrays" }, { "code": null, "e": 49180, "s": 49173, "text": "Greedy" }, { "code": null, "e": 49189, "s": 49180, "text": "Pointers" }, { "code": null, "e": 49200, "s": 49189, "text": "Algorithms" }, { "code": null, "e": 49298, "s": 49200, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 49323, "s": 49298, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 49350, "s": 49323, "text": "How to Start Learning DSA?" }, { "code": null, "e": 49384, "s": 49350, "text": "K means Clustering - Introduction" }, { "code": null, "e": 49451, "s": 49384, "text": "Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete" }, { "code": null, "e": 49480, "s": 49451, "text": "Quadratic Probing in Hashing" }, { "code": null, "e": 49531, "s": 49480, "text": "Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 49589, "s": 49531, "text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2" }, { "code": null, "e": 49640, "s": 49589, "text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5" }, { "code": null, "e": 49667, "s": 49640, "text": "Program for array rotation" } ]
Deep Learning Tabular Data with PyTorch | by Offir Inbar | Towards Data Science
This Post will provide you a detailed end to end guide for using Pytorch for Tabular Data using a realistic example. By the end of this post, you will be able to build your Pytorch Model. Courses: I started with both fast.ai courses and DeepLearning.ai specialization (Coursera). They gave me the basic knowledge about DeepLearning. The great Stanford cs231n is also highly recommended. It’s very easy to watch more and more courses. I think that the most important thing is to be “Hands-On”. Write the code! Start a project or try to tackle a Kaggle competition. Use Python’s set_trace() to fully understand each step. One can find the full code Here I chose to work on the New York City Taxi Fare Prediction from Kaggle were the mission is to predict a rider’s taxi fare. Note that its a regression problem. You can find more details and the full Dataset Here. The training data contains more than 2 Million samples (5.31 GB). To minimize training time, One took a random subset of 100k training samples. import pandasimport randomfilename = r"C:\Users\User\Desktop\offir\study\computer learning\Kaggle_comp\NYC Taxi\train.csv"n = sum(1 for line in open(filename)) - 1 #number of records in file (excludes header)s = 100000 #desired sample sizeskip = sorted(random.sample(range(1,n+1),n-s)) #the 0-indexed header will not be included in the skip listdf = pandas.read_csv(filename, skiprows=skip)df.to_csv("temp.csv") I wrote my code using the free Google Colab. To use the GPU: Runtime -> Change runtime settings -> Hardware accelerator -> GPU. After Running the following command you need to upload the CSV file from your computer. Check the CSV file you are uploading is named sub_train. Upload also the test set The next step is to delete all the fares that are less than 0 (they don’t make sense) The length of df_train is now 99,990. it’s very important to keep track of the types and lengths of your different datasets at every step. The goal is to predict the fare amount. Therefore it was dropped from the train_X data frame. Moreover, I chose to predict the log of the price while training. the explanation is out of the scope of this blogpost. Let’s do some feature engineering. One Define the haverine_distatance function and Add a DateTime column to derive useful statistics. you can see the full process in the GitHub Repo. After this stage the Dataframe looks like this: Define Categorical and continuous columns and take only the relevant columns. Make the cat categories as type “category” and label encoder it. Define the Embedding size for the categorical columns. The rule of thumb for determining the embedding size is to divide the number of unique entries in each column by 2, but not to exceed 50. Now Let’s deal with the Continuous variables. before Normalizing them, it’s important to divide between the train and the test sets to prevent Data Leakage. Split between the training and validation set. in this case, the validation set is 20% of the total training set. X_train, X_val, y_train, y_val = train_test_split(X, Y, test_size=0.20, random_state=42,shuffle=True ) After this step, it important to take a look at the different shapes. currently, our data is stored in pandas arrays. PyTorch knows how to work with Tensors. The following steps will convert our data into the right type. Keep track of your data type in each step. I added comments with the current data type. It’s time to use PyTorch DataLoader. I chose the batch size to be 128, feel free to play with it. The goal is to define a model based on the number of continuous columns + the number of categorical columns and their embeddings. The output would be a single float value because of its a regression task. ps: dropout probability for each layer emb_drop: provide embedding dropout emd_szs: list of tuples: each categorical variable size is paired with an embedding size n_cont: number of continuous variables out_sz: output size Set a y_range for prediction (optional), and call the model. feel free to play with the inputs. The model looks like this: Define an optimizer. I chose Adam with a Learning Rate of 1e-2. The learning is the first Hyperparameter you should tune. moreover, the are different strategies to use the learning rate (fit one cycle, cosine, etc). Here I use a constant learning rate. Train your model. Try to track and understand each step. it’s very helpful to use the set_trace() command. The evaluation metric is RMSE. Pass the inputs to the fit function. the loss function, in this case, is MSEloss. Plot the Train vs Validation Loss After playing with the model and tuning the Hyperparameters you are getting to the point when you are satisfied with it. Only then you can go to the next step: test your model on the test set. Remember: your test has to go over the same process as the training set (we already did that). the next steps are “preparing” it to get evaluated. Divide into categorical and continuous columns and make them a Tensor. Make a prediction Ok, you finally made a prediction! congrats! Note that the prediction is now a Tensor. If one wants to change it to a Pandas Data frame walk through the steps in the repo. next, you can export it to a CSV file. If you are doing a Kaggle competition, upload it to Kaggle to see your score. In summary, you learned how to build a PyTorch model for Tabular data from scratch. You must go threw the full code and try to understand each line. Don’t forget to connect with me on Linkedin if you have any questions, comments or concerns.
[ { "code": null, "e": 359, "s": 171, "text": "This Post will provide you a detailed end to end guide for using Pytorch for Tabular Data using a realistic example. By the end of this post, you will be able to build your Pytorch Model." }, { "code": null, "e": 558, "s": 359, "text": "Courses: I started with both fast.ai courses and DeepLearning.ai specialization (Coursera). They gave me the basic knowledge about DeepLearning. The great Stanford cs231n is also highly recommended." }, { "code": null, "e": 735, "s": 558, "text": "It’s very easy to watch more and more courses. I think that the most important thing is to be “Hands-On”. Write the code! Start a project or try to tackle a Kaggle competition." }, { "code": null, "e": 791, "s": 735, "text": "Use Python’s set_trace() to fully understand each step." }, { "code": null, "e": 823, "s": 791, "text": "One can find the full code Here" }, { "code": null, "e": 1034, "s": 823, "text": "I chose to work on the New York City Taxi Fare Prediction from Kaggle were the mission is to predict a rider’s taxi fare. Note that its a regression problem. You can find more details and the full Dataset Here." }, { "code": null, "e": 1178, "s": 1034, "text": "The training data contains more than 2 Million samples (5.31 GB). To minimize training time, One took a random subset of 100k training samples." }, { "code": null, "e": 1590, "s": 1178, "text": "import pandasimport randomfilename = r\"C:\\Users\\User\\Desktop\\offir\\study\\computer learning\\Kaggle_comp\\NYC Taxi\\train.csv\"n = sum(1 for line in open(filename)) - 1 #number of records in file (excludes header)s = 100000 #desired sample sizeskip = sorted(random.sample(range(1,n+1),n-s)) #the 0-indexed header will not be included in the skip listdf = pandas.read_csv(filename, skiprows=skip)df.to_csv(\"temp.csv\")" }, { "code": null, "e": 1635, "s": 1590, "text": "I wrote my code using the free Google Colab." }, { "code": null, "e": 1718, "s": 1635, "text": "To use the GPU: Runtime -> Change runtime settings -> Hardware accelerator -> GPU." }, { "code": null, "e": 1863, "s": 1718, "text": "After Running the following command you need to upload the CSV file from your computer. Check the CSV file you are uploading is named sub_train." }, { "code": null, "e": 1888, "s": 1863, "text": "Upload also the test set" }, { "code": null, "e": 1974, "s": 1888, "text": "The next step is to delete all the fares that are less than 0 (they don’t make sense)" }, { "code": null, "e": 2113, "s": 1974, "text": "The length of df_train is now 99,990. it’s very important to keep track of the types and lengths of your different datasets at every step." }, { "code": null, "e": 2207, "s": 2113, "text": "The goal is to predict the fare amount. Therefore it was dropped from the train_X data frame." }, { "code": null, "e": 2327, "s": 2207, "text": "Moreover, I chose to predict the log of the price while training. the explanation is out of the scope of this blogpost." }, { "code": null, "e": 2362, "s": 2327, "text": "Let’s do some feature engineering." }, { "code": null, "e": 2510, "s": 2362, "text": "One Define the haverine_distatance function and Add a DateTime column to derive useful statistics. you can see the full process in the GitHub Repo." }, { "code": null, "e": 2558, "s": 2510, "text": "After this stage the Dataframe looks like this:" }, { "code": null, "e": 2636, "s": 2558, "text": "Define Categorical and continuous columns and take only the relevant columns." }, { "code": null, "e": 2701, "s": 2636, "text": "Make the cat categories as type “category” and label encoder it." }, { "code": null, "e": 2894, "s": 2701, "text": "Define the Embedding size for the categorical columns. The rule of thumb for determining the embedding size is to divide the number of unique entries in each column by 2, but not to exceed 50." }, { "code": null, "e": 3051, "s": 2894, "text": "Now Let’s deal with the Continuous variables. before Normalizing them, it’s important to divide between the train and the test sets to prevent Data Leakage." }, { "code": null, "e": 3165, "s": 3051, "text": "Split between the training and validation set. in this case, the validation set is 20% of the total training set." }, { "code": null, "e": 3268, "s": 3165, "text": "X_train, X_val, y_train, y_val = train_test_split(X, Y, test_size=0.20, random_state=42,shuffle=True )" }, { "code": null, "e": 3338, "s": 3268, "text": "After this step, it important to take a look at the different shapes." }, { "code": null, "e": 3577, "s": 3338, "text": "currently, our data is stored in pandas arrays. PyTorch knows how to work with Tensors. The following steps will convert our data into the right type. Keep track of your data type in each step. I added comments with the current data type." }, { "code": null, "e": 3675, "s": 3577, "text": "It’s time to use PyTorch DataLoader. I chose the batch size to be 128, feel free to play with it." }, { "code": null, "e": 3880, "s": 3675, "text": "The goal is to define a model based on the number of continuous columns + the number of categorical columns and their embeddings. The output would be a single float value because of its a regression task." }, { "code": null, "e": 3919, "s": 3880, "text": "ps: dropout probability for each layer" }, { "code": null, "e": 3955, "s": 3919, "text": "emb_drop: provide embedding dropout" }, { "code": null, "e": 4044, "s": 3955, "text": "emd_szs: list of tuples: each categorical variable size is paired with an embedding size" }, { "code": null, "e": 4083, "s": 4044, "text": "n_cont: number of continuous variables" }, { "code": null, "e": 4103, "s": 4083, "text": "out_sz: output size" }, { "code": null, "e": 4199, "s": 4103, "text": "Set a y_range for prediction (optional), and call the model. feel free to play with the inputs." }, { "code": null, "e": 4226, "s": 4199, "text": "The model looks like this:" }, { "code": null, "e": 4479, "s": 4226, "text": "Define an optimizer. I chose Adam with a Learning Rate of 1e-2. The learning is the first Hyperparameter you should tune. moreover, the are different strategies to use the learning rate (fit one cycle, cosine, etc). Here I use a constant learning rate." }, { "code": null, "e": 4617, "s": 4479, "text": "Train your model. Try to track and understand each step. it’s very helpful to use the set_trace() command. The evaluation metric is RMSE." }, { "code": null, "e": 4699, "s": 4617, "text": "Pass the inputs to the fit function. the loss function, in this case, is MSEloss." }, { "code": null, "e": 4733, "s": 4699, "text": "Plot the Train vs Validation Loss" }, { "code": null, "e": 4926, "s": 4733, "text": "After playing with the model and tuning the Hyperparameters you are getting to the point when you are satisfied with it. Only then you can go to the next step: test your model on the test set." }, { "code": null, "e": 5073, "s": 4926, "text": "Remember: your test has to go over the same process as the training set (we already did that). the next steps are “preparing” it to get evaluated." }, { "code": null, "e": 5144, "s": 5073, "text": "Divide into categorical and continuous columns and make them a Tensor." }, { "code": null, "e": 5162, "s": 5144, "text": "Make a prediction" }, { "code": null, "e": 5207, "s": 5162, "text": "Ok, you finally made a prediction! congrats!" }, { "code": null, "e": 5373, "s": 5207, "text": "Note that the prediction is now a Tensor. If one wants to change it to a Pandas Data frame walk through the steps in the repo. next, you can export it to a CSV file." }, { "code": null, "e": 5451, "s": 5373, "text": "If you are doing a Kaggle competition, upload it to Kaggle to see your score." }, { "code": null, "e": 5600, "s": 5451, "text": "In summary, you learned how to build a PyTorch model for Tabular data from scratch. You must go threw the full code and try to understand each line." } ]
Build a Simple Todo App using React | Towards Data Science
Hello readers! This is the first time I am writing an article on building something with React. So, I am also new to React and Frontend Frameworks. And the best way to make your first React project would be to make a simple Todo App. Building a Todo App is easy and does not take much time but it teaches you some important concepts. It teaches you the principle of CRUD (Create, Read, Update and Delete) which are very important to understand for any developer. Since this is our first project in the React world, we would keep things simple. We won’t be using Redux for state management and we would not use any kind of server to manage it. Building a simple Todo list means we won’t be able to keep track of the todos once we refresh the page. So, it is not a perfect solution but a good start. We will learn to build an advanced Todo App which would involve Redux and a server but for now, we would like to keep things simple. We would build a simple working React app with some styling. So, let’s begin:- So, let’s start building our first React Todo app. We would be using create-react-app to help us bootstrap the React App for us. npm install create-react-app Running the above command would install create-react-app in our project. Now, this would be ready for use. To create a new project named ‘todo’, we would run the command as follows:- create-react-app todo Now, this would create a folder named ‘todo’ in our current repository. Next, we should move inside the todo folder by doing: cd todo Now, we will install two libraries using npm which would help us with using the Bootstrap library in our app to apply the styling. npm install react-bootstrap bootstrap Running the above command will install both react-bootstrap and bootstrap libraries in our application. Now, we are ready to build the app. Now, let’s write some custom CSS code to do some styling. Do not worry about this part. It is very simple styling to make our Todo app look a bit nicer. .app { padding: 30px; background-color: floralwhite;}.todo { align-items: center; display: flex; font-size: 18px; justify-content: space-between;} We will do the rest of the styling using react-bootstrap components. Next, we will start with the main part, the App.js file. We will start by importing the required things in our App.js file. import React from "react";import "./App.css";import { Button, Card, Form } from 'react-bootstrap';import 'bootstrap/dist/css/bootstrap.min.css'; We will use React Hooks to allow us to replace the class-based components with functional components and still use all features without any issues. So, we start with the main function of the App. We will define a todos javascript list which would contain all our todos and also carries the status of each todo whether they are done or not. We will use setTodos and will use React.useState which is enabled by React Hooks. function App() { const [todos, setTodos] = React.useState([ { text: "This is a sampe todo", isDone: false } ]);} Next, we move to the part of adding todos. We will define an addTodo function and will define a newTodos which would take the todos list and append the new todo’s text to the list using the spread operator. We then use setTodos to set newTodos as todos. const addTodo = text => { const newTodos = [...todos, { text }]; setTodos(newTodos); }; Next, we move to the part of marking Todos as done. We will define a markTodo function. We use the spread operator to copy all the todos in newTodos and then we mark the todo as done by using its index and then we set the newTodos as todos. const markTodo = index => { const newTodos = [...todos]; newTodos[index].isDone = true; setTodos(newTodos); }; Next, we move the part of deleting the todos. In the same way, this time we use the index to splice the list and remove the todo whose index matches and then we set the new todos. const removeTodo = index => { const newTodos = [...todos]; newTodos.splice(index, 1); setTodos(newTodos); }; We then finish off the App function by returning the JSX rendering which would be displayed on the website. We are using a FormTodo component which we will define later on. It accepts the addTodo as a parameter. Then we display all the todos using the map operator. For each todo, we will pass it to the Todo component (will define later). We send the index, todo, the markTodo and removeTodo functions. return ( <div className="app"> <div className="container"> <h1 className="text-center mb-4">Todo List</h1> <FormTodo addTodo={addTodo} /> <div> {todos.map((todo, index) => ( <Card> <Card.Body> <Todo key={index} index={index} todo={todo} markTodo={markTodo} removeTodo={removeTodo} /> </Card.Body> </Card> ))} </div> </div> </div> ); Now, we will define the Todo component. It accepts the four parameters which we passed on earlier when we called the Todo component. We return some JSX which would show each Todo. It will also show two buttons for marking Todos as Done and for removing the Todo respectively. function Todo({ todo, index, markTodo, removeTodo }) { return ( <div className="todo" > <span style={{ textDecoration: todo.isDone ? "line-through" : "" }}>{todo.text}</span> <div> <Button variant="outline-success" onClick={() => markTodo(index)}>✓</Button>{' '} <Button variant="outline-danger" onClick={() => removeTodo(index)}>✕</Button> </div> </div> );} Next, we would define the FormTodo function. It accepts the addTodo as a parameter. It handles the submission of a new Todo. If the value is not empty, then we call the addTodo function on that todo text and then set the value of the form to empty again. We return a form which accepts a Todo and has a Submit button for submission of the todos. Clicking on the submit button would add the Todo in the Todo list. function FormTodo({ addTodo }) { const [value, setValue] = React.useState(""); const handleSubmit = e => { e.preventDefault(); if (!value) return; addTodo(value); setValue(""); }; return ( <Form onSubmit={handleSubmit}> <Form.Group> <Form.Label><b>Add Todo</b></Form.Label> <Form.Control type="text" className="input" value={value} onChange={e => setValue(e.target.value)} placeholder="Add new todo" /> </Form.Group> <Button variant="primary mb-3" type="submit"> Submit </Button> </Form> );} Now, let’s have a look at the complete App.js file:- In this way, we had built our simple Todo App. You can try out this simple React Todo which we have built on this website hosted on Github pages. You can access the GitHub repository of this article and see the complete package structure and code. Some more articles to read after this one:-
[ { "code": null, "e": 406, "s": 172, "text": "Hello readers! This is the first time I am writing an article on building something with React. So, I am also new to React and Frontend Frameworks. And the best way to make your first React project would be to make a simple Todo App." }, { "code": null, "e": 635, "s": 406, "text": "Building a Todo App is easy and does not take much time but it teaches you some important concepts. It teaches you the principle of CRUD (Create, Read, Update and Delete) which are very important to understand for any developer." }, { "code": null, "e": 815, "s": 635, "text": "Since this is our first project in the React world, we would keep things simple. We won’t be using Redux for state management and we would not use any kind of server to manage it." }, { "code": null, "e": 970, "s": 815, "text": "Building a simple Todo list means we won’t be able to keep track of the todos once we refresh the page. So, it is not a perfect solution but a good start." }, { "code": null, "e": 1164, "s": 970, "text": "We will learn to build an advanced Todo App which would involve Redux and a server but for now, we would like to keep things simple. We would build a simple working React app with some styling." }, { "code": null, "e": 1182, "s": 1164, "text": "So, let’s begin:-" }, { "code": null, "e": 1311, "s": 1182, "text": "So, let’s start building our first React Todo app. We would be using create-react-app to help us bootstrap the React App for us." }, { "code": null, "e": 1340, "s": 1311, "text": "npm install create-react-app" }, { "code": null, "e": 1447, "s": 1340, "text": "Running the above command would install create-react-app in our project. Now, this would be ready for use." }, { "code": null, "e": 1523, "s": 1447, "text": "To create a new project named ‘todo’, we would run the command as follows:-" }, { "code": null, "e": 1545, "s": 1523, "text": "create-react-app todo" }, { "code": null, "e": 1671, "s": 1545, "text": "Now, this would create a folder named ‘todo’ in our current repository. Next, we should move inside the todo folder by doing:" }, { "code": null, "e": 1679, "s": 1671, "text": "cd todo" }, { "code": null, "e": 1810, "s": 1679, "text": "Now, we will install two libraries using npm which would help us with using the Bootstrap library in our app to apply the styling." }, { "code": null, "e": 1848, "s": 1810, "text": "npm install react-bootstrap bootstrap" }, { "code": null, "e": 1952, "s": 1848, "text": "Running the above command will install both react-bootstrap and bootstrap libraries in our application." }, { "code": null, "e": 1988, "s": 1952, "text": "Now, we are ready to build the app." }, { "code": null, "e": 2141, "s": 1988, "text": "Now, let’s write some custom CSS code to do some styling. Do not worry about this part. It is very simple styling to make our Todo app look a bit nicer." }, { "code": null, "e": 2294, "s": 2141, "text": ".app { padding: 30px; background-color: floralwhite;}.todo { align-items: center; display: flex; font-size: 18px; justify-content: space-between;}" }, { "code": null, "e": 2363, "s": 2294, "text": "We will do the rest of the styling using react-bootstrap components." }, { "code": null, "e": 2487, "s": 2363, "text": "Next, we will start with the main part, the App.js file. We will start by importing the required things in our App.js file." }, { "code": null, "e": 2632, "s": 2487, "text": "import React from \"react\";import \"./App.css\";import { Button, Card, Form } from 'react-bootstrap';import 'bootstrap/dist/css/bootstrap.min.css';" }, { "code": null, "e": 2780, "s": 2632, "text": "We will use React Hooks to allow us to replace the class-based components with functional components and still use all features without any issues." }, { "code": null, "e": 3054, "s": 2780, "text": "So, we start with the main function of the App. We will define a todos javascript list which would contain all our todos and also carries the status of each todo whether they are done or not. We will use setTodos and will use React.useState which is enabled by React Hooks." }, { "code": null, "e": 3185, "s": 3054, "text": "function App() { const [todos, setTodos] = React.useState([ { text: \"This is a sampe todo\", isDone: false } ]);}" }, { "code": null, "e": 3439, "s": 3185, "text": "Next, we move to the part of adding todos. We will define an addTodo function and will define a newTodos which would take the todos list and append the new todo’s text to the list using the spread operator. We then use setTodos to set newTodos as todos." }, { "code": null, "e": 3534, "s": 3439, "text": "const addTodo = text => { const newTodos = [...todos, { text }]; setTodos(newTodos); };" }, { "code": null, "e": 3775, "s": 3534, "text": "Next, we move to the part of marking Todos as done. We will define a markTodo function. We use the spread operator to copy all the todos in newTodos and then we mark the todo as done by using its index and then we set the newTodos as todos." }, { "code": null, "e": 3896, "s": 3775, "text": "const markTodo = index => { const newTodos = [...todos]; newTodos[index].isDone = true; setTodos(newTodos); };" }, { "code": null, "e": 4076, "s": 3896, "text": "Next, we move the part of deleting the todos. In the same way, this time we use the index to splice the list and remove the todo whose index matches and then we set the new todos." }, { "code": null, "e": 4195, "s": 4076, "text": "const removeTodo = index => { const newTodos = [...todos]; newTodos.splice(index, 1); setTodos(newTodos); };" }, { "code": null, "e": 4407, "s": 4195, "text": "We then finish off the App function by returning the JSX rendering which would be displayed on the website. We are using a FormTodo component which we will define later on. It accepts the addTodo as a parameter." }, { "code": null, "e": 4599, "s": 4407, "text": "Then we display all the todos using the map operator. For each todo, we will pass it to the Todo component (will define later). We send the index, todo, the markTodo and removeTodo functions." }, { "code": null, "e": 5148, "s": 4599, "text": "return ( <div className=\"app\"> <div className=\"container\"> <h1 className=\"text-center mb-4\">Todo List</h1> <FormTodo addTodo={addTodo} /> <div> {todos.map((todo, index) => ( <Card> <Card.Body> <Todo key={index} index={index} todo={todo} markTodo={markTodo} removeTodo={removeTodo} /> </Card.Body> </Card> ))} </div> </div> </div> );" }, { "code": null, "e": 5281, "s": 5148, "text": "Now, we will define the Todo component. It accepts the four parameters which we passed on earlier when we called the Todo component." }, { "code": null, "e": 5424, "s": 5281, "text": "We return some JSX which would show each Todo. It will also show two buttons for marking Todos as Done and for removing the Todo respectively." }, { "code": null, "e": 5834, "s": 5424, "text": "function Todo({ todo, index, markTodo, removeTodo }) { return ( <div className=\"todo\" > <span style={{ textDecoration: todo.isDone ? \"line-through\" : \"\" }}>{todo.text}</span> <div> <Button variant=\"outline-success\" onClick={() => markTodo(index)}>✓</Button>{' '} <Button variant=\"outline-danger\" onClick={() => removeTodo(index)}>✕</Button> </div> </div> );}" }, { "code": null, "e": 6089, "s": 5834, "text": "Next, we would define the FormTodo function. It accepts the addTodo as a parameter. It handles the submission of a new Todo. If the value is not empty, then we call the addTodo function on that todo text and then set the value of the form to empty again." }, { "code": null, "e": 6247, "s": 6089, "text": "We return a form which accepts a Todo and has a Submit button for submission of the todos. Clicking on the submit button would add the Todo in the Todo list." }, { "code": null, "e": 6788, "s": 6247, "text": "function FormTodo({ addTodo }) { const [value, setValue] = React.useState(\"\"); const handleSubmit = e => { e.preventDefault(); if (!value) return; addTodo(value); setValue(\"\"); }; return ( <Form onSubmit={handleSubmit}> <Form.Group> <Form.Label><b>Add Todo</b></Form.Label> <Form.Control type=\"text\" className=\"input\" value={value} onChange={e => setValue(e.target.value)} placeholder=\"Add new todo\" /> </Form.Group> <Button variant=\"primary mb-3\" type=\"submit\"> Submit </Button> </Form> );}" }, { "code": null, "e": 6841, "s": 6788, "text": "Now, let’s have a look at the complete App.js file:-" }, { "code": null, "e": 6987, "s": 6841, "text": "In this way, we had built our simple Todo App. You can try out this simple React Todo which we have built on this website hosted on Github pages." }, { "code": null, "e": 7089, "s": 6987, "text": "You can access the GitHub repository of this article and see the complete package structure and code." } ]
Java Recursion
Recursion is the technique of making a function call itself. This technique provides a way to break complicated problems down into simple problems which are easier to solve. Recursion may be a bit difficult to understand. The best way to figure out how it works is to experiment with it. Adding two numbers together is easy to do, but adding a range of numbers is more complicated. In the following example, recursion is used to add a range of numbers together by breaking it down into the simple task of adding two numbers: Use recursion to add all of the numbers up to 10. public class Main { public static void main(String[] args) { int result = sum(10); System.out.println(result); } public static int sum(int k) { if (k > 0) { return k + sum(k - 1); } else { return 0; } } } Try it Yourself » When the sum() function is called, it adds parameter k to the sum of all numbers smaller than k and returns the result. When k becomes 0, the function just returns 0. When running, the program follows these steps: Since the function does not call itself when k is 0, the program stops there and returns the result. Just as loops can run into the problem of infinite looping, recursive functions can run into the problem of infinite recursion. Infinite recursion is when the function never stops calling itself. Every recursive function should have a halting condition, which is the condition where the function stops calling itself. In the previous example, the halting condition is when the parameter k becomes 0. It is helpful to see a variety of different examples to better understand the concept. In this example, the function adds a range of numbers between a start and an end. The halting condition for this recursive function is when end is not greater than start: Use recursion to add all of the numbers between 5 to 10. public class Main { public static void main(String[] args) { int result = sum(5, 10); System.out.println(result); } public static int sum(int start, int end) { if (end > start) { return end + sum(start, end - 1); } else { return end; } } } Try it Yourself » The developer should be very careful with recursion as it can be quite easy to slip into writing a function which never terminates, or one that uses excess amounts of memory or processor power. However, when written correctly recursion can be a very efficient and mathematically-elegant approach to programming. 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: help@w3schools.com Your message has been sent to W3Schools.
[ { "code": null, "e": 174, "s": 0, "text": "Recursion is the technique of making a function call itself. This technique provides a way\nto break complicated problems down into simple problems which are easier to solve." }, { "code": null, "e": 288, "s": 174, "text": "Recursion may be a bit difficult to understand. The\nbest way to figure out how it works is to experiment with it." }, { "code": null, "e": 525, "s": 288, "text": "Adding two numbers together is easy to do, but adding a range of numbers is more\ncomplicated. In the following example, recursion is used to add a range of numbers\ntogether by breaking it down into the simple task of adding two numbers:" }, { "code": null, "e": 575, "s": 525, "text": "Use recursion to add all of the numbers up to 10." }, { "code": null, "e": 820, "s": 575, "text": "public class Main {\n public static void main(String[] args) {\n int result = sum(10);\n System.out.println(result);\n }\n public static int sum(int k) {\n if (k > 0) {\n return k + sum(k - 1);\n } else {\n return 0;\n }\n }\n}" }, { "code": null, "e": 840, "s": 820, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 1054, "s": 840, "text": "When the sum() function is called, it adds parameter k to the sum of all numbers smaller\nthan k and returns the result. When k becomes 0, the function just returns 0. When\nrunning, the program follows these steps:" }, { "code": null, "e": 1155, "s": 1054, "text": "Since the function does not call itself when k is 0, the program stops there and returns the\nresult." }, { "code": null, "e": 1555, "s": 1155, "text": "Just as loops can run into the problem of infinite looping, recursive functions can run into\nthe problem of infinite recursion. Infinite recursion is when the function never stops calling\nitself. Every recursive function should have a halting condition, which is the condition\nwhere the function stops calling itself. In the previous example, the halting condition is\nwhen the parameter k becomes 0." }, { "code": null, "e": 1813, "s": 1555, "text": "It is helpful to see a variety of different examples to better understand the concept. In this\nexample, the function adds a range of numbers between a start and an end. The halting\ncondition for this recursive function is when end is not greater than start:" }, { "code": null, "e": 1870, "s": 1813, "text": "Use recursion to add all of the numbers between 5 to 10." }, { "code": null, "e": 2150, "s": 1870, "text": "public class Main {\n public static void main(String[] args) {\n int result = sum(5, 10);\n System.out.println(result);\n }\n public static int sum(int start, int end) {\n if (end > start) {\n return end + sum(start, end - 1);\n } else {\n return end;\n }\n }\n}" }, { "code": null, "e": 2170, "s": 2150, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 2482, "s": 2170, "text": "The developer should be very careful with recursion as it can be quite easy to slip into writing a function which never terminates, or one that uses excess amounts of memory or processor power. However, when written correctly recursion can be a very efficient and mathematically-elegant approach to programming." }, { "code": null, "e": 2515, "s": 2482, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 2557, "s": 2515, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 2664, "s": 2557, "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": 2683, "s": 2664, "text": "help@w3schools.com" } ]
Use ListIterator to traverse an ArrayList in the reverse direction in Java
A ListIterator can be used to traverse the elements in the forward direction as well as the reverse direction in the List Collection. So the ListIterator is only valid for classes such as LinkedList, ArrayList etc. The method hasPrevious( ) in ListIterator returns true if there are more elements in the List while traversing in the reverse direction and false otherwise. The method previous( ) returns the previous element in the List and reduces the cursor position backward. A program that demonstrates this is given as follows − Live Demo import java.util.ArrayList; import java.util.ListIterator; public class Demo { public static void main(String[] args) { ArrayList<String> aList = new ArrayList<String>(); aList.add("Amanda"); aList.add("Peter"); aList.add("Julie"); aList.add("James"); aList.add("Emma"); ListIterator<String> li = aList.listIterator(); while (li.hasNext()) { li.next(); } System.out.println("The ArrayList elements in the reverse direction are: "); while (li.hasPrevious()) { System.out.println(li.previous()); } } } The ArrayList elements in the reverse direction are: Emma James Julie Peter Amanda Now let us understand the above program. The ArrayList is created and ArrayList.add() is used to add the elements to the ArrayList. A code snippet which demonstrates this is as follows − ArrayList<String> aList = new ArrayList<String>(); aList.add("Amanda"); aList.add("Peter"); aList.add("Julie"); aList.add("James"); aList.add("Emma"); Then the ListIterator interface is used to display the ArrayList elements in the reverse direction. A code snippet which demonstrates this is as follows − ListIterator<String> li = aList.listIterator(); while (li.hasNext()) { li.next(); } System.out.println("The ArrayList elements in the reverse direction are: "); while (li.hasPrevious()) { System.out.println(li.previous()); }
[ { "code": null, "e": 1277, "s": 1062, "text": "A ListIterator can be used to traverse the elements in the forward direction as well as the reverse direction in the List Collection. So the ListIterator is only valid for classes such as LinkedList, ArrayList etc." }, { "code": null, "e": 1540, "s": 1277, "text": "The method hasPrevious( ) in ListIterator returns true if there are more elements in the List while traversing in the reverse direction and false otherwise. The method previous( ) returns the previous element in the List and reduces the cursor position backward." }, { "code": null, "e": 1595, "s": 1540, "text": "A program that demonstrates this is given as follows −" }, { "code": null, "e": 1606, "s": 1595, "text": " Live Demo" }, { "code": null, "e": 2202, "s": 1606, "text": "import java.util.ArrayList;\nimport java.util.ListIterator;\npublic class Demo {\n public static void main(String[] args) {\n ArrayList<String> aList = new ArrayList<String>();\n aList.add(\"Amanda\");\n aList.add(\"Peter\");\n aList.add(\"Julie\");\n aList.add(\"James\");\n aList.add(\"Emma\");\n ListIterator<String> li = aList.listIterator();\n while (li.hasNext()) {\n li.next();\n }\n System.out.println(\"The ArrayList elements in the reverse direction are: \");\n while (li.hasPrevious()) {\n System.out.println(li.previous());\n }\n }\n}" }, { "code": null, "e": 2285, "s": 2202, "text": "The ArrayList elements in the reverse direction are:\nEmma\nJames\nJulie\nPeter\nAmanda" }, { "code": null, "e": 2326, "s": 2285, "text": "Now let us understand the above program." }, { "code": null, "e": 2472, "s": 2326, "text": "The ArrayList is created and ArrayList.add() is used to add the elements to the ArrayList. A code snippet which demonstrates this is as follows −" }, { "code": null, "e": 2623, "s": 2472, "text": "ArrayList<String> aList = new ArrayList<String>();\naList.add(\"Amanda\");\naList.add(\"Peter\");\naList.add(\"Julie\");\naList.add(\"James\");\naList.add(\"Emma\");" }, { "code": null, "e": 2778, "s": 2623, "text": "Then the ListIterator interface is used to display the ArrayList elements in the reverse direction. A code snippet which demonstrates this is as follows −" }, { "code": null, "e": 3009, "s": 2778, "text": "ListIterator<String> li = aList.listIterator();\nwhile (li.hasNext()) {\n li.next();\n}\nSystem.out.println(\"The ArrayList elements in the reverse direction are: \");\nwhile (li.hasPrevious()) {\n System.out.println(li.previous());\n}" } ]
Java Program to Read and Print All Files From a Zip File - GeeksforGeeks
29 Sep, 2021 A zip file is a file where one or more files are compressed together, generally, zip files are ideal for storing large files. Here the zip file will first read and at the same time printing the contents of a zip file using a java program using the java.util.zip.ZipEntry class for marking the zip file and after reading it, the contents inside it would be printed. If in-case, the zip file is not found the code will throw an input-output exception that FileNotFoundException Illustration: Considering a system that stores a zip file named geekforgeeks.zip at D drive in windows operating system D:/geeks.zip in windows operating system Archive.zip in macOS operating system Case 1: geekforgeeks.zip Input : D:/geekforgeeks.zip Output : The files in the Zip are as follows: Java program to print a number.java Java program to print your name.java Java program to calculate.java Java program to print a pattern.java Now if a system does not store the specific zip file inputted by the user then the code would throw an exception and print a message that the file has not been found. Case 2: D:/geeks.zip Input : D:/geeks.zip Output : java.io.FileNotFoundException: D:/geeks.zip (The system cannot find the file specified) Case 3: Archive.zip It is the same as case 1 so reserving this for the implementation part just on the different operating system as shown in the example with greater depth. Approach Take the location of the zip file as input in the main method. The location of the zip file is now sent to the method. In the method, the file is read and its content is printed. If in-case the file is not found, the code would throw an exception. Example Java // Java program to read and print all files// from a zip file // Importing input output classesimport java.io.BufferedInputStream;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;// Importing zip classes and Scanner class// from java.util packageimport java.util.Scanner;import java.util.zip.ZipEntry;import java.util.zip.ZipInputStream; // Class to Read and print the Zip Filespublic class GFG { // Function to read and print the file names. public void printFileContent(String filePath) { // Creating objects for the classes and // initializing them to null FileInputStream fs = null; ZipInputStream Zs = null; ZipEntry ze = null; // Try block to handle if exception occurs try { // Display message when program compiles // successfully System.out.println( "Files in the zip are as follows: "); fs = new FileInputStream(filePath); Zs = new ZipInputStream( new BufferedInputStream(fs)); // Loop to read and print the zip file name till // the end while ((ze = Zs.getNextEntry()) != null) { System.out.println(ze.getName()); } // Closing the file connection Zs.close(); } // Catch block to handle if any exception related // to file handling occurs catch (FileNotFoundException fe) { // Print the line line and exception // of the program where it occurred fe.printStackTrace(); } // Catch block to handle generic exceptions catch (IOException ie) { // Print the line line and exception // of the program where it occurred ie.printStackTrace(); } } // Main driver method public static void main(String[] args) { // Creating an object of the file GFG zf = new GFG(); // Taking input of the zip file from local directory // Name of the zip file to be read should be entered Scanner sc = new Scanner(System.in); // Display message asking user to enter // zip file local directory System.out.println( "Enter the location of the zip file: "); String str = sc.nextLine(); // Print the zip files(compressed files) zf.printFileContent(str); }} Output: Zip file chosen: Archive.zip Zip file directory on local computer: /Users/mayanksolanki/Desktop/Job/Geekathon/Archive.zip As seen above the following zip file prints out 5 files inside it. (All image of .png format) Files in the zip are as follows: Q1.Vaidik.Try2.png __MACOSX/._Q1.Vaidik.Try2.png Q2.Vaidik.Rry1.Output.png __MACOSX/._Q2.Vaidik.Rry1.Output.png Q2.Vaidik.Try2.png __MACOSX/._Q2.Vaidik.Try2.png Q4.Vaidik.OSI.png __MACOSX/._Q4.Vaidik.OSI.png Q12Vaidik.Try1.png __MACOSX/._Q12Vaidik.Try1.png sooda367 sweetyty Picked Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Functional Interfaces in Java Stream In Java Constructors in Java Different ways of Reading a text file in Java Exceptions in Java Convert a String to Character array in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class Factory method design pattern in Java
[ { "code": null, "e": 23583, "s": 23555, "text": "\n29 Sep, 2021" }, { "code": null, "e": 24060, "s": 23583, "text": "A zip file is a file where one or more files are compressed together, generally, zip files are ideal for storing large files. Here the zip file will first read and at the same time printing the contents of a zip file using a java program using the java.util.zip.ZipEntry class for marking the zip file and after reading it, the contents inside it would be printed. If in-case, the zip file is not found the code will throw an input-output exception that FileNotFoundException" }, { "code": null, "e": 24074, "s": 24060, "text": "Illustration:" }, { "code": null, "e": 24124, "s": 24074, "text": "Considering a system that stores a zip file named" }, { "code": null, "e": 24180, "s": 24124, "text": "geekforgeeks.zip at D drive in windows operating system" }, { "code": null, "e": 24221, "s": 24180, "text": "D:/geeks.zip in windows operating system" }, { "code": null, "e": 24259, "s": 24221, "text": "Archive.zip in macOS operating system" }, { "code": null, "e": 24284, "s": 24259, "text": "Case 1: geekforgeeks.zip" }, { "code": null, "e": 24536, "s": 24284, "text": "Input : D:/geekforgeeks.zip\nOutput : The files in the Zip are as follows:\n Java program to print a number.java\n Java program to print your name.java\n Java program to calculate.java\n Java program to print a pattern.java" }, { "code": null, "e": 24703, "s": 24536, "text": "Now if a system does not store the specific zip file inputted by the user then the code would throw an exception and print a message that the file has not been found." }, { "code": null, "e": 24724, "s": 24703, "text": "Case 2: D:/geeks.zip" }, { "code": null, "e": 24844, "s": 24724, "text": "Input : D:/geeks.zip\nOutput : java.io.FileNotFoundException: D:/geeks.zip (The system cannot find the file specified)" }, { "code": null, "e": 24864, "s": 24844, "text": "Case 3: Archive.zip" }, { "code": null, "e": 25018, "s": 24864, "text": "It is the same as case 1 so reserving this for the implementation part just on the different operating system as shown in the example with greater depth." }, { "code": null, "e": 25027, "s": 25018, "text": "Approach" }, { "code": null, "e": 25090, "s": 25027, "text": "Take the location of the zip file as input in the main method." }, { "code": null, "e": 25146, "s": 25090, "text": "The location of the zip file is now sent to the method." }, { "code": null, "e": 25206, "s": 25146, "text": "In the method, the file is read and its content is printed." }, { "code": null, "e": 25275, "s": 25206, "text": "If in-case the file is not found, the code would throw an exception." }, { "code": null, "e": 25283, "s": 25275, "text": "Example" }, { "code": null, "e": 25288, "s": 25283, "text": "Java" }, { "code": "// Java program to read and print all files// from a zip file // Importing input output classesimport java.io.BufferedInputStream;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;// Importing zip classes and Scanner class// from java.util packageimport java.util.Scanner;import java.util.zip.ZipEntry;import java.util.zip.ZipInputStream; // Class to Read and print the Zip Filespublic class GFG { // Function to read and print the file names. public void printFileContent(String filePath) { // Creating objects for the classes and // initializing them to null FileInputStream fs = null; ZipInputStream Zs = null; ZipEntry ze = null; // Try block to handle if exception occurs try { // Display message when program compiles // successfully System.out.println( \"Files in the zip are as follows: \"); fs = new FileInputStream(filePath); Zs = new ZipInputStream( new BufferedInputStream(fs)); // Loop to read and print the zip file name till // the end while ((ze = Zs.getNextEntry()) != null) { System.out.println(ze.getName()); } // Closing the file connection Zs.close(); } // Catch block to handle if any exception related // to file handling occurs catch (FileNotFoundException fe) { // Print the line line and exception // of the program where it occurred fe.printStackTrace(); } // Catch block to handle generic exceptions catch (IOException ie) { // Print the line line and exception // of the program where it occurred ie.printStackTrace(); } } // Main driver method public static void main(String[] args) { // Creating an object of the file GFG zf = new GFG(); // Taking input of the zip file from local directory // Name of the zip file to be read should be entered Scanner sc = new Scanner(System.in); // Display message asking user to enter // zip file local directory System.out.println( \"Enter the location of the zip file: \"); String str = sc.nextLine(); // Print the zip files(compressed files) zf.printFileContent(str); }}", "e": 27735, "s": 25288, "text": null }, { "code": null, "e": 27745, "s": 27735, "text": "Output: " }, { "code": null, "e": 27774, "s": 27745, "text": "Zip file chosen: Archive.zip" }, { "code": null, "e": 27867, "s": 27774, "text": "Zip file directory on local computer: /Users/mayanksolanki/Desktop/Job/Geekathon/Archive.zip" }, { "code": null, "e": 27962, "s": 27867, "text": "As seen above the following zip file prints out 5 files inside it. (All image of .png format) " }, { "code": null, "e": 27996, "s": 27962, "text": "Files in the zip are as follows: " }, { "code": null, "e": 28015, "s": 27996, "text": "Q1.Vaidik.Try2.png" }, { "code": null, "e": 28045, "s": 28015, "text": "__MACOSX/._Q1.Vaidik.Try2.png" }, { "code": null, "e": 28071, "s": 28045, "text": "Q2.Vaidik.Rry1.Output.png" }, { "code": null, "e": 28108, "s": 28071, "text": "__MACOSX/._Q2.Vaidik.Rry1.Output.png" }, { "code": null, "e": 28127, "s": 28108, "text": "Q2.Vaidik.Try2.png" }, { "code": null, "e": 28157, "s": 28127, "text": "__MACOSX/._Q2.Vaidik.Try2.png" }, { "code": null, "e": 28175, "s": 28157, "text": "Q4.Vaidik.OSI.png" }, { "code": null, "e": 28204, "s": 28175, "text": "__MACOSX/._Q4.Vaidik.OSI.png" }, { "code": null, "e": 28223, "s": 28204, "text": "Q12Vaidik.Try1.png" }, { "code": null, "e": 28253, "s": 28223, "text": "__MACOSX/._Q12Vaidik.Try1.png" }, { "code": null, "e": 28264, "s": 28255, "text": "sooda367" }, { "code": null, "e": 28273, "s": 28264, "text": "sweetyty" }, { "code": null, "e": 28280, "s": 28273, "text": "Picked" }, { "code": null, "e": 28285, "s": 28280, "text": "Java" }, { "code": null, "e": 28299, "s": 28285, "text": "Java Programs" }, { "code": null, "e": 28304, "s": 28299, "text": "Java" }, { "code": null, "e": 28402, "s": 28304, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28411, "s": 28402, "text": "Comments" }, { "code": null, "e": 28424, "s": 28411, "text": "Old Comments" }, { "code": null, "e": 28454, "s": 28424, "text": "Functional Interfaces in Java" }, { "code": null, "e": 28469, "s": 28454, "text": "Stream In Java" }, { "code": null, "e": 28490, "s": 28469, "text": "Constructors in Java" }, { "code": null, "e": 28536, "s": 28490, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 28555, "s": 28536, "text": "Exceptions in Java" }, { "code": null, "e": 28599, "s": 28555, "text": "Convert a String to Character array in Java" }, { "code": null, "e": 28625, "s": 28599, "text": "Java Programming Examples" }, { "code": null, "e": 28659, "s": 28625, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 28706, "s": 28659, "text": "Implementing a Linked List in Java using Class" } ]
How to check whether a string is in lowercase or uppercase in R?
We can use str_detect function to check whether a single string or a vector of strings is in lowercase or uppercase. Along with str_detect function, we need to use either upper or lower to check whether the string is in lowercase or uppercase and the output will be returned in TRUE or FALSE form, if the string will be in lowercase and we pass lower with str_detect function then the output will be TRUE and vice-versa. Live Demo x1<-letters[1:26] x1 [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s" [20] "t" "u" "v" "w" "x" "y" "z" str_detect(x1,"[[:upper:]]") [1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE [13] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE [25] FALSE FALSE Live Demo x2<-LETTERS[1:26] x2 [1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q" "R" "S" [20] "T" "U" "V" "W" "X" "Y" "Z" str_detect(x2,"[[:upper:]]") [1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE [16] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE Live Demo x3<-"india" x3 [1] "india" str_detect(x3,"[[:upper:]]") [1] FALSE Live Demo x4<-c("abc","abcd","abcde","bacdef") x4 [1] "abc" "abcd" "abcde" "bacdef" str_detect(x4,"[[:upper:]]") [1] FALSE FALSE FALSE FALSE Live Demo x5<-c("AK", "AL", "AR", "AS", "AZ", "CA", "CO", "CT", "DC", "DE", "FL", "GA", "GU", "HI", "IA", "ID", "IL", "IN", "KS", "KY", "LA", "MA", "MD", "ME", "MI", "MN", "MO", "MP", "MS", "MT", "NC", "ND", "NE", "NH", "NJ", "NM", "NV", "NY", "OH", "OK", "OR", "PA", "PR", "RI", "SC", "SD", "TN", "TX", "UM", "UT", "VA", "VI", "VT", "WA", "WI", "WV", "WY") x5 [1] "AK" "AL" "AR" "AS" "AZ" "CA" "CO" "CT" "DC" "DE" "FL" "GA" "GU" "HI" "IA" [16] "ID" "IL" "IN" "KS" "KY" "LA" "MA" "MD" "ME" "MI" "MN" "MO" "MP" "MS" "MT" [31] "NC" "ND" "NE" "NH" "NJ" "NM" "NV" "NY" "OH" "OK" "OR" "PA" "PR" "RI" "SC" [46] "SD" "TN" "TX" "UM" "UT" "VA" "VI" "VT" "WA" "WI" "WV" "WY" str_detect(x5,"[[:upper:]]") [1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE [16] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE [31] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE [46] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE Live Demo x6<-c("alabama", "alaska", "american samoa", "arizona", "arkansas", "california", "colorado", "connecticut", "delaware", "district of columbia", "florida", "georgia", "guam", "hawaii", "idaho", "illinois", "indiana", "iowa", "kansas", "kentucky", "louisiana", "maine", "maryland", "massachusetts", "michigan", "minnesota", "minor outlying islands", "mississippi", "missouri", "montana", "nebraska", "nevada", "new hampshire", "new jersey", "new mexico", "new york", "north carolina", "north dakota", "northern mariana islands", "ohio", "oklahoma", "oregon", "pennsylvania", "puerto rico", "rhode island", "south carolina", "south dakota", "tennessee", "texas", "u.s. virgin islands", "utah", "vermont", "virginia", "washington", "west virginia", "wisconsin", "wyoming") x6 [1] "alabama" "alaska" [3] "american samoa" "arizona" [5] "arkansas" "california" [7] "colorado" "connecticut" [9] "delaware" "district of columbia" [11] "florida" "georgia" [13] "guam" "hawaii" [15] "idaho" "illinois" [17] "indiana" "iowa" [19] "kansas" "kentucky" [21] "louisiana" "maine" [23] "maryland" "massachusetts" [25] "michigan" "minnesota" [27] "minor outlying islands" "mississippi" [29] "missouri" "montana" [31] "nebraska" "nevada" [33] "new hampshire" "new jersey" [35] "new mexico" "new york" [37] "north carolina" "north dakota" [39] "northern mariana islands" "ohio" [41] "oklahoma" "oregon" [43] "pennsylvania" "puerto rico" [45] "rhode island" "south carolina" [47] "south dakota" "tennessee" [49] "texas" "u.s. virgin islands" [51] "utah" "vermont" [53] "virginia" "washington" [55] "west virginia" "wisconsin" [57] "wyoming" str_detect(x6,"[[:upper:]]") [1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE [13] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE [25] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE [37] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE [49] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
[ { "code": null, "e": 1483, "s": 1062, "text": "We can use str_detect function to check whether a single string or a vector of strings is in lowercase or uppercase. Along with str_detect function, we need to use either upper or lower to check whether the string is in lowercase or uppercase and the output will be returned in TRUE or FALSE form, if the string will be in lowercase and we pass lower with str_detect function then the output will be TRUE and vice-versa." }, { "code": null, "e": 1494, "s": 1483, "text": " Live Demo" }, { "code": null, "e": 1515, "s": 1494, "text": "x1<-letters[1:26]\nx1" }, { "code": null, "e": 1628, "s": 1515, "text": "[1] \"a\" \"b\" \"c\" \"d\" \"e\" \"f\" \"g\" \"h\" \"i\" \"j\" \"k\" \"l\" \"m\" \"n\" \"o\" \"p\" \"q\" \"r\" \"s\"\n[20] \"t\" \"u\" \"v\" \"w\" \"x\" \"y\" \"z\"" }, { "code": null, "e": 1657, "s": 1628, "text": "str_detect(x1,\"[[:upper:]]\")" }, { "code": null, "e": 1828, "s": 1657, "text": "[1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE\n[13] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE\n[25] FALSE FALSE" }, { "code": null, "e": 1839, "s": 1828, "text": " Live Demo" }, { "code": null, "e": 1860, "s": 1839, "text": "x2<-LETTERS[1:26]\nx2" }, { "code": null, "e": 1973, "s": 1860, "text": "[1] \"A\" \"B\" \"C\" \"D\" \"E\" \"F\" \"G\" \"H\" \"I\" \"J\" \"K\" \"L\" \"M\" \"N\" \"O\" \"P\" \"Q\" \"R\" \"S\"\n[20] \"T\" \"U\" \"V\" \"W\" \"X\" \"Y\" \"Z\"" }, { "code": null, "e": 2002, "s": 1973, "text": "str_detect(x2,\"[[:upper:]]\")" }, { "code": null, "e": 2141, "s": 2002, "text": "[1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE\n[16] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE" }, { "code": null, "e": 2152, "s": 2141, "text": " Live Demo" }, { "code": null, "e": 2167, "s": 2152, "text": "x3<-\"india\"\nx3" }, { "code": null, "e": 2179, "s": 2167, "text": "[1] \"india\"" }, { "code": null, "e": 2208, "s": 2179, "text": "str_detect(x3,\"[[:upper:]]\")" }, { "code": null, "e": 2219, "s": 2208, "text": "[1] FALSE\n" }, { "code": null, "e": 2230, "s": 2219, "text": " Live Demo" }, { "code": null, "e": 2270, "s": 2230, "text": "x4<-c(\"abc\",\"abcd\",\"abcde\",\"bacdef\")\nx4" }, { "code": null, "e": 2304, "s": 2270, "text": "[1] \"abc\" \"abcd\" \"abcde\" \"bacdef\"" }, { "code": null, "e": 2333, "s": 2304, "text": "str_detect(x4,\"[[:upper:]]\")" }, { "code": null, "e": 2362, "s": 2333, "text": "[1] FALSE FALSE FALSE FALSE\n" }, { "code": null, "e": 2373, "s": 2362, "text": " Live Demo" }, { "code": null, "e": 2724, "s": 2373, "text": "x5<-c(\"AK\", \"AL\", \"AR\", \"AS\", \"AZ\", \"CA\", \"CO\", \"CT\", \"DC\", \"DE\", \"FL\", \"GA\", \"GU\", \"HI\", \"IA\", \"ID\", \"IL\", \"IN\", \"KS\", \"KY\", \"LA\", \"MA\", \"MD\", \"ME\", \"MI\", \"MN\", \"MO\", \"MP\", \"MS\", \"MT\", \"NC\", \"ND\", \"NE\", \"NH\", \"NJ\", \"NM\", \"NV\", \"NY\", \"OH\", \"OK\", \"OR\", \"PA\", \"PR\", \"RI\", \"SC\", \"SD\", \"TN\", \"TX\", \"UM\", \"UT\", \"VA\", \"VI\", \"VT\", \"WA\", \"WI\", \"WV\", \"WY\")\nx5" }, { "code": null, "e": 3028, "s": 2724, "text": "[1] \"AK\" \"AL\" \"AR\" \"AS\" \"AZ\" \"CA\" \"CO\" \"CT\" \"DC\" \"DE\" \"FL\" \"GA\" \"GU\" \"HI\" \"IA\"\n[16] \"ID\" \"IL\" \"IN\" \"KS\" \"KY\" \"LA\" \"MA\" \"MD\" \"ME\" \"MI\" \"MN\" \"MO\" \"MP\" \"MS\" \"MT\"\n[31] \"NC\" \"ND\" \"NE\" \"NH\" \"NJ\" \"NM\" \"NV\" \"NY\" \"OH\" \"OK\" \"OR\" \"PA\" \"PR\" \"RI\" \"SC\"\n[46] \"SD\" \"TN\" \"TX\" \"UM\" \"UT\" \"VA\" \"VI\" \"VT\" \"WA\" \"WI\" \"WV\" \"WY\"" }, { "code": null, "e": 3057, "s": 3028, "text": "str_detect(x5,\"[[:upper:]]\")" }, { "code": null, "e": 3361, "s": 3057, "text": "[1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE\n[16] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE\n[31] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE\n[46] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE" }, { "code": null, "e": 3372, "s": 3361, "text": " Live Demo" }, { "code": null, "e": 4145, "s": 3372, "text": "x6<-c(\"alabama\", \"alaska\", \"american samoa\", \"arizona\", \"arkansas\", \"california\", \"colorado\", \"connecticut\", \"delaware\", \"district of columbia\", \"florida\", \"georgia\", \"guam\", \"hawaii\", \"idaho\", \"illinois\", \"indiana\", \"iowa\", \"kansas\", \"kentucky\", \"louisiana\", \"maine\", \"maryland\", \"massachusetts\", \"michigan\", \"minnesota\", \"minor outlying islands\", \"mississippi\", \"missouri\", \"montana\", \"nebraska\", \"nevada\", \"new hampshire\", \"new jersey\", \"new mexico\", \"new york\", \"north carolina\", \"north dakota\", \"northern mariana islands\", \"ohio\", \"oklahoma\", \"oregon\", \"pennsylvania\", \"puerto rico\", \"rhode island\", \"south carolina\", \"south dakota\", \"tennessee\", \"texas\", \"u.s. virgin islands\", \"utah\", \"vermont\", \"virginia\", \"washington\", \"west virginia\", \"wisconsin\", \"wyoming\")\nx6" }, { "code": null, "e": 4992, "s": 4145, "text": "[1] \"alabama\" \"alaska\"\n[3] \"american samoa\" \"arizona\"\n[5] \"arkansas\" \"california\"\n[7] \"colorado\" \"connecticut\"\n[9] \"delaware\" \"district of columbia\"\n[11] \"florida\" \"georgia\"\n[13] \"guam\" \"hawaii\"\n[15] \"idaho\" \"illinois\"\n[17] \"indiana\" \"iowa\"\n[19] \"kansas\" \"kentucky\"\n[21] \"louisiana\" \"maine\"\n[23] \"maryland\" \"massachusetts\"\n[25] \"michigan\" \"minnesota\"\n[27] \"minor outlying islands\" \"mississippi\"\n[29] \"missouri\" \"montana\"\n[31] \"nebraska\" \"nevada\"\n[33] \"new hampshire\" \"new jersey\"\n[35] \"new mexico\" \"new york\"\n[37] \"north carolina\" \"north dakota\"\n[39] \"northern mariana islands\" \"ohio\"\n[41] \"oklahoma\" \"oregon\"\n[43] \"pennsylvania\" \"puerto rico\"\n[45] \"rhode island\" \"south carolina\"\n[47] \"south dakota\" \"tennessee\"\n[49] \"texas\" \"u.s. virgin islands\"\n[51] \"utah\" \"vermont\"\n[53] \"virginia\" \"washington\"\n[55] \"west virginia\" \"wisconsin\"\n[57] \"wyoming\"" }, { "code": null, "e": 5021, "s": 4992, "text": "str_detect(x6,\"[[:upper:]]\")" }, { "code": null, "e": 5387, "s": 5021, "text": "[1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE\n[13] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE\n[25] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE\n[37] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE\n[49] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE" } ]
Improve Docker performances with WSL2 | Towards Data Science
Docker was claimed as the leading solution for setting up a local development environment. Thanks to the simplicity of docker-compose files, you can have an isolated environment per project, that reflect the same configuration of the production environment. Moreover, this solution makes the development independent by the operative system you have. In poo word, even if your container will be a Linux image, you can develop by using Windows or Mac. Anyway, in some setup the performance may decrease, compromising the productivity. Form last Docker update, Docker engineers added the possibility to use WSL2 technology for boosting performances, giving same development experience on all platform, windows included. This article explains why we may have performance issues on Windows, and how to install WSL2 properly for improving performances. Docker is the leading container solution, active since 2013. I don't want to spend a lot of time talking about what docker is. If you are here, probably already use it, so I will spend just a few words for introducing the limitation that WSL2 overcome. Anyway, if you want to know more about docker, you can read this article where I tried to explain in simple words“what is exactly docker”. The central part to remark about Docker is how it works under windows. Because it shares the OS, not the hardware, you couldn’t have any Linux based containers on Windows. That is. But everybody uses Linux containers on windows, how it is possible? Docker engineers solved this problem with a trick. We cannot have a Linux container on Windows, but we can put Linux in windows machine by using a hypervisor. So the solution was quickly coined. Docker Desktop for windows use a Hypervisor (usually Microsoft HyperV) for running a virtual machine, and it shares the VM OS to the docker container. That’s how things work, and I tried to explain it using a diagram. The big problems with this architecture are: the resource limitation. While docker is designed for sharing OS, a hypervisor still use hardware, and you need to allocate resources to it. This lead to the same performance issues we had using virtual machines. Disk overhead. The container image is inside the VM, it stores files in volumes, but you may want to share folders from the Windows environment, especially when developing. This is the red-arrow roundtrip in the diagram and its impact performances. As Docker on Windows for running Linux container if used mostly in a development environment, performance doesn't matter a lot. In fact, most of the solution requires low resource for handling one request at a time. Anyway, there are some cases when this performance matters. Platform with an application states, where the executable is compiled and loaded once, doesn't offer too much about disk latency. Developing in .net or java, you just have to press the play button, wait a minute, and then you have your application ready for tests, where all the compiled source code is more or less in RAM, and you don't need to stress the hard drive. Instead, for PHP or Python application, it’s different. As they haven’t any application state, each request is interpreted independently, so you need to scan and load all the files required each time. This means a lot of file read, so your latency is multiplied with an immense amount of file. For this system, using volume mapping on windows is quite expensive and decrease performance. You could use volume mounted to the Linux OS, but in this case, you will have trouble on editing from the Windows UI. That’s why, in most cases, we accepted the slowest performance (in most cases acceptable for a dev environment), or in other cases we were forced to switch to Linux, nullifying the advantages of using Docker for having multi-OS availability. WSL (Windows Subsystem for Linux) is a compatibility layer for running Linux binary executables natively on Windows. It works since Windows 10 and let you use Linux inside Windows without using virtual machines. Since June 2019, an enhancement of WSL (WSL 2) was delivered with Windows 10. This update brings a lot of performance improvement through a set of optimised Hyper-V features. In simple words, you have now a Linux distribution inside your Windows machine faster than running virtual machines. The good news is that Docker Desktop supports it and it can boost your containers. Using WLS2 and Docker combines, we virtually skip one step. The Windows and Linux file system are mutually shared: you can see Linux from windows accessing the shared drive \\WSL$\ or by Linux you can see Windows from /mtn/c) The docker containers use the Linux WSL without any resource limitation and have better performance. In this scenario, there is huge bad news. Sharing windows folder is still possible, but with worst performance than in the standard case. This is not a problem in Java or .net, or a tolerable problem, but made the PHP development unfeasible. Fortunately, there is a solution that mixes the benefit of using WSL2 and a great development experience. In fact, Visual Studio Code is able to work remotely to the WSL2 subsystem so that you can do the following: Keep the volumes inside WSL2 as regular volume mount, so get the best performance for file system access. Work from Windows, as usual, editing the code on Linux. It’s clear that if you will pay a more significant cost for accessing the file while you double click an item in your IDE or save it, it is a very acceptable solution. The problem comes with massive file load, and this is not the case of a developer that writes code working on a dozen of time simultaneously. Anyway, Visual Studio does somethings better. It has an extension that can interact remotely with their remote subsystem, so you can keep the UI into Windows, but use the engine from an instance inside Linux. So, also, your user experience as a developer is safe. Well, once we have understood how and why we can boost performance on Docker, we just need to follow some easy step for getting things done. We will need to perform a couple of steps, but, from a higher point of view, we have to: Enable the WSL2 environmentConfigure the IDE and start coding. Enable the WSL2 environment Configure the IDE and start coding. This section explains how to install the WSL2 version an be ready for starting coding with Docker and WSL2. This first step enables the Window subsystem. You have to run it on a command line with administrative rights. dism.exe /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart This second command activates the Virtual Machine Platform (yes, WSL still uses hyper-v behind the hood). If your PC doesn’t have the virtualisation feature turned on, you may need to set it from the BIOS. dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart After this second step, a reboot is welcome. The last step for installing and configuring WSL2 is to install the update. It is a simple MSI package, so you can download it and install with a double click. The file is hosted here from Microsoft. Once we are ok with WSL2, just set up version 2 as default for all the subsystem. wsl --set-default-version 2 To run Docker over a subsystem, we need to download a Linux distro. Since Microsoft + Open Source is now a reality, it is possible directly from the Microsoft store. I used Ubunto, and it is just 440MB, so don’t worry about finish your disk space. After this step, you will see all the OS installed as a subsystem. wsl --list --verbose You should see docker, docker-data, ubuntu, all on WSL 2. Inside Docker Desktop, just check the configuration and enable the WSL2 feature. It may need some docker restart or PC restart. Warning: When you switch from standard mode to WSL2, you will need to redownload all the images (that you have located inside the Hyper-v VM instead of WSL2). Moreover, the data inside the named volumes are stored inside the VM, so you won't find them in the new WSL2 machines. So, first of all, extract and backup all relevant data from the Docker container. Basing on your local setup, you may lose data. This first step is to check “Use the WSL2 based engine”. Then you unlock the WSL integration panel, where you can activate Ubuntu distro. The last step is to install and download the Visual Studio Plugin. As usual, you can do it by clicking install from the web site or by the Visual Studio Code UI. You can also find the extension here. At that time, all the steps are completed, and you can start coding. You will thank this time spent when you will see the performance! The final balance will be a lot of time saved just on the first day of work. For start coding, you have two options: starting from the WSL or from Windwsow. Personally, I prefer the second one as it is very self-contained. 1. Open WSL terminal or enter the command “WSL” into a shell. As Ubunto is the preferred subsystem, you will be inside it. 2. Type “code .” This will open Visual Studio Code on your windows machine. 1. Open visual studio code. 2. Click the WSL box (left bottom corner, the green button into the bottom toolbar) or F1 + Remore WLS+ New Window 3. the new window is connected with the Linux OS Since that moment you can use Visual Studio Code to do all you need. In fact, you can open a terminal from the file tree. The terminal will be inside the WSL machine, and if you run docker-compose up, you will activate containers on the host docker system. You can also use the git tools for handling commits, so probably that’s all you need to start coding. For many reasons, a lot of developers are using Windows as the development environment. This is a common choice for having best programs compatibility or a better user experience that Linux. Other are using Windows for getting cheaper notebook than Mackbook. Docker helped for having the same development experience on all the OS system, but in some case may lead to performance issues on Windows. WSL2 improve performance but need some attention about where to put the file and how to create volumes. Once these steps are done, you can benefit from the same performance you had in Linux, but with your comfortable Windows user experience. Disclaimer: I don’t want to animate the sectionalism between Linux, Windows and Mac supporters. Each developer should be free to choose the OS that prefers, having the same user experience. This is not the main purpose of Docker but is a comfortable side effect. The purpose of this article is just to unlock a new opportunity and avoid a forced OS change for who prefer working on Windows. 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. daniele-fontani.medium.com References: Official docker guide for using docker with WSL2 Visual Studio Code remote development architecture
[ { "code": null, "e": 430, "s": 172, "text": "Docker was claimed as the leading solution for setting up a local development environment. Thanks to the simplicity of docker-compose files, you can have an isolated environment per project, that reflect the same configuration of the production environment." }, { "code": null, "e": 622, "s": 430, "text": "Moreover, this solution makes the development independent by the operative system you have. In poo word, even if your container will be a Linux image, you can develop by using Windows or Mac." }, { "code": null, "e": 705, "s": 622, "text": "Anyway, in some setup the performance may decrease, compromising the productivity." }, { "code": null, "e": 889, "s": 705, "text": "Form last Docker update, Docker engineers added the possibility to use WSL2 technology for boosting performances, giving same development experience on all platform, windows included." }, { "code": null, "e": 1019, "s": 889, "text": "This article explains why we may have performance issues on Windows, and how to install WSL2 properly for improving performances." }, { "code": null, "e": 1411, "s": 1019, "text": "Docker is the leading container solution, active since 2013. I don't want to spend a lot of time talking about what docker is. If you are here, probably already use it, so I will spend just a few words for introducing the limitation that WSL2 overcome. Anyway, if you want to know more about docker, you can read this article where I tried to explain in simple words“what is exactly docker”." }, { "code": null, "e": 2073, "s": 1411, "text": "The central part to remark about Docker is how it works under windows. Because it shares the OS, not the hardware, you couldn’t have any Linux based containers on Windows. That is. But everybody uses Linux containers on windows, how it is possible? Docker engineers solved this problem with a trick. We cannot have a Linux container on Windows, but we can put Linux in windows machine by using a hypervisor. So the solution was quickly coined. Docker Desktop for windows use a Hypervisor (usually Microsoft HyperV) for running a virtual machine, and it shares the VM OS to the docker container. That’s how things work, and I tried to explain it using a diagram." }, { "code": null, "e": 2118, "s": 2073, "text": "The big problems with this architecture are:" }, { "code": null, "e": 2331, "s": 2118, "text": "the resource limitation. While docker is designed for sharing OS, a hypervisor still use hardware, and you need to allocate resources to it. This lead to the same performance issues we had using virtual machines." }, { "code": null, "e": 2580, "s": 2331, "text": "Disk overhead. The container image is inside the VM, it stores files in volumes, but you may want to share folders from the Windows environment, especially when developing. This is the red-arrow roundtrip in the diagram and its impact performances." }, { "code": null, "e": 2856, "s": 2580, "text": "As Docker on Windows for running Linux container if used mostly in a development environment, performance doesn't matter a lot. In fact, most of the solution requires low resource for handling one request at a time. Anyway, there are some cases when this performance matters." }, { "code": null, "e": 3225, "s": 2856, "text": "Platform with an application states, where the executable is compiled and loaded once, doesn't offer too much about disk latency. Developing in .net or java, you just have to press the play button, wait a minute, and then you have your application ready for tests, where all the compiled source code is more or less in RAM, and you don't need to stress the hard drive." }, { "code": null, "e": 3519, "s": 3225, "text": "Instead, for PHP or Python application, it’s different. As they haven’t any application state, each request is interpreted independently, so you need to scan and load all the files required each time. This means a lot of file read, so your latency is multiplied with an immense amount of file." }, { "code": null, "e": 3731, "s": 3519, "text": "For this system, using volume mapping on windows is quite expensive and decrease performance. You could use volume mounted to the Linux OS, but in this case, you will have trouble on editing from the Windows UI." }, { "code": null, "e": 3973, "s": 3731, "text": "That’s why, in most cases, we accepted the slowest performance (in most cases acceptable for a dev environment), or in other cases we were forced to switch to Linux, nullifying the advantages of using Docker for having multi-OS availability." }, { "code": null, "e": 4360, "s": 3973, "text": "WSL (Windows Subsystem for Linux) is a compatibility layer for running Linux binary executables natively on Windows. It works since Windows 10 and let you use Linux inside Windows without using virtual machines. Since June 2019, an enhancement of WSL (WSL 2) was delivered with Windows 10. This update brings a lot of performance improvement through a set of optimised Hyper-V features." }, { "code": null, "e": 4477, "s": 4360, "text": "In simple words, you have now a Linux distribution inside your Windows machine faster than running virtual machines." }, { "code": null, "e": 4560, "s": 4477, "text": "The good news is that Docker Desktop supports it and it can boost your containers." }, { "code": null, "e": 4620, "s": 4560, "text": "Using WLS2 and Docker combines, we virtually skip one step." }, { "code": null, "e": 4786, "s": 4620, "text": "The Windows and Linux file system are mutually shared: you can see Linux from windows accessing the shared drive \\\\WSL$\\ or by Linux you can see Windows from /mtn/c)" }, { "code": null, "e": 4887, "s": 4786, "text": "The docker containers use the Linux WSL without any resource limitation and have better performance." }, { "code": null, "e": 5129, "s": 4887, "text": "In this scenario, there is huge bad news. Sharing windows folder is still possible, but with worst performance than in the standard case. This is not a problem in Java or .net, or a tolerable problem, but made the PHP development unfeasible." }, { "code": null, "e": 5344, "s": 5129, "text": "Fortunately, there is a solution that mixes the benefit of using WSL2 and a great development experience. In fact, Visual Studio Code is able to work remotely to the WSL2 subsystem so that you can do the following:" }, { "code": null, "e": 5450, "s": 5344, "text": "Keep the volumes inside WSL2 as regular volume mount, so get the best performance for file system access." }, { "code": null, "e": 5506, "s": 5450, "text": "Work from Windows, as usual, editing the code on Linux." }, { "code": null, "e": 5816, "s": 5506, "text": "It’s clear that if you will pay a more significant cost for accessing the file while you double click an item in your IDE or save it, it is a very acceptable solution. The problem comes with massive file load, and this is not the case of a developer that writes code working on a dozen of time simultaneously." }, { "code": null, "e": 6080, "s": 5816, "text": "Anyway, Visual Studio does somethings better. It has an extension that can interact remotely with their remote subsystem, so you can keep the UI into Windows, but use the engine from an instance inside Linux. So, also, your user experience as a developer is safe." }, { "code": null, "e": 6221, "s": 6080, "text": "Well, once we have understood how and why we can boost performance on Docker, we just need to follow some easy step for getting things done." }, { "code": null, "e": 6310, "s": 6221, "text": "We will need to perform a couple of steps, but, from a higher point of view, we have to:" }, { "code": null, "e": 6373, "s": 6310, "text": "Enable the WSL2 environmentConfigure the IDE and start coding." }, { "code": null, "e": 6401, "s": 6373, "text": "Enable the WSL2 environment" }, { "code": null, "e": 6437, "s": 6401, "text": "Configure the IDE and start coding." }, { "code": null, "e": 6545, "s": 6437, "text": "This section explains how to install the WSL2 version an be ready for starting coding with Docker and WSL2." }, { "code": null, "e": 6656, "s": 6545, "text": "This first step enables the Window subsystem. You have to run it on a command line with administrative rights." }, { "code": null, "e": 6752, "s": 6656, "text": "dism.exe /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart" }, { "code": null, "e": 6958, "s": 6752, "text": "This second command activates the Virtual Machine Platform (yes, WSL still uses hyper-v behind the hood). If your PC doesn’t have the virtualisation feature turned on, you may need to set it from the BIOS." }, { "code": null, "e": 7043, "s": 6958, "text": "dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart" }, { "code": null, "e": 7088, "s": 7043, "text": "After this second step, a reboot is welcome." }, { "code": null, "e": 7248, "s": 7088, "text": "The last step for installing and configuring WSL2 is to install the update. It is a simple MSI package, so you can download it and install with a double click." }, { "code": null, "e": 7288, "s": 7248, "text": "The file is hosted here from Microsoft." }, { "code": null, "e": 7370, "s": 7288, "text": "Once we are ok with WSL2, just set up version 2 as default for all the subsystem." }, { "code": null, "e": 7398, "s": 7370, "text": "wsl --set-default-version 2" }, { "code": null, "e": 7646, "s": 7398, "text": "To run Docker over a subsystem, we need to download a Linux distro. Since Microsoft + Open Source is now a reality, it is possible directly from the Microsoft store. I used Ubunto, and it is just 440MB, so don’t worry about finish your disk space." }, { "code": null, "e": 7713, "s": 7646, "text": "After this step, you will see all the OS installed as a subsystem." }, { "code": null, "e": 7734, "s": 7713, "text": "wsl --list --verbose" }, { "code": null, "e": 7792, "s": 7734, "text": "You should see docker, docker-data, ubuntu, all on WSL 2." }, { "code": null, "e": 7920, "s": 7792, "text": "Inside Docker Desktop, just check the configuration and enable the WSL2 feature. It may need some docker restart or PC restart." }, { "code": null, "e": 8327, "s": 7920, "text": "Warning: When you switch from standard mode to WSL2, you will need to redownload all the images (that you have located inside the Hyper-v VM instead of WSL2). Moreover, the data inside the named volumes are stored inside the VM, so you won't find them in the new WSL2 machines. So, first of all, extract and backup all relevant data from the Docker container. Basing on your local setup, you may lose data." }, { "code": null, "e": 8384, "s": 8327, "text": "This first step is to check “Use the WSL2 based engine”." }, { "code": null, "e": 8465, "s": 8384, "text": "Then you unlock the WSL integration panel, where you can activate Ubuntu distro." }, { "code": null, "e": 8627, "s": 8465, "text": "The last step is to install and download the Visual Studio Plugin. As usual, you can do it by clicking install from the web site or by the Visual Studio Code UI." }, { "code": null, "e": 8665, "s": 8627, "text": "You can also find the extension here." }, { "code": null, "e": 8877, "s": 8665, "text": "At that time, all the steps are completed, and you can start coding. You will thank this time spent when you will see the performance! The final balance will be a lot of time saved just on the first day of work." }, { "code": null, "e": 8957, "s": 8877, "text": "For start coding, you have two options: starting from the WSL or from Windwsow." }, { "code": null, "e": 9023, "s": 8957, "text": "Personally, I prefer the second one as it is very self-contained." }, { "code": null, "e": 9146, "s": 9023, "text": "1. Open WSL terminal or enter the command “WSL” into a shell. As Ubunto is the preferred subsystem, you will be inside it." }, { "code": null, "e": 9222, "s": 9146, "text": "2. Type “code .” This will open Visual Studio Code on your windows machine." }, { "code": null, "e": 9250, "s": 9222, "text": "1. Open visual studio code." }, { "code": null, "e": 9365, "s": 9250, "text": "2. Click the WSL box (left bottom corner, the green button into the bottom toolbar) or F1 + Remore WLS+ New Window" }, { "code": null, "e": 9414, "s": 9365, "text": "3. the new window is connected with the Linux OS" }, { "code": null, "e": 9773, "s": 9414, "text": "Since that moment you can use Visual Studio Code to do all you need. In fact, you can open a terminal from the file tree. The terminal will be inside the WSL machine, and if you run docker-compose up, you will activate containers on the host docker system. You can also use the git tools for handling commits, so probably that’s all you need to start coding." }, { "code": null, "e": 10032, "s": 9773, "text": "For many reasons, a lot of developers are using Windows as the development environment. This is a common choice for having best programs compatibility or a better user experience that Linux. Other are using Windows for getting cheaper notebook than Mackbook." }, { "code": null, "e": 10171, "s": 10032, "text": "Docker helped for having the same development experience on all the OS system, but in some case may lead to performance issues on Windows." }, { "code": null, "e": 10275, "s": 10171, "text": "WSL2 improve performance but need some attention about where to put the file and how to create volumes." }, { "code": null, "e": 10413, "s": 10275, "text": "Once these steps are done, you can benefit from the same performance you had in Linux, but with your comfortable Windows user experience." }, { "code": null, "e": 10804, "s": 10413, "text": "Disclaimer: I don’t want to animate the sectionalism between Linux, Windows and Mac supporters. Each developer should be free to choose the OS that prefers, having the same user experience. This is not the main purpose of Docker but is a comfortable side effect. The purpose of this article is just to unlock a new opportunity and avoid a forced OS change for who prefer working on Windows." }, { "code": null, "e": 10987, "s": 10804, "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": 11014, "s": 10987, "text": "daniele-fontani.medium.com" }, { "code": null, "e": 11026, "s": 11014, "text": "References:" }, { "code": null, "e": 11075, "s": 11026, "text": "Official docker guide for using docker with WSL2" } ]
Convert.ToDateTime(String, IFormatProvider) Method in C#
The Convert.ToDateTime() method in C# converts the specified string representation of a number to an equivalent date and time, using the specified culture-specific formatting information. Following is the syntax − public static DateTime ToDateTime (string val, IFormatProvider provider); Above, value is a string that contains a date and time to convert, whereas the provider is an object that supplies culture-specific formatting information. Let us now see an example to implement the Convert.ToDateTime() method − using System; using System.Globalization; public class Demo { public static void Main(){ CultureInfo cultures = new CultureInfo("en-US"); String val = "11/11/2019"; Console.WriteLine("Converted DateTime value..."); DateTime res = Convert.ToDateTime(val, cultures); Console.Write("{0}", res); } } This will produce the following output − Converted DateTime value... 11/11/2019 12:00:00 AM
[ { "code": null, "e": 1250, "s": 1062, "text": "The Convert.ToDateTime() method in C# converts the specified string representation of a number to an equivalent date and time, using the specified culture-specific formatting information." }, { "code": null, "e": 1276, "s": 1250, "text": "Following is the syntax −" }, { "code": null, "e": 1350, "s": 1276, "text": "public static DateTime ToDateTime (string val, IFormatProvider provider);" }, { "code": null, "e": 1506, "s": 1350, "text": "Above, value is a string that contains a date and time to convert, whereas the provider is an object that supplies culture-specific formatting information." }, { "code": null, "e": 1579, "s": 1506, "text": "Let us now see an example to implement the Convert.ToDateTime() method −" }, { "code": null, "e": 1911, "s": 1579, "text": "using System;\nusing System.Globalization;\npublic class Demo {\n public static void Main(){\n CultureInfo cultures = new CultureInfo(\"en-US\");\n String val = \"11/11/2019\";\n Console.WriteLine(\"Converted DateTime value...\");\n DateTime res = Convert.ToDateTime(val, cultures);\n Console.Write(\"{0}\", res);\n }\n}" }, { "code": null, "e": 1952, "s": 1911, "text": "This will produce the following output −" }, { "code": null, "e": 2003, "s": 1952, "text": "Converted DateTime value...\n11/11/2019 12:00:00 AM" } ]
How to align two divs horizontally in HTML?
To align two divs horizontally in HTML, use the float CSS property with left value. You can try to run the following code to learn how to align divs horizontally − Live Demo <!DOCTYPE html> <html> <head> <style> .demo div { float: left; clear: none; } </style> </head> <body> <div class="demo"> <div> <span>div1</span> <select size="5"> <option value="c1">India</option> <option value="c2">US</option> <option value="c3">UK</option> <option value="c4">Australia</option> </select> </div> <div> <span>div2</span> <select size="5"> <option value="r1">1</option> <option value="r2">2</option> <option value="r3">3</option> <option value="r4">4</option> </select> </div> </div> </body> </html>
[ { "code": null, "e": 1226, "s": 1062, "text": "To align two divs horizontally in HTML, use the float CSS property with left value. You can try to run the following code to learn how to align divs horizontally −" }, { "code": null, "e": 1236, "s": 1226, "text": "Live Demo" }, { "code": null, "e": 1913, "s": 1236, "text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\n.demo div {\n float: left;\n clear: none;\n}\n</style>\n</head>\n<body>\n<div class=\"demo\">\n <div>\n <span>div1</span>\n <select size=\"5\">\n <option value=\"c1\">India</option>\n <option value=\"c2\">US</option>\n <option value=\"c3\">UK</option>\n <option value=\"c4\">Australia</option>\n </select>\n </div>\n <div>\n <span>div2</span>\n <select size=\"5\">\n <option value=\"r1\">1</option>\n <option value=\"r2\">2</option>\n <option value=\"r3\">3</option>\n <option value=\"r4\">4</option>\n </select>\n </div>\n</div>\n</body>\n</html>" } ]
Flask Simple HTML Templates Example - onlinetutorialspoint
PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC EXCEPTIONS COLLECTIONS SWING JDBC JAVA 8 SPRING SPRING BOOT HIBERNATE PYTHON PHP JQUERY PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws In this tutorial, we are going to see the Flask simple HTML Templates, this is going to be something the extension work of the previous HelloWorld example. In the previous example, we return the Hello, World! string message from the server, but in reality, the server sends an HTML response to a web browser. So as part of this tutorial, I am going to return the HTML response from the Flask server. Python 3.8.5 Flask 2.0.1 Mac OS X My current application structure (venv) flask-templates % . ├── app │ ├── __init__.py │ └── routes.py └── helloworld.py You might have noticed that I just copied our Hello World application 🙂 and building some interesting webpage. implement routes.py from app import app @app.route('/') def index(): return """ <html> <head> <title>Colorful Hello, World!</title> </head> <body> <h1 style="color:#093657"> Hello, World!</h1> </body> </html> """ This is a very basic HTML page with a head and body section, inside there is a title that will appear on the browser tab and in the body, I show the content with color code. I left the remaining files as it is. __init__.py from flask import Flask app = Flask(__name__) from app import routes helloworld.py from app import app Make sure you have to set the FLASK_APP=helloworld.py environment variable. Now let’s some more extend this application by appending the user name. In this case, I am creating a fake user with a python dictionary but in reality, it’s going to be a real user that’s being populated from the database or somewhere else. from app import app @app.route('/') def index(): user = { 'name':'Chandra' } return ''' <html> <head> <title>Colorful Hello, World!</title> </head> <body> <h1 style="color:#093657"> Hello, World! '''+user['name']+'''</h1> </body> </html> ''' Output: So far so good, but think about a little bit more, that this is one of the simplest pages that we build so far and yet we already have a little bit of complication in the way that we present a variable component user['name']inside the page. If we continue to extend this page it’s going to become very difficult to maintain and the problem is going to even worse when we start adding more pages. The big problem here is that we are mixing code with HTML and that’s really a disaster, so with this, we clearly say it is not a good practice. Surely the accepted good practice is to separate the application logic from presentation. So what I am going to do now is; I’ll move the HTML into a separate file, so that’s where the templates come into place. By default, Falsk is going to look the templates into the directory named templates so hence I am going to create a directory called templates inside the application folder that is app Updated project strucure: (venv) flask-templates % . ├── app │ ├── __init__.py │ ├── routes.py │ └── templates │ └── index.html └── helloworld.py Create index.html <html> <head> <title>Colorful Hello, World!</title> </head> <body> <h1 style="color:#093657"> Hello, Template! {{user.name}}</h1> </body> </html> On the above for the user.name I have to enclose this with double curly braces like this {{user.name}} we can call it as template placeholders. At the time we produce a response from a browser, we are going to replace that with actual values it’s going to come from a user object. update routes.py In routes.py remove the static HTML content and instead call render_template() function that comes with Flask. from app import app from flask import render_template @app.route('/') def index(): user = { 'name':'Chandra' } return render_template('index.html', user = user) Make sure we have to pass the template name and user object as parameters for render_template() function. Let’s run again Install Flask Flask Hello World Example Flask Templates Happy Learning 🙂 Flask – Jinja Templates Example Hello World Flask Example Python – How to install the Flask framework? Rendering Static HTML page using Django Angularjs Services Example Tutorials Simple Spring Boot Example AngularJs Directive Example Tutorials Angularjs Custom Filter Example Using Array in AngularJs Example Python – AWS SAM Lambda Example AngularJs Orderby Filter Example Python Django Helloworld Example Java Swing JOptionPane Html Content Example Steps to Create AngularJs Controller Step by Step Tutorials AngularJs Example Flask – Jinja Templates Example Hello World Flask Example Python – How to install the Flask framework? Rendering Static HTML page using Django Angularjs Services Example Tutorials Simple Spring Boot Example AngularJs Directive Example Tutorials Angularjs Custom Filter Example Using Array in AngularJs Example Python – AWS SAM Lambda Example AngularJs Orderby Filter Example Python Django Helloworld Example Java Swing JOptionPane Html Content Example Steps to Create AngularJs Controller Step by Step Tutorials AngularJs Example
[ { "code": null, "e": 158, "s": 123, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 172, "s": 158, "text": "Java Examples" }, { "code": null, "e": 183, "s": 172, "text": "C Examples" }, { "code": null, "e": 195, "s": 183, "text": "C Tutorials" }, { "code": null, "e": 199, "s": 195, "text": "aws" }, { "code": null, "e": 234, "s": 199, "text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC" }, { "code": null, "e": 245, "s": 234, "text": "EXCEPTIONS" }, { "code": null, "e": 257, "s": 245, "text": "COLLECTIONS" }, { "code": null, "e": 263, "s": 257, "text": "SWING" }, { "code": null, "e": 268, "s": 263, "text": "JDBC" }, { "code": null, "e": 275, "s": 268, "text": "JAVA 8" }, { "code": null, "e": 282, "s": 275, "text": "SPRING" }, { "code": null, "e": 294, "s": 282, "text": "SPRING BOOT" }, { "code": null, "e": 304, "s": 294, "text": "HIBERNATE" }, { "code": null, "e": 311, "s": 304, "text": "PYTHON" }, { "code": null, "e": 315, "s": 311, "text": "PHP" }, { "code": null, "e": 322, "s": 315, "text": "JQUERY" }, { "code": null, "e": 357, "s": 322, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 371, "s": 357, "text": "Java Examples" }, { "code": null, "e": 382, "s": 371, "text": "C Examples" }, { "code": null, "e": 394, "s": 382, "text": "C Tutorials" }, { "code": null, "e": 398, "s": 394, "text": "aws" }, { "code": null, "e": 554, "s": 398, "text": "In this tutorial, we are going to see the Flask simple HTML Templates, this is going to be something the extension work of the previous HelloWorld example." }, { "code": null, "e": 798, "s": 554, "text": "In the previous example, we return the Hello, World! string message from the server, but in reality, the server sends an HTML response to a web browser. So as part of this tutorial, I am going to return the HTML response from the Flask server." }, { "code": null, "e": 811, "s": 798, "text": "Python 3.8.5" }, { "code": null, "e": 823, "s": 811, "text": "Flask 2.0.1" }, { "code": null, "e": 832, "s": 823, "text": "Mac OS X" }, { "code": null, "e": 865, "s": 832, "text": "My current application structure" }, { "code": null, "e": 957, "s": 865, "text": "(venv) flask-templates %\n.\n├── app\n│ ├── __init__.py\n│ └── routes.py\n└── helloworld.py\n" }, { "code": null, "e": 1068, "s": 957, "text": "You might have noticed that I just copied our Hello World application 🙂 and building some interesting webpage." }, { "code": null, "e": 1088, "s": 1068, "text": "implement routes.py" }, { "code": null, "e": 1323, "s": 1088, "text": "from app import app\n\n@app.route('/')\ndef index():\n return \"\"\"\n <html>\n <head>\n <title>Colorful Hello, World!</title>\n </head>\n <body>\n <h1 style=\"color:#093657\"> Hello, World!</h1>\n </body>\n </html>\n \"\"\"\n" }, { "code": null, "e": 1534, "s": 1323, "text": "This is a very basic HTML page with a head and body section, inside there is a title that will appear on the browser tab and in the body, I show the content with color code. I left the remaining files as it is." }, { "code": null, "e": 1546, "s": 1534, "text": "__init__.py" }, { "code": null, "e": 1618, "s": 1546, "text": "from flask import Flask\n\napp = Flask(__name__)\n\nfrom app import routes\n" }, { "code": null, "e": 1632, "s": 1618, "text": "helloworld.py" }, { "code": null, "e": 1652, "s": 1632, "text": "from app import app" }, { "code": null, "e": 1728, "s": 1652, "text": "Make sure you have to set the FLASK_APP=helloworld.py environment variable." }, { "code": null, "e": 1970, "s": 1728, "text": "Now let’s some more extend this application by appending the user name. In this case, I am creating a fake user with a python dictionary but in reality, it’s going to be a real user that’s being populated from the database or somewhere else." }, { "code": null, "e": 2270, "s": 1970, "text": "from app import app\n\n@app.route('/')\ndef index():\n user = {\n 'name':'Chandra'\n }\n return '''\n <html>\n <head>\n <title>Colorful Hello, World!</title>\n </head>\n <body>\n <h1 style=\"color:#093657\"> Hello, World! '''+user['name']+'''</h1>\n </body>\n </html>\n '''\n" }, { "code": null, "e": 2278, "s": 2270, "text": "Output:" }, { "code": null, "e": 2674, "s": 2278, "text": "So far so good, but think about a little bit more, that this is one of the simplest pages that we build so far and yet we already have a little bit of complication in the way that we present a variable component user['name']inside the page. If we continue to extend this page it’s going to become very difficult to maintain and the problem is going to even worse when we start adding more pages." }, { "code": null, "e": 2818, "s": 2674, "text": "The big problem here is that we are mixing code with HTML and that’s really a disaster, so with this, we clearly say it is not a good practice." }, { "code": null, "e": 3029, "s": 2818, "text": "Surely the accepted good practice is to separate the application logic from presentation. So what I am going to do now is; I’ll move the HTML into a separate file, so that’s where the templates come into place." }, { "code": null, "e": 3214, "s": 3029, "text": "By default, Falsk is going to look the templates into the directory named templates so hence I am going to create a directory called templates inside the application folder that is app" }, { "code": null, "e": 3240, "s": 3214, "text": "Updated project strucure:" }, { "code": null, "e": 3373, "s": 3240, "text": "(venv) flask-templates %\n.\n├── app\n│ ├── __init__.py\n│ ├── routes.py\n│ └── templates\n│ └── index.html\n└── helloworld.py\n" }, { "code": null, "e": 3391, "s": 3373, "text": "Create index.html" }, { "code": null, "e": 3569, "s": 3391, "text": "<html>\n <head>\n <title>Colorful Hello, World!</title>\n </head>\n <body>\n <h1 style=\"color:#093657\"> Hello, Template! {{user.name}}</h1>\n </body>\n</html>" }, { "code": null, "e": 3851, "s": 3569, "text": "On the above for the user.name I have to enclose this with double curly braces like this {{user.name}} we can call it as template placeholders. At the time we produce a response from a browser, we are going to replace that with actual values it’s going to come from a user object." }, { "code": null, "e": 3868, "s": 3851, "text": "update routes.py" }, { "code": null, "e": 3979, "s": 3868, "text": "In routes.py remove the static HTML content and instead call render_template() function that comes with Flask." }, { "code": null, "e": 4162, "s": 3979, "text": "from app import app\nfrom flask import render_template\n\n@app.route('/')\ndef index():\n user = {\n 'name':'Chandra'\n }\n return render_template('index.html', user = user)\n" }, { "code": null, "e": 4268, "s": 4162, "text": "Make sure we have to pass the template name and user object as parameters for render_template() function." }, { "code": null, "e": 4284, "s": 4268, "text": "Let’s run again" }, { "code": null, "e": 4298, "s": 4284, "text": "Install Flask" }, { "code": null, "e": 4324, "s": 4298, "text": "Flask Hello World Example" }, { "code": null, "e": 4340, "s": 4324, "text": "Flask Templates" }, { "code": null, "e": 4357, "s": 4340, "text": "Happy Learning 🙂" }, { "code": null, "e": 4889, "s": 4357, "text": "\nFlask – Jinja Templates Example\nHello World Flask Example\nPython – How to install the Flask framework?\nRendering Static HTML page using Django\nAngularjs Services Example Tutorials\nSimple Spring Boot Example\nAngularJs Directive Example Tutorials\nAngularjs Custom Filter Example\nUsing Array in AngularJs Example\nPython – AWS SAM Lambda Example\nAngularJs Orderby Filter Example\nPython Django Helloworld Example\nJava Swing JOptionPane Html Content Example\nSteps to Create AngularJs Controller\nStep by Step Tutorials AngularJs Example\n" }, { "code": null, "e": 4921, "s": 4889, "text": "Flask – Jinja Templates Example" }, { "code": null, "e": 4947, "s": 4921, "text": "Hello World Flask Example" }, { "code": null, "e": 4992, "s": 4947, "text": "Python – How to install the Flask framework?" }, { "code": null, "e": 5032, "s": 4992, "text": "Rendering Static HTML page using Django" }, { "code": null, "e": 5069, "s": 5032, "text": "Angularjs Services Example Tutorials" }, { "code": null, "e": 5096, "s": 5069, "text": "Simple Spring Boot Example" }, { "code": null, "e": 5134, "s": 5096, "text": "AngularJs Directive Example Tutorials" }, { "code": null, "e": 5166, "s": 5134, "text": "Angularjs Custom Filter Example" }, { "code": null, "e": 5199, "s": 5166, "text": "Using Array in AngularJs Example" }, { "code": null, "e": 5231, "s": 5199, "text": "Python – AWS SAM Lambda Example" }, { "code": null, "e": 5264, "s": 5231, "text": "AngularJs Orderby Filter Example" }, { "code": null, "e": 5297, "s": 5264, "text": "Python Django Helloworld Example" }, { "code": null, "e": 5341, "s": 5297, "text": "Java Swing JOptionPane Html Content Example" }, { "code": null, "e": 5378, "s": 5341, "text": "Steps to Create AngularJs Controller" } ]
MongoDB - Delete Multiple Documents Using MongoShell - GeeksforGeeks
27 Feb, 2020 In MongoDB, you are allowed to delete the existing documents from the collection using db.collection.deleteMany() method. This method deletes multiple documents from the collection according to the filter. deleteMany() is a mongo shell method, which can delete multiple documents. This method can be used in the multi-document transactions. If you use this method in capped collection, then it will throw an exception. Syntax: db.collection.deleteMany( <filter>, { writeConcern: <document>, collation: <document> } ) Parameters: fileter: First parameter of this method. It specifies the selection criteria for the delete using query operators. The type of this parameter is document. If it contains empty document, i.e, {}, then this method will delete all the documents from the collection. Optional Parameters: writeConcern: It is only used when you do not want to use the default write concern. The type of this parameter is document. collation: It specifies the use of the collation for operations. It allows users to specify the language-specific rules for string comparison like rules for lettercase and accent marks. The type of this parameter is document. Return: This method will return a document that contains a boolean acknowledged as true (if the write concern is enabled) or false (if the write concern is disabled) and deletedCount that represents the total number of deleted documents. Examples: In the following examples, we are working with: Database: GeeksforGeeks Collection: contributor Document: four documents that contain the details of the contributors in the form of field-value pairs. In this example, we are deleting multiple documents from the contributor collection that matches the filter, i.e., language: “C#”. Or in other words, we are removing those contributors who are working with C# language from the database. In this example, we are deleting all the documents from the contributor collection by passing empty document in the db.collection.deleteMany() method. db.contributor.deleteMany({}) MongoDB Advanced Computer Subject Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Copying Files to and from Docker Containers Principal Component Analysis with Python An introduction to Machine Learning Fuzzy Logic | Introduction OpenCV - Overview Mounting a Volume Inside Docker Container Classifying data using Support Vector Machines(SVMs) in Python Getting Started with System Design How to create a REST API using Java Spring Boot Basics of API Testing Using Postman
[ { "code": null, "e": 23921, "s": 23893, "text": "\n27 Feb, 2020" }, { "code": null, "e": 24127, "s": 23921, "text": "In MongoDB, you are allowed to delete the existing documents from the collection using db.collection.deleteMany() method. This method deletes multiple documents from the collection according to the filter." }, { "code": null, "e": 24340, "s": 24127, "text": "deleteMany() is a mongo shell method, which can delete multiple documents. This method can be used in the multi-document transactions. If you use this method in capped collection, then it will throw an exception." }, { "code": null, "e": 24348, "s": 24340, "text": "Syntax:" }, { "code": null, "e": 24459, "s": 24348, "text": "db.collection.deleteMany(\n <filter>,\n {\n writeConcern: <document>,\n collation: <document>\n }\n)" }, { "code": null, "e": 24471, "s": 24459, "text": "Parameters:" }, { "code": null, "e": 24734, "s": 24471, "text": "fileter: First parameter of this method. It specifies the selection criteria for the delete using query operators. The type of this parameter is document. If it contains empty document, i.e, {}, then this method will delete all the documents from the collection." }, { "code": null, "e": 24755, "s": 24734, "text": "Optional Parameters:" }, { "code": null, "e": 24880, "s": 24755, "text": "writeConcern: It is only used when you do not want to use the default write concern. The type of this parameter is document." }, { "code": null, "e": 25106, "s": 24880, "text": "collation: It specifies the use of the collation for operations. It allows users to specify the language-specific rules for string comparison like rules for lettercase and accent marks. The type of this parameter is document." }, { "code": null, "e": 25344, "s": 25106, "text": "Return: This method will return a document that contains a boolean acknowledged as true (if the write concern is enabled) or false (if the write concern is disabled) and deletedCount that represents the total number of deleted documents." }, { "code": null, "e": 25354, "s": 25344, "text": "Examples:" }, { "code": null, "e": 25402, "s": 25354, "text": "In the following examples, we are working with:" }, { "code": null, "e": 25554, "s": 25402, "text": "Database: GeeksforGeeks\nCollection: contributor\nDocument: four documents that contain the details of the contributors in the form of field-value pairs." }, { "code": null, "e": 25791, "s": 25554, "text": "In this example, we are deleting multiple documents from the contributor collection that matches the filter, i.e., language: “C#”. Or in other words, we are removing those contributors who are working with C# language from the database." }, { "code": null, "e": 25942, "s": 25791, "text": "In this example, we are deleting all the documents from the contributor collection by passing empty document in the db.collection.deleteMany() method." }, { "code": null, "e": 25972, "s": 25942, "text": "db.contributor.deleteMany({})" }, { "code": null, "e": 25980, "s": 25972, "text": "MongoDB" }, { "code": null, "e": 26006, "s": 25980, "text": "Advanced Computer Subject" }, { "code": null, "e": 26104, "s": 26006, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26113, "s": 26104, "text": "Comments" }, { "code": null, "e": 26126, "s": 26113, "text": "Old Comments" }, { "code": null, "e": 26170, "s": 26126, "text": "Copying Files to and from Docker Containers" }, { "code": null, "e": 26211, "s": 26170, "text": "Principal Component Analysis with Python" }, { "code": null, "e": 26247, "s": 26211, "text": "An introduction to Machine Learning" }, { "code": null, "e": 26274, "s": 26247, "text": "Fuzzy Logic | Introduction" }, { "code": null, "e": 26292, "s": 26274, "text": "OpenCV - Overview" }, { "code": null, "e": 26334, "s": 26292, "text": "Mounting a Volume Inside Docker Container" }, { "code": null, "e": 26397, "s": 26334, "text": "Classifying data using Support Vector Machines(SVMs) in Python" }, { "code": null, "e": 26432, "s": 26397, "text": "Getting Started with System Design" }, { "code": null, "e": 26480, "s": 26432, "text": "How to create a REST API using Java Spring Boot" } ]
Python - Stemming and Lemmatization
In the areas of Natural Language Processing we come across situation where two or more words have a common root. For example, the three words - agreed, agreeing and agreeable have the same root word agree. A search involving any of these words should treat them as the same word which is the root word. So it becomes essential to link all the words into their root word. The NLTK library has methods to do this linking and give the output showing the root word. The below program uses the Porter Stemming Algorithm for stemming. import nltk from nltk.stem.porter import PorterStemmer porter_stemmer = PorterStemmer() word_data = "It originated from the idea that there are readers who prefer learning new skills from the comforts of their drawing rooms" # First Word tokenization nltk_tokens = nltk.word_tokenize(word_data) #Next find the roots of the word for w in nltk_tokens: print "Actual: %s Stem: %s" % (w,porter_stemmer.stem(w)) When we execute the above code, it produces the following result. Actual: It Stem: It Actual: originated Stem: origin Actual: from Stem: from Actual: the Stem: the Actual: idea Stem: idea Actual: that Stem: that Actual: there Stem: there Actual: are Stem: are Actual: readers Stem: reader Actual: who Stem: who Actual: prefer Stem: prefer Actual: learning Stem: learn Actual: new Stem: new Actual: skills Stem: skill Actual: from Stem: from Actual: the Stem: the Actual: comforts Stem: comfort Actual: of Stem: of Actual: their Stem: their Actual: drawing Stem: draw Actual: rooms Stem: room Lemmatization is similar ti stemming but it brings context to the words.So it goes a steps further by linking words with similar meaning to one word. For example if a paragraph has words like cars, trains and automobile, then it will link all of them to automobile. In the below program we use the WordNet lexical database for lemmatization. import nltk from nltk.stem import WordNetLemmatizer wordnet_lemmatizer = WordNetLemmatizer() word_data = "It originated from the idea that there are readers who prefer learning new skills from the comforts of their drawing rooms" nltk_tokens = nltk.word_tokenize(word_data) for w in nltk_tokens: print "Actual: %s Lemma: %s" % (w,wordnet_lemmatizer.lemmatize(w)) When we execute the above code, it produces the following result. Actual: It Lemma: It Actual: originated Lemma: originated Actual: from Lemma: from Actual: the Lemma: the Actual: idea Lemma: idea Actual: that Lemma: that Actual: there Lemma: there Actual: are Lemma: are Actual: readers Lemma: reader Actual: who Lemma: who Actual: prefer Lemma: prefer Actual: learning Lemma: learning Actual: new Lemma: new Actual: skills Lemma: skill Actual: from Lemma: from Actual: the Lemma: the Actual: comforts Lemma: comfort Actual: of Lemma: of Actual: their Lemma: their Actual: drawing Lemma: drawing Actual: rooms Lemma: room 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": 2991, "s": 2529, "text": "In the areas of Natural Language Processing we come across situation where two or more words have a common root. For example, the three words - agreed, agreeing and agreeable have the same root word agree. A search involving any of these words should treat them as the same word which is the root word. So it becomes essential to link all the words into their root word. The NLTK library has methods to do this linking and give the output showing the root word." }, { "code": null, "e": 3058, "s": 2991, "text": "The below program uses the Porter Stemming Algorithm for stemming." }, { "code": null, "e": 3475, "s": 3058, "text": "import nltk\nfrom nltk.stem.porter import PorterStemmer\nporter_stemmer = PorterStemmer()\n\nword_data = \"It originated from the idea that there are readers who prefer learning new skills from the comforts of their drawing rooms\"\n# First Word tokenization\nnltk_tokens = nltk.word_tokenize(word_data)\n#Next find the roots of the word\nfor w in nltk_tokens:\n print \"Actual: %s Stem: %s\" % (w,porter_stemmer.stem(w))" }, { "code": null, "e": 3541, "s": 3475, "text": "When we execute the above code, it produces the following result." }, { "code": null, "e": 4088, "s": 3541, "text": "Actual: It Stem: It\nActual: originated Stem: origin\nActual: from Stem: from\nActual: the Stem: the\nActual: idea Stem: idea\nActual: that Stem: that\nActual: there Stem: there\nActual: are Stem: are\nActual: readers Stem: reader\nActual: who Stem: who\nActual: prefer Stem: prefer\nActual: learning Stem: learn\nActual: new Stem: new\nActual: skills Stem: skill\nActual: from Stem: from\nActual: the Stem: the\nActual: comforts Stem: comfort\nActual: of Stem: of\nActual: their Stem: their\nActual: drawing Stem: draw\nActual: rooms Stem: room" }, { "code": null, "e": 4430, "s": 4088, "text": "Lemmatization is similar ti stemming but it brings context to the words.So it goes a steps further by linking words with similar meaning to one word. For example if a paragraph has words like cars, trains and automobile, then it will link all of them to automobile. In the below program we use the WordNet lexical database for lemmatization." }, { "code": null, "e": 4803, "s": 4430, "text": "import nltk\nfrom nltk.stem import WordNetLemmatizer\nwordnet_lemmatizer = WordNetLemmatizer()\n\nword_data = \"It originated from the idea that there are readers who prefer learning new skills from the comforts of their drawing rooms\"\nnltk_tokens = nltk.word_tokenize(word_data)\nfor w in nltk_tokens:\n print \"Actual: %s Lemma: %s\" % (w,wordnet_lemmatizer.lemmatize(w))" }, { "code": null, "e": 4869, "s": 4803, "text": "When we execute the above code, it produces the following result." }, { "code": null, "e": 5447, "s": 4869, "text": "Actual: It Lemma: It\nActual: originated Lemma: originated\nActual: from Lemma: from\nActual: the Lemma: the\nActual: idea Lemma: idea\nActual: that Lemma: that\nActual: there Lemma: there\nActual: are Lemma: are\nActual: readers Lemma: reader\nActual: who Lemma: who\nActual: prefer Lemma: prefer\nActual: learning Lemma: learning\nActual: new Lemma: new\nActual: skills Lemma: skill\nActual: from Lemma: from\nActual: the Lemma: the\nActual: comforts Lemma: comfort\nActual: of Lemma: of\nActual: their Lemma: their\nActual: drawing Lemma: drawing\nActual: rooms Lemma: room" }, { "code": null, "e": 5484, "s": 5447, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 5500, "s": 5484, "text": " Malhar Lathkar" }, { "code": null, "e": 5533, "s": 5500, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 5552, "s": 5533, "text": " Arnab Chakraborty" }, { "code": null, "e": 5587, "s": 5552, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 5609, "s": 5587, "text": " In28Minutes Official" }, { "code": null, "e": 5643, "s": 5609, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 5671, "s": 5643, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 5706, "s": 5671, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 5720, "s": 5706, "text": " Lets Kode It" }, { "code": null, "e": 5753, "s": 5720, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 5770, "s": 5753, "text": " Abhilash Nelson" }, { "code": null, "e": 5777, "s": 5770, "text": " Print" }, { "code": null, "e": 5788, "s": 5777, "text": " Add Notes" } ]
Accelerating Pandas concatenation | by Philippe Cotte | Towards Data Science
I was recently faced with the problem of concatenating a fair amount of MultiIndexed Pandas Series (stacked DataFrames) into one single DataFrame. This can take a fair amount of time if you have many and/or large Series, and because of the MultiIndex, Dask cannot be used. I first present a sample of code using Dask’s logic to concatenate the Series pairwise in parallel jobs. I then show the acceleration performance for different parallel processing methods, for several number of CPUs ranging from 8 to 80 and several number of Series ranging from 10 to 90. An optimal computation time of 37 % compared to the benchmark is found with only 8 CPUs. A higher number of CPUs does not reduce the relative computation time significantly. In order to give some context to this study, let us specify how the data look like: we need to concatenate 90 time-indexed DataFrames of roughly 2000 lines and 500 columns, by stacking them into Series of 2000 x 500 lines and then concatenating those Series together with each Series being a column of the new DataFrame (see Figure 1). This can take, on my local machine (Intel® CoreTM i9–9900K CPU @ 3.60 GHz × 16, 32 GB memory), up to 10 minutes. It is worth mentioning that after stacking the initial DataFrames into Series, not a single index was found that was present in every Series, so the concatenation process will have a lot of re-indexing to do. Usually, for this kind of acceleration problem, one would use Dask. Here it is not possible, for Dask does not support MultiIndex. But we can still use its basic logic, which is the following (see Figure 2): instead of concatenating N DataFrames at once, we split the N DataFrames into N/2 pairs and parallelize the concatenation of the 2 DataFrames in each pairs. Then we end up with N/2 DataFrames, which we split into N/4 pairs, and so on. If N is not even, we just do the previous steps with the first N-1 DataFrames, and concatenate the remaining DataFrame with the resulting DataFrame. Here is the sample of code doing that : You can notice that the step of loading the files was included in the concat method, in order to make it parallel too. The algorithm presented above was executed on a GCP machine of type n2-highcpu-80 (80 vCPUs, 80 GB memory). The benchmark used is the standard pandas concatenation, where the process of loading the files is parallelized: with ProcessPoolExecutor(max_workers=max_workers) as e: features = pd.concat(e.map(get_feature, features), axis=1)features = features.loc[:, sorted(features.columns)] Figure 3 shows the absolute (left axis, plain lines) and relative (right axis, dashed lines) computation time against the number of CPUs used, for 90 DataFrames and various parallelization methods. The error bars are obtained by running each point 5 times and taking the standard deviation of the 5 resulting times. Several things can be said about that graph: There is a fast decrease in computation time for all methods between 8 and 16 CPUs. This can be attributed to the process of opening files being efficiently parallelized, for the benchmark line follows this trend too but only implements parallel jobs for opening the files. The computation time is back to its initial value at 64 CPUs for all the methods, most likely because of the overhead of the multithreading (this has also been observed at the end of this study by one of my coworkers) towardsdatascience.com The most effective parallel computation method seems to be ThreadPool There is a clear speed up of the concatenation process between ThreadPool and the benchmark, with a gain of 63 % +/- 1.5 %. This gain is achieved with 8 CPUs, and is not significantly better with more CPUs Figure 4 is similar to the previous one but when concatenating 30 DataFrames instead of 90. The curves behave similarly compared to the previous graph. The absolute computation times are smaller as expected. So is the relative gain, and that too was to be expected. However the best method changed: ProcessPoolExecutor achieves the best gain, and not ThreadPool anymore. Figure 5 shows the same absolute and relative time, with 8 CPUs, against the number of DataFrames to concatenate. This graph tells us two things: Even with as few as 10 DataFrames, the parallelization gives significant decrease in computation time. ThreadPool is the best method only above 70 DataFrames. Below that, ProcessPoolExecutor shows better results. My knowledge of the gears and tricks involved in parallel computation is not enough to allow me to propose any explanation on that last point, but if you have an idea about it do not hesitate to leave a comment! It would seem that ThreadPool, even though being a bit slower with fewer DataFrames, handles better a load ramping up than ProcessPoolExecutor. I proposed here a method to accelerate the process of concatenating many Pandas Series into one DataFrame by using a Dask-like approach, when Dask itself can not be used because of the MultiIndex. This approach allowed for a gain of 63 % in computation time with only 8 CPUs, so it is worth implementing on desktop machines. The results provided here have only been tested with a fixed size for input Pandas Series (2000x500 rows). It remains to be studied how well this method would fare with bigger or smaller data sets. Furthermore, after stacking the initial DataFrames into Series, not a single index was found that was present in every Series, so the concatenation process had a lot of re-indexing to do, which would have benefited a lot from the parallelization. For “cleaner” data sets, sharing a common index, the gain in computational time might be smaller. Advestis is a European Contract Research Organization (CRO) with a deep understanding and practice of statistics, and interpretable machine learning techniques. The expertise of Advestis covers the modeling of complex systems and predictive analysis for temporal phenomena.
[ { "code": null, "e": 734, "s": 172, "text": "I was recently faced with the problem of concatenating a fair amount of MultiIndexed Pandas Series (stacked DataFrames) into one single DataFrame. This can take a fair amount of time if you have many and/or large Series, and because of the MultiIndex, Dask cannot be used. I first present a sample of code using Dask’s logic to concatenate the Series pairwise in parallel jobs. I then show the acceleration performance for different parallel processing methods, for several number of CPUs ranging from 8 to 80 and several number of Series ranging from 10 to 90." }, { "code": null, "e": 908, "s": 734, "text": "An optimal computation time of 37 % compared to the benchmark is found with only 8 CPUs. A higher number of CPUs does not reduce the relative computation time significantly." }, { "code": null, "e": 1566, "s": 908, "text": "In order to give some context to this study, let us specify how the data look like: we need to concatenate 90 time-indexed DataFrames of roughly 2000 lines and 500 columns, by stacking them into Series of 2000 x 500 lines and then concatenating those Series together with each Series being a column of the new DataFrame (see Figure 1). This can take, on my local machine (Intel® CoreTM i9–9900K CPU @ 3.60 GHz × 16, 32 GB memory), up to 10 minutes. It is worth mentioning that after stacking the initial DataFrames into Series, not a single index was found that was present in every Series, so the concatenation process will have a lot of re-indexing to do." }, { "code": null, "e": 2009, "s": 1566, "text": "Usually, for this kind of acceleration problem, one would use Dask. Here it is not possible, for Dask does not support MultiIndex. But we can still use its basic logic, which is the following (see Figure 2): instead of concatenating N DataFrames at once, we split the N DataFrames into N/2 pairs and parallelize the concatenation of the 2 DataFrames in each pairs. Then we end up with N/2 DataFrames, which we split into N/4 pairs, and so on." }, { "code": null, "e": 2158, "s": 2009, "text": "If N is not even, we just do the previous steps with the first N-1 DataFrames, and concatenate the remaining DataFrame with the resulting DataFrame." }, { "code": null, "e": 2198, "s": 2158, "text": "Here is the sample of code doing that :" }, { "code": null, "e": 2317, "s": 2198, "text": "You can notice that the step of loading the files was included in the concat method, in order to make it parallel too." }, { "code": null, "e": 2538, "s": 2317, "text": "The algorithm presented above was executed on a GCP machine of type n2-highcpu-80 (80 vCPUs, 80 GB memory). The benchmark used is the standard pandas concatenation, where the process of loading the files is parallelized:" }, { "code": null, "e": 2708, "s": 2538, "text": "with ProcessPoolExecutor(max_workers=max_workers) as e: features = pd.concat(e.map(get_feature, features), axis=1)features = features.loc[:, sorted(features.columns)]" }, { "code": null, "e": 3024, "s": 2708, "text": "Figure 3 shows the absolute (left axis, plain lines) and relative (right axis, dashed lines) computation time against the number of CPUs used, for 90 DataFrames and various parallelization methods. The error bars are obtained by running each point 5 times and taking the standard deviation of the 5 resulting times." }, { "code": null, "e": 3069, "s": 3024, "text": "Several things can be said about that graph:" }, { "code": null, "e": 3343, "s": 3069, "text": "There is a fast decrease in computation time for all methods between 8 and 16 CPUs. This can be attributed to the process of opening files being efficiently parallelized, for the benchmark line follows this trend too but only implements parallel jobs for opening the files." }, { "code": null, "e": 3561, "s": 3343, "text": "The computation time is back to its initial value at 64 CPUs for all the methods, most likely because of the overhead of the multithreading (this has also been observed at the end of this study by one of my coworkers)" }, { "code": null, "e": 3584, "s": 3561, "text": "towardsdatascience.com" }, { "code": null, "e": 3654, "s": 3584, "text": "The most effective parallel computation method seems to be ThreadPool" }, { "code": null, "e": 3778, "s": 3654, "text": "There is a clear speed up of the concatenation process between ThreadPool and the benchmark, with a gain of 63 % +/- 1.5 %." }, { "code": null, "e": 3860, "s": 3778, "text": "This gain is achieved with 8 CPUs, and is not significantly better with more CPUs" }, { "code": null, "e": 3952, "s": 3860, "text": "Figure 4 is similar to the previous one but when concatenating 30 DataFrames instead of 90." }, { "code": null, "e": 4231, "s": 3952, "text": "The curves behave similarly compared to the previous graph. The absolute computation times are smaller as expected. So is the relative gain, and that too was to be expected. However the best method changed: ProcessPoolExecutor achieves the best gain, and not ThreadPool anymore." }, { "code": null, "e": 4345, "s": 4231, "text": "Figure 5 shows the same absolute and relative time, with 8 CPUs, against the number of DataFrames to concatenate." }, { "code": null, "e": 4377, "s": 4345, "text": "This graph tells us two things:" }, { "code": null, "e": 4480, "s": 4377, "text": "Even with as few as 10 DataFrames, the parallelization gives significant decrease in computation time." }, { "code": null, "e": 4590, "s": 4480, "text": "ThreadPool is the best method only above 70 DataFrames. Below that, ProcessPoolExecutor shows better results." }, { "code": null, "e": 4946, "s": 4590, "text": "My knowledge of the gears and tricks involved in parallel computation is not enough to allow me to propose any explanation on that last point, but if you have an idea about it do not hesitate to leave a comment! It would seem that ThreadPool, even though being a bit slower with fewer DataFrames, handles better a load ramping up than ProcessPoolExecutor." }, { "code": null, "e": 5271, "s": 4946, "text": "I proposed here a method to accelerate the process of concatenating many Pandas Series into one DataFrame by using a Dask-like approach, when Dask itself can not be used because of the MultiIndex. This approach allowed for a gain of 63 % in computation time with only 8 CPUs, so it is worth implementing on desktop machines." }, { "code": null, "e": 5814, "s": 5271, "text": "The results provided here have only been tested with a fixed size for input Pandas Series (2000x500 rows). It remains to be studied how well this method would fare with bigger or smaller data sets. Furthermore, after stacking the initial DataFrames into Series, not a single index was found that was present in every Series, so the concatenation process had a lot of re-indexing to do, which would have benefited a lot from the parallelization. For “cleaner” data sets, sharing a common index, the gain in computational time might be smaller." } ]
PHP | imagecrop() Function - GeeksforGeeks
23 Aug, 2019 The imagecrop() function is an inbuilt function in PHP which is used to crop an image to the given rectangle. This function crops an image to the given rectangular area and returns the resulting image. The given image is not modified. Syntax: resource imagecrop ( $image, $rect ) Parameters: This function accepts two parameters as mentioned above and described below: $image: It is returned by one of the image creation functions, such as imagecreatetruecolor(). It is used to create size of image. $rect: The cropping rectangle as array with keys x, y, width and height. Return Value: This function return cropped image resource on success or False on failure. Below programs illustrate the imagecrop() function in PHP: Program: <?php // Create an image from given image$im = imagecreatefrompng('https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-9.png'); // find the size of image$size = min(imagesx($im), imagesy($im)); // Set the crop image size $im2 = imagecrop($im, ['x' => 0, 'y' => 0, 'width' => 250, 'height' => 150]);if ($im2 !== FALSE) { header("Content-type: image/png"); imagepng($im2); imagedestroy($im2);}imagedestroy($im);?> output: Related Articles: PHP | gd_info() Function PHP | imagearc() Function Reference: http://php.net/manual/en/function.imagecrop.php Image-Processing PHP-function PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? How to Upload Image into Database and Display it using PHP ? How to check whether an array is empty using PHP? How to receive JSON POST with PHP ? Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 24245, "s": 24217, "text": "\n23 Aug, 2019" }, { "code": null, "e": 24480, "s": 24245, "text": "The imagecrop() function is an inbuilt function in PHP which is used to crop an image to the given rectangle. This function crops an image to the given rectangular area and returns the resulting image. The given image is not modified." }, { "code": null, "e": 24488, "s": 24480, "text": "Syntax:" }, { "code": null, "e": 24525, "s": 24488, "text": "resource imagecrop ( $image, $rect )" }, { "code": null, "e": 24614, "s": 24525, "text": "Parameters: This function accepts two parameters as mentioned above and described below:" }, { "code": null, "e": 24745, "s": 24614, "text": "$image: It is returned by one of the image creation functions, such as imagecreatetruecolor(). It is used to create size of image." }, { "code": null, "e": 24818, "s": 24745, "text": "$rect: The cropping rectangle as array with keys x, y, width and height." }, { "code": null, "e": 24908, "s": 24818, "text": "Return Value: This function return cropped image resource on success or False on failure." }, { "code": null, "e": 24967, "s": 24908, "text": "Below programs illustrate the imagecrop() function in PHP:" }, { "code": null, "e": 24976, "s": 24967, "text": "Program:" }, { "code": "<?php // Create an image from given image$im = imagecreatefrompng('https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-9.png'); // find the size of image$size = min(imagesx($im), imagesy($im)); // Set the crop image size $im2 = imagecrop($im, ['x' => 0, 'y' => 0, 'width' => 250, 'height' => 150]);if ($im2 !== FALSE) { header(\"Content-type: image/png\"); imagepng($im2); imagedestroy($im2);}imagedestroy($im);?>", "e": 25416, "s": 24976, "text": null }, { "code": null, "e": 25424, "s": 25416, "text": "output:" }, { "code": null, "e": 25442, "s": 25424, "text": "Related Articles:" }, { "code": null, "e": 25467, "s": 25442, "text": "PHP | gd_info() Function" }, { "code": null, "e": 25493, "s": 25467, "text": "PHP | imagearc() Function" }, { "code": null, "e": 25552, "s": 25493, "text": "Reference: http://php.net/manual/en/function.imagecrop.php" }, { "code": null, "e": 25569, "s": 25552, "text": "Image-Processing" }, { "code": null, "e": 25582, "s": 25569, "text": "PHP-function" }, { "code": null, "e": 25586, "s": 25582, "text": "PHP" }, { "code": null, "e": 25603, "s": 25586, "text": "Web Technologies" }, { "code": null, "e": 25607, "s": 25603, "text": "PHP" }, { "code": null, "e": 25705, "s": 25607, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25714, "s": 25705, "text": "Comments" }, { "code": null, "e": 25727, "s": 25714, "text": "Old Comments" }, { "code": null, "e": 25777, "s": 25727, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 25817, "s": 25777, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 25878, "s": 25817, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 25928, "s": 25878, "text": "How to check whether an array is empty using PHP?" }, { "code": null, "e": 25964, "s": 25928, "text": "How to receive JSON POST with PHP ?" }, { "code": null, "e": 26020, "s": 25964, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 26053, "s": 26020, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 26115, "s": 26053, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 26158, "s": 26115, "text": "How to fetch data from an API in ReactJS ?" } ]
nested loops in C
C programming allows to use one loop inside another loop. The following section shows a few examples to illustrate the concept. The syntax for a nested for loop statement in C is as follows − for ( init; condition; increment ) { for ( init; condition; increment ) { statement(s); } statement(s); } The syntax for a nested while loop statement in C programming language is as follows − while(condition) { while(condition) { statement(s); } statement(s); } The syntax for a nested do...while loop statement in C programming language is as follows − do { statement(s); do { statement(s); }while( condition ); }while( condition ); A final note on loop nesting is that you can put any type of loop inside any other type of loop. For example, a 'for' loop can be inside a 'while' loop or vice versa. The following program uses a nested for loop to find the prime numbers from 2 to 100 − #include <stdio.h> int main () { /* local variable definition */ int i, j; for(i = 2; i<100; i++) { for(j = 2; j <= (i/j); j++) if(!(i%j)) break; // if factor found, not prime if(j > (i/j)) printf("%d is prime\n", i); } return 0; } When the above code is compiled and executed, it produces the following result − 2 is prime 3 is prime 5 is prime 7 is prime 11 is prime 13 is prime 17 is prime 19 is prime 23 is prime 29 is prime 31 is prime 37 is prime 41 is prime 43 is prime 47 is prime 53 is prime 59 is prime 61 is prime 67 is prime 71 is prime 73 is prime 79 is prime 83 is prime 89 is prime 97 is prime Print Add Notes Bookmark this page
[ { "code": null, "e": 2212, "s": 2084, "text": "C programming allows to use one loop inside another loop. The following section shows a few examples to illustrate the concept." }, { "code": null, "e": 2276, "s": 2212, "text": "The syntax for a nested for loop statement in C is as follows −" }, { "code": null, "e": 2399, "s": 2276, "text": "for ( init; condition; increment ) {\n\n for ( init; condition; increment ) {\n statement(s);\n }\n statement(s);\n}\n" }, { "code": null, "e": 2486, "s": 2399, "text": "The syntax for a nested while loop statement in C programming language is as follows −" }, { "code": null, "e": 2573, "s": 2486, "text": "while(condition) {\n\n while(condition) {\n statement(s);\n }\n statement(s);\n}\n" }, { "code": null, "e": 2665, "s": 2573, "text": "The syntax for a nested do...while loop statement in C programming language is as follows −" }, { "code": null, "e": 2763, "s": 2665, "text": "do {\n statement(s);\n\n do {\n statement(s);\n }while( condition );\n\n}while( condition );\n" }, { "code": null, "e": 2930, "s": 2763, "text": "A final note on loop nesting is that you can put any type of loop inside any other type of loop. For example, a 'for' loop can be inside a 'while' loop or vice versa." }, { "code": null, "e": 3017, "s": 2930, "text": "The following program uses a nested for loop to find the prime numbers from 2 to 100 −" }, { "code": null, "e": 3293, "s": 3017, "text": "#include <stdio.h>\n \nint main () {\n\n /* local variable definition */\n int i, j;\n \n for(i = 2; i<100; i++) {\n\n for(j = 2; j <= (i/j); j++) \n if(!(i%j)) break; // if factor found, not prime\n if(j > (i/j)) printf(\"%d is prime\\n\", i);\n }\n \n return 0;\n}" }, { "code": null, "e": 3374, "s": 3293, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 3671, "s": 3374, "text": "2 is prime\n3 is prime\n5 is prime\n7 is prime\n11 is prime\n13 is prime\n17 is prime\n19 is prime\n23 is prime\n29 is prime\n31 is prime\n37 is prime\n41 is prime\n43 is prime\n47 is prime\n53 is prime\n59 is prime\n61 is prime\n67 is prime\n71 is prime\n73 is prime\n79 is prime\n83 is prime\n89 is prime\n97 is prime\n" }, { "code": null, "e": 3678, "s": 3671, "text": " Print" }, { "code": null, "e": 3689, "s": 3678, "text": " Add Notes" } ]
Mermaid: Create diagrams quickly and effortlessly | by Alexandra Souly | Towards Data Science
If you’ve ever tried to explain anything complicated — be it an algorithm, a code base structure or a project plan — you probably know how useful good diagrams are. However, with lots of us working remotely, it is more difficult to share spontaneous drawings when explanations fall short. While it was easy to have a whiteboard session in the office, this is a lot more awkward online. Trying to draw wonky boxes with your mouse in a drawing app, or dragging clunky arrows, all while your co-workers are watching your shared screen in a call is not fun, to say the least. But there is a way to generate all your diagrams quickly and painlessly with code only, so you’ll never have to draw a box again! Mermaid is a tool that lets you create complicated diagrams in Markdown — it works with simple commands and an intuitive syntax. You don’t have to draw anything, just write down what you want to see! You can create flowcharts to help you understand algorithms, Gantt charts for project management, pie charts, and many other common diagram types. Mermaid arranges the diagram sensibly for you, so you won’t have to worry about manually rearranging all your boxes if you forgot a middle step in a flowchart. In this article, I will tell you about the different ways to use Mermaid, and show you some examples of what it’s capable of. It is certainly my favourite tool to create diagrams, I hope it becomes yours too! Human brains are much better at understanding images and patterns than text. We process a complicated structure faster if we see its visual representation, and it turns out we also remember it better — this is called the picture superiority effect. This is also intuitive — you can draw conclusions form a bar or pie chart much faster than reading a list of numbers. Pictures also grab the audience’s attention. If you give a lengthy, complicated explanation without a visual aid, most of your listeners will have zoned out after a minute, or already forgot the beginning. If you include a diagram, they can find their way back to your explanation. They are also helpful to draw for yourself if you just want to understand something that requires more information than what your working memory can deal with. Drawing the high level code base architecture, the information flow in a components or a lower level OOP class designs can help you spot design errors upfront, when it’s the cheapest to correct. A very underrated use for diagrams is putting one in your GitHub repository README file, displaying the code architecture. Particularly for open source repos lots of people contribute to, it allows newcomers to familiarise themselves with the codebase quickly, instead of looking through what’s in each directory. The same applies to new starters in your company — they will really appreciate having a diagram for every repository. Unlike lots of other GUI-based graph drawing software, Mermaid is completely text-based. No painful dragging of boxes and arrows, you just type code based on a Markdown-inspired syntax. This makes the diagrams very easily maintainable. You will always have the code that generated the diagram, so you won’t end up with a beautiful, but outdated image file you can’t modify anymore. This also means that you can easily see the changes to a diagram, unlike with any other image-based method. If you keep your diagram under Git version control (which you can easily, as it’s stored as text), a simple git diff will show you what changed in a human-readable way. I‘ve already mentioned that Mermaid rearranges the boxes for you if you decide to add more stuff to your diagram. This makes it possible to generate diagrams on the fly in a video call, much faster than hand-drawing them on a laptop. I have found that if you spend about half an hour on learning the syntax, you can completely replace any other graph drawing tool you use. Personally, I find drawing with a mouse really difficult, so for me Mermaid is superior to using Paint or OneNote, and with some practice it is much faster to use than draw.io for example. Let’s look at some examples Mermaid can render for us, and what the code that generates it looks like: graph TD A{Does your flowchart have arrows?} --> B[No] A --> C[yes] B --> D(Add them already) C --> E(Yay, what a great flowchart!) D -.->|you can even add text to them| A The start graph TD indicates the orientation of the graph: top-down as opposed to LR(left-right), RL(right-left) or BT(bottom-top).You can specify nodes by a short identifier (A, B, C here) and indicate what shape and text it should have with the brackets following it. You can specify many shapes, including circle, rhombus or trapezoid. To specify the arrows from one box to another, you just type the two node IDs joined by an arrow, depending on what arrow type you want. You can add text to the arrows with the |<text>| before the destination node. There is also a shorthand to express more complicated dependencies to save time typing out all the arrows, using & to bundle nodes together. To create subgraphs, you can just type subgraph <name> and <end> once you have finished declaring what's inside. Mermaid uses CSS style for customisation, you can change the style of your nodes if you want. Although that's a bit harder to just memorise, it should be okay if you are familiar with CSS : graph LRA & B--> C & Dstyle A fill:#f9f,stroke:#333,stroke-width:pxstyle B fill:#bbf,stroke:#f66,stroke-width:2px,color:#fff,stroke-dasharray: 5 5subgraph beginningA & Bendsubgraph endingC & Dend Another example, this one of a Gantt chart, commonly used for project management: gantttitle Writing my thesisdateFormat MM-DDaxisFormat %m-%dsection ResearchProcrastinate :a1, 01-01, 59dDo it :after a1 , 10dsection Write-upShould I start? :03-01 , 20dUgh ok : 6d We had to specify the date formats, what our sections are, what the tasks are, when they start and how long they last. Straightforward, and no boilerplate statements needed. To learn more about the syntax and different options like pie charts and status diagrams, check out the Mermaid syntax guide here. You can use Mermaid in lots of different ways: Online live editor GitLab Websites (including GitHub pages) Code editors Browser extension Command line The full list of integrations can be found here. This is the simplest way to try out Mermaid, using their online tool. You can start with a template, and verify how your changes affect the final result. You can save your image directly, or just create a link to it. As a bonus, it also saves your recent changes with cookies, so you don’t have to worry about continuing the next day. All the examples in this article were made with the live editor. GitLab does Mermaid support by default in its Markdown files. You can just add your diagrams with the following syntax, and it will magically work: ```mermaidgraph TD;A →B;A →C;B →D;C →D;``` If you are however a GitHub user, I will have to disappoint you — they have not officially integrated with Mermaid so far. There is a project to compile your Mermaid graph as a GitHub action, so you can still insert the image into a README file without doing anything and let the pipeline take care of it. If you have a website with Yarn as your package manager, adding Mermaid as a dependency is simple: yarn add mermaid If you don’t have a bundler, use the following: <script src="https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js"></script><script>mermaid.initialize({startOnLoad:true});</script> This will make the Mermaid parser look for <div> tags with class Mermaid, and render them into diagrams. So you would use it as <div class="mermaid">graph TD;A-->B;A-->C;B-->D;C-->D;</div> If you use GitHub pages, just add the following to your ‘header.html’, or download the file and source from the relative path: <script src="https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js"> Then, to include a diagram in your Markdown posts, use ```html<div class="mermaid">graph TD;A-->B;A-->C;B-->D;C-->D;</div>``` Alternatively, if you have a Jekyll site that is not on GitHub pages, you can use the jekyll-mermaid plugin. If you use WordPress, there is a plugin for you too. May editors support Mermaid, including Atom, VIM and VS Code. I personally use VS Code, and the extension Markdown Preview Mermaid Support is very helpful in rendering the graphs in the markdown previews. The browser extension processes all the Markdown syntax found in a Markdown document, which means you can still locally view your graphs even if for example GitHub won’t render them to you. This extension works both on Chrome and Firefox. Of course, if you want other people to also see the diagram, they also have to download the extension. Mermaid-CLI exists so that you can directly create diagrams out of input files using the CLI. It works from within a Docker container, you can see how to use it here. Mermaid is such a fun tool to use once you get used to it, and it can save so much time and effort when trying to create diagrams without paper. I hope you found this short guide useful and it can save some time for your next diagram! https://mermaid-js.github.io/ Blog — Use Mermaid syntax to create diagrams Mermaid — Create Charts and Diagrams With Markdown-like Syntax | by Trevor Lasn | Better Programming Making Diagrams Fun With Mermaid. Sometimes, a good diagram is the best... | by Ozan Tunca | Better Programming Diagrams as Code: Mermaid (freshbrewed.science)
[ { "code": null, "e": 337, "s": 172, "text": "If you’ve ever tried to explain anything complicated — be it an algorithm, a code base structure or a project plan — you probably know how useful good diagrams are." }, { "code": null, "e": 744, "s": 337, "text": "However, with lots of us working remotely, it is more difficult to share spontaneous drawings when explanations fall short. While it was easy to have a whiteboard session in the office, this is a lot more awkward online. Trying to draw wonky boxes with your mouse in a drawing app, or dragging clunky arrows, all while your co-workers are watching your shared screen in a call is not fun, to say the least." }, { "code": null, "e": 874, "s": 744, "text": "But there is a way to generate all your diagrams quickly and painlessly with code only, so you’ll never have to draw a box again!" }, { "code": null, "e": 1074, "s": 874, "text": "Mermaid is a tool that lets you create complicated diagrams in Markdown — it works with simple commands and an intuitive syntax. You don’t have to draw anything, just write down what you want to see!" }, { "code": null, "e": 1221, "s": 1074, "text": "You can create flowcharts to help you understand algorithms, Gantt charts for project management, pie charts, and many other common diagram types." }, { "code": null, "e": 1381, "s": 1221, "text": "Mermaid arranges the diagram sensibly for you, so you won’t have to worry about manually rearranging all your boxes if you forgot a middle step in a flowchart." }, { "code": null, "e": 1590, "s": 1381, "text": "In this article, I will tell you about the different ways to use Mermaid, and show you some examples of what it’s capable of. It is certainly my favourite tool to create diagrams, I hope it becomes yours too!" }, { "code": null, "e": 1957, "s": 1590, "text": "Human brains are much better at understanding images and patterns than text. We process a complicated structure faster if we see its visual representation, and it turns out we also remember it better — this is called the picture superiority effect. This is also intuitive — you can draw conclusions form a bar or pie chart much faster than reading a list of numbers." }, { "code": null, "e": 2239, "s": 1957, "text": "Pictures also grab the audience’s attention. If you give a lengthy, complicated explanation without a visual aid, most of your listeners will have zoned out after a minute, or already forgot the beginning. If you include a diagram, they can find their way back to your explanation." }, { "code": null, "e": 2594, "s": 2239, "text": "They are also helpful to draw for yourself if you just want to understand something that requires more information than what your working memory can deal with. Drawing the high level code base architecture, the information flow in a components or a lower level OOP class designs can help you spot design errors upfront, when it’s the cheapest to correct." }, { "code": null, "e": 3026, "s": 2594, "text": "A very underrated use for diagrams is putting one in your GitHub repository README file, displaying the code architecture. Particularly for open source repos lots of people contribute to, it allows newcomers to familiarise themselves with the codebase quickly, instead of looking through what’s in each directory. The same applies to new starters in your company — they will really appreciate having a diagram for every repository." }, { "code": null, "e": 3408, "s": 3026, "text": "Unlike lots of other GUI-based graph drawing software, Mermaid is completely text-based. No painful dragging of boxes and arrows, you just type code based on a Markdown-inspired syntax. This makes the diagrams very easily maintainable. You will always have the code that generated the diagram, so you won’t end up with a beautiful, but outdated image file you can’t modify anymore." }, { "code": null, "e": 3685, "s": 3408, "text": "This also means that you can easily see the changes to a diagram, unlike with any other image-based method. If you keep your diagram under Git version control (which you can easily, as it’s stored as text), a simple git diff will show you what changed in a human-readable way." }, { "code": null, "e": 4247, "s": 3685, "text": "I‘ve already mentioned that Mermaid rearranges the boxes for you if you decide to add more stuff to your diagram. This makes it possible to generate diagrams on the fly in a video call, much faster than hand-drawing them on a laptop. I have found that if you spend about half an hour on learning the syntax, you can completely replace any other graph drawing tool you use. Personally, I find drawing with a mouse really difficult, so for me Mermaid is superior to using Paint or OneNote, and with some practice it is much faster to use than draw.io for example." }, { "code": null, "e": 4350, "s": 4247, "text": "Let’s look at some examples Mermaid can render for us, and what the code that generates it looks like:" }, { "code": null, "e": 4537, "s": 4350, "text": "graph TD A{Does your flowchart have arrows?} --> B[No] A --> C[yes] B --> D(Add them already) C --> E(Yay, what a great flowchart!) D -.->|you can even add text to them| A" }, { "code": null, "e": 5091, "s": 4537, "text": "The start graph TD indicates the orientation of the graph: top-down as opposed to LR(left-right), RL(right-left) or BT(bottom-top).You can specify nodes by a short identifier (A, B, C here) and indicate what shape and text it should have with the brackets following it. You can specify many shapes, including circle, rhombus or trapezoid. To specify the arrows from one box to another, you just type the two node IDs joined by an arrow, depending on what arrow type you want. You can add text to the arrows with the |<text>| before the destination node." }, { "code": null, "e": 5535, "s": 5091, "text": "There is also a shorthand to express more complicated dependencies to save time typing out all the arrows, using & to bundle nodes together. To create subgraphs, you can just type subgraph <name> and <end> once you have finished declaring what's inside. Mermaid uses CSS style for customisation, you can change the style of your nodes if you want. Although that's a bit harder to just memorise, it should be okay if you are familiar with CSS :" }, { "code": null, "e": 5731, "s": 5535, "text": "graph LRA & B--> C & Dstyle A fill:#f9f,stroke:#333,stroke-width:pxstyle B fill:#bbf,stroke:#f66,stroke-width:2px,color:#fff,stroke-dasharray: 5 5subgraph beginningA & Bendsubgraph endingC & Dend" }, { "code": null, "e": 5813, "s": 5731, "text": "Another example, this one of a Gantt chart, commonly used for project management:" }, { "code": null, "e": 6021, "s": 5813, "text": "gantttitle Writing my thesisdateFormat MM-DDaxisFormat %m-%dsection ResearchProcrastinate :a1, 01-01, 59dDo it :after a1 , 10dsection Write-upShould I start? :03-01 , 20dUgh ok : 6d" }, { "code": null, "e": 6195, "s": 6021, "text": "We had to specify the date formats, what our sections are, what the tasks are, when they start and how long they last. Straightforward, and no boilerplate statements needed." }, { "code": null, "e": 6326, "s": 6195, "text": "To learn more about the syntax and different options like pie charts and status diagrams, check out the Mermaid syntax guide here." }, { "code": null, "e": 6373, "s": 6326, "text": "You can use Mermaid in lots of different ways:" }, { "code": null, "e": 6392, "s": 6373, "text": "Online live editor" }, { "code": null, "e": 6399, "s": 6392, "text": "GitLab" }, { "code": null, "e": 6433, "s": 6399, "text": "Websites (including GitHub pages)" }, { "code": null, "e": 6446, "s": 6433, "text": "Code editors" }, { "code": null, "e": 6464, "s": 6446, "text": "Browser extension" }, { "code": null, "e": 6477, "s": 6464, "text": "Command line" }, { "code": null, "e": 6526, "s": 6477, "text": "The full list of integrations can be found here." }, { "code": null, "e": 6926, "s": 6526, "text": "This is the simplest way to try out Mermaid, using their online tool. You can start with a template, and verify how your changes affect the final result. You can save your image directly, or just create a link to it. As a bonus, it also saves your recent changes with cookies, so you don’t have to worry about continuing the next day. All the examples in this article were made with the live editor." }, { "code": null, "e": 7074, "s": 6926, "text": "GitLab does Mermaid support by default in its Markdown files. You can just add your diagrams with the following syntax, and it will magically work:" }, { "code": null, "e": 7117, "s": 7074, "text": "```mermaidgraph TD;A →B;A →C;B →D;C →D;```" }, { "code": null, "e": 7423, "s": 7117, "text": "If you are however a GitHub user, I will have to disappoint you — they have not officially integrated with Mermaid so far. There is a project to compile your Mermaid graph as a GitHub action, so you can still insert the image into a README file without doing anything and let the pipeline take care of it." }, { "code": null, "e": 7522, "s": 7423, "text": "If you have a website with Yarn as your package manager, adding Mermaid as a dependency is simple:" }, { "code": null, "e": 7539, "s": 7522, "text": "yarn add mermaid" }, { "code": null, "e": 7587, "s": 7539, "text": "If you don’t have a bundler, use the following:" }, { "code": null, "e": 7724, "s": 7587, "text": "<script src=\"https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js\"></script><script>mermaid.initialize({startOnLoad:true});</script>" }, { "code": null, "e": 7852, "s": 7724, "text": "This will make the Mermaid parser look for <div> tags with class Mermaid, and render them into diagrams. So you would use it as" }, { "code": null, "e": 7913, "s": 7852, "text": "<div class=\"mermaid\">graph TD;A-->B;A-->C;B-->D;C-->D;</div>" }, { "code": null, "e": 8040, "s": 7913, "text": "If you use GitHub pages, just add the following to your ‘header.html’, or download the file and source from the relative path:" }, { "code": null, "e": 8112, "s": 8040, "text": "<script src=\"https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js\">" }, { "code": null, "e": 8167, "s": 8112, "text": "Then, to include a diagram in your Markdown posts, use" }, { "code": null, "e": 8238, "s": 8167, "text": "```html<div class=\"mermaid\">graph TD;A-->B;A-->C;B-->D;C-->D;</div>```" }, { "code": null, "e": 8347, "s": 8238, "text": "Alternatively, if you have a Jekyll site that is not on GitHub pages, you can use the jekyll-mermaid plugin." }, { "code": null, "e": 8400, "s": 8347, "text": "If you use WordPress, there is a plugin for you too." }, { "code": null, "e": 8605, "s": 8400, "text": "May editors support Mermaid, including Atom, VIM and VS Code. I personally use VS Code, and the extension Markdown Preview Mermaid Support is very helpful in rendering the graphs in the markdown previews." }, { "code": null, "e": 8947, "s": 8605, "text": "The browser extension processes all the Markdown syntax found in a Markdown document, which means you can still locally view your graphs even if for example GitHub won’t render them to you. This extension works both on Chrome and Firefox. Of course, if you want other people to also see the diagram, they also have to download the extension." }, { "code": null, "e": 9114, "s": 8947, "text": "Mermaid-CLI exists so that you can directly create diagrams out of input files using the CLI. It works from within a Docker container, you can see how to use it here." }, { "code": null, "e": 9349, "s": 9114, "text": "Mermaid is such a fun tool to use once you get used to it, and it can save so much time and effort when trying to create diagrams without paper. I hope you found this short guide useful and it can save some time for your next diagram!" }, { "code": null, "e": 9379, "s": 9349, "text": "https://mermaid-js.github.io/" }, { "code": null, "e": 9424, "s": 9379, "text": "Blog — Use Mermaid syntax to create diagrams" }, { "code": null, "e": 9525, "s": 9424, "text": "Mermaid — Create Charts and Diagrams With Markdown-like Syntax | by Trevor Lasn | Better Programming" }, { "code": null, "e": 9637, "s": 9525, "text": "Making Diagrams Fun With Mermaid. Sometimes, a good diagram is the best... | by Ozan Tunca | Better Programming" } ]
Tryit Editor v3.7
Tryit: HTML background-color
[]
Android Rotate animations in Kotlin - GeeksforGeeks
03 Mar, 2022 Rotate animation is a special kind of animation in Android which controls the Rotation of an object. These type of animations are usually used by developers to give a feel to the user about the changes happening in the application like loading content, processing data, etc. By using the rotate animation effect, an object can be rotated in the X-Y plane of activity and it allows the rotation in both Clockwise and Anticlockwise direction. This example demonstrates the steps involved in implementing the clockwise and anticlockwise rotation animation to an image file. An image file will be added in the activity using ImageView. Note: The steps are performed on Android Studio version 4.0 Step 1: Create a New Project Click on File, then New => New Project.Select language as Kotlin.Select the minimum SDK as per your need. Click on File, then New => New Project. Select language as Kotlin. Select the minimum SDK as per your need. Step 2: Modify activity_main.xml file Below is the code for activity_main.xml file to add a TextView, ImageView, and 2 buttons in an activity. Filename: activity_main.xml 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" android:background="#168BC34A" tools:context=".MainActivity" > <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:fontFamily="@font/roboto" android:text="@string/heading" android:textAlignment="center" android:textColor="@android:color/holo_green_dark" android:textSize="36sp" android:textStyle="bold" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.050000012" /> <ImageView android:id="@+id/imageView" android:layout_width="243dp" android:layout_height="241dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/textView" app:layout_constraintVertical_bias="0.19999999" app:srcCompat="@drawable/logo" /> <Button android:id="@+id/clk_rotate_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="#AB4CAF50" android:fontFamily="@font/roboto" android:text="@string/clk_rotate_button_text" android:textSize="14sp" android:textStyle="bold" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.12" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/imageView" app:layout_constraintVertical_bias="0.7" /> <Button android:id="@+id/anticlk_rotate_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="#AB4CAF50" android:fontFamily="@font/roboto" android:text="@string/anticlk_rotate_button_text" android:textStyle="bold" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.78" app:layout_constraintStart_toEndOf="@+id/clk_rotate_button" app:layout_constraintTop_toBottomOf="@+id/imageView" app:layout_constraintVertical_bias="0.7" /></androidx.constraintlayout.widget.ConstraintLayout> Step 3: Define XML file for clockwise and anticlockwise rotation of the imageCreate a new directory in the res folder of the application and name it anim. In this directory create 2 Animation Resource File namely rotate_clockwise and rotate_anticlockwise. These 2 files are the XML file which holds the details of the animation. Below is the code for both the file. Filename: rotate_clockwise.xml XML <?xml version="1.0" encoding="utf-8"?><set xmlns:android="http://schemas.android.com/apk/res/android"> <rotate android:pivotX = "50%" android:pivotY = "50%" android:fromDegrees = "0" android:toDegrees = "360" android:duration = "2500"/> </set> Filename: rotate_anticlockwise.xml XML <?xml version="1.0" encoding="utf-8"?><set xmlns:android="http://schemas.android.com/apk/res/android"> <rotate android:pivotX = "50%" android:pivotY = "50%" android:fromDegrees = "360" android:toDegrees = "0" android:duration = "2500"/> </set> Step 4: Modify MainActivity.kt File Below is the code for MainActivity.kt file to load and start the animation on the ImageView widget according to the button clicked by the user. Filename: MainActivity.kt Java package com.example.androidrotateanimation import android.os.Bundleimport android.view.animation.AnimationUtilsimport android.widget.Buttonimport android.widget.ImageViewimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // assigning id of button which rotates // the image in clockwise direction val clk_button: Button = findViewById(R.id.clk_rotate_button) // assigning id of button which rotates // the image in anti-clockwise direction val anticlk_button: Button = findViewById(R.id.anticlk_rotate_button) // assigning id of imageview // which is to be rotated val image: ImageView = findViewById(R.id.imageView) // actions to be performed when // "rotate clockwise" button is clicked clk_button.setOnClickListener() { // loading the animation of // rotate_clockwise.xml file into a variable val clk_rotate = AnimationUtils.loadAnimation( this, R.anim.rotate_clockwise ) // assigning that animation to // the image and start animation image.startAnimation(clk_rotate) } // actions to be performed when // "rotate anticlockwise" button is clicked anticlk_button.setOnClickListener() { // loading the animation of // rotate_anticlockwise.xml file into a variable val anticlk_rotate = AnimationUtils.loadAnimation( this, R.anim.rotate_anticlockwise ) // assigning that animation to // the image and start animation image.startAnimation(anticlk_rotate) } }} simmytarika5 surindertarika1234 sweetyty Android-Animation Picked Android Kotlin Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Create and Add Data to SQLite Database in Android? Broadcast Receiver in Android With Example Android RecyclerView in Kotlin CardView in Android With Example Content Providers in Android with Example Broadcast Receiver in Android With Example Android UI Layouts Android RecyclerView in Kotlin Content Providers in Android with Example Retrofit with Kotlin Coroutine in Android
[ { "code": null, "e": 23825, "s": 23797, "text": "\n03 Mar, 2022" }, { "code": null, "e": 24267, "s": 23825, "text": "Rotate animation is a special kind of animation in Android which controls the Rotation of an object. These type of animations are usually used by developers to give a feel to the user about the changes happening in the application like loading content, processing data, etc. By using the rotate animation effect, an object can be rotated in the X-Y plane of activity and it allows the rotation in both Clockwise and Anticlockwise direction. " }, { "code": null, "e": 24458, "s": 24267, "text": "This example demonstrates the steps involved in implementing the clockwise and anticlockwise rotation animation to an image file. An image file will be added in the activity using ImageView." }, { "code": null, "e": 24518, "s": 24458, "text": "Note: The steps are performed on Android Studio version 4.0" }, { "code": null, "e": 24548, "s": 24518, "text": "Step 1: Create a New Project " }, { "code": null, "e": 24654, "s": 24548, "text": "Click on File, then New => New Project.Select language as Kotlin.Select the minimum SDK as per your need." }, { "code": null, "e": 24694, "s": 24654, "text": "Click on File, then New => New Project." }, { "code": null, "e": 24721, "s": 24694, "text": "Select language as Kotlin." }, { "code": null, "e": 24762, "s": 24721, "text": "Select the minimum SDK as per your need." }, { "code": null, "e": 24801, "s": 24762, "text": "Step 2: Modify activity_main.xml file " }, { "code": null, "e": 24906, "s": 24801, "text": "Below is the code for activity_main.xml file to add a TextView, ImageView, and 2 buttons in an activity." }, { "code": null, "e": 24934, "s": 24906, "text": "Filename: activity_main.xml" }, { "code": null, "e": 24938, "s": 24934, "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\" android:background=\"#168BC34A\" tools:context=\".MainActivity\" > <TextView android:id=\"@+id/textView\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:fontFamily=\"@font/roboto\" android:text=\"@string/heading\" android:textAlignment=\"center\" android:textColor=\"@android:color/holo_green_dark\" android:textSize=\"36sp\" android:textStyle=\"bold\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" app:layout_constraintVertical_bias=\"0.050000012\" /> <ImageView android:id=\"@+id/imageView\" android:layout_width=\"243dp\" android:layout_height=\"241dp\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toBottomOf=\"@+id/textView\" app:layout_constraintVertical_bias=\"0.19999999\" app:srcCompat=\"@drawable/logo\" /> <Button android:id=\"@+id/clk_rotate_button\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:background=\"#AB4CAF50\" android:fontFamily=\"@font/roboto\" android:text=\"@string/clk_rotate_button_text\" android:textSize=\"14sp\" android:textStyle=\"bold\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintHorizontal_bias=\"0.12\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toBottomOf=\"@+id/imageView\" app:layout_constraintVertical_bias=\"0.7\" /> <Button android:id=\"@+id/anticlk_rotate_button\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:background=\"#AB4CAF50\" android:fontFamily=\"@font/roboto\" android:text=\"@string/anticlk_rotate_button_text\" android:textStyle=\"bold\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintHorizontal_bias=\"0.78\" app:layout_constraintStart_toEndOf=\"@+id/clk_rotate_button\" app:layout_constraintTop_toBottomOf=\"@+id/imageView\" app:layout_constraintVertical_bias=\"0.7\" /></androidx.constraintlayout.widget.ConstraintLayout>", "e": 27770, "s": 24938, "text": null }, { "code": null, "e": 28137, "s": 27770, "text": "Step 3: Define XML file for clockwise and anticlockwise rotation of the imageCreate a new directory in the res folder of the application and name it anim. In this directory create 2 Animation Resource File namely rotate_clockwise and rotate_anticlockwise. These 2 files are the XML file which holds the details of the animation. Below is the code for both the file. " }, { "code": null, "e": 28168, "s": 28137, "text": "Filename: rotate_clockwise.xml" }, { "code": null, "e": 28172, "s": 28168, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><set xmlns:android=\"http://schemas.android.com/apk/res/android\"> <rotate android:pivotX = \"50%\" android:pivotY = \"50%\" android:fromDegrees = \"0\" android:toDegrees = \"360\" android:duration = \"2500\"/> </set>", "e": 28455, "s": 28172, "text": null }, { "code": null, "e": 28490, "s": 28455, "text": "Filename: rotate_anticlockwise.xml" }, { "code": null, "e": 28494, "s": 28490, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><set xmlns:android=\"http://schemas.android.com/apk/res/android\"> <rotate android:pivotX = \"50%\" android:pivotY = \"50%\" android:fromDegrees = \"360\" android:toDegrees = \"0\" android:duration = \"2500\"/> </set>", "e": 28777, "s": 28494, "text": null }, { "code": null, "e": 28957, "s": 28777, "text": "Step 4: Modify MainActivity.kt File Below is the code for MainActivity.kt file to load and start the animation on the ImageView widget according to the button clicked by the user." }, { "code": null, "e": 28983, "s": 28957, "text": "Filename: MainActivity.kt" }, { "code": null, "e": 28988, "s": 28983, "text": "Java" }, { "code": "package com.example.androidrotateanimation import android.os.Bundleimport android.view.animation.AnimationUtilsimport android.widget.Buttonimport android.widget.ImageViewimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // assigning id of button which rotates // the image in clockwise direction val clk_button: Button = findViewById(R.id.clk_rotate_button) // assigning id of button which rotates // the image in anti-clockwise direction val anticlk_button: Button = findViewById(R.id.anticlk_rotate_button) // assigning id of imageview // which is to be rotated val image: ImageView = findViewById(R.id.imageView) // actions to be performed when // \"rotate clockwise\" button is clicked clk_button.setOnClickListener() { // loading the animation of // rotate_clockwise.xml file into a variable val clk_rotate = AnimationUtils.loadAnimation( this, R.anim.rotate_clockwise ) // assigning that animation to // the image and start animation image.startAnimation(clk_rotate) } // actions to be performed when // \"rotate anticlockwise\" button is clicked anticlk_button.setOnClickListener() { // loading the animation of // rotate_anticlockwise.xml file into a variable val anticlk_rotate = AnimationUtils.loadAnimation( this, R.anim.rotate_anticlockwise ) // assigning that animation to // the image and start animation image.startAnimation(anticlk_rotate) } }}", "e": 30890, "s": 28988, "text": null }, { "code": null, "e": 30903, "s": 30890, "text": "simmytarika5" }, { "code": null, "e": 30922, "s": 30903, "text": "surindertarika1234" }, { "code": null, "e": 30931, "s": 30922, "text": "sweetyty" }, { "code": null, "e": 30949, "s": 30931, "text": "Android-Animation" }, { "code": null, "e": 30956, "s": 30949, "text": "Picked" }, { "code": null, "e": 30964, "s": 30956, "text": "Android" }, { "code": null, "e": 30971, "s": 30964, "text": "Kotlin" }, { "code": null, "e": 30979, "s": 30971, "text": "Android" }, { "code": null, "e": 31077, "s": 30979, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31086, "s": 31077, "text": "Comments" }, { "code": null, "e": 31099, "s": 31086, "text": "Old Comments" }, { "code": null, "e": 31157, "s": 31099, "text": "How to Create and Add Data to SQLite Database in Android?" }, { "code": null, "e": 31200, "s": 31157, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 31231, "s": 31200, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 31264, "s": 31231, "text": "CardView in Android With Example" }, { "code": null, "e": 31306, "s": 31264, "text": "Content Providers in Android with Example" }, { "code": null, "e": 31349, "s": 31306, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 31368, "s": 31349, "text": "Android UI Layouts" }, { "code": null, "e": 31399, "s": 31368, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 31441, "s": 31399, "text": "Content Providers in Android with Example" } ]
Convert an Array to a Circular Doubly Linked List in C++
In this tutorial, we will be discussing a program to convert an array to a circular doubly linked list. For this we will be provided with an array. Our task is to take the elements of the array and get it converted into a circular doubly linked list. Live Demo #include<iostream> using namespace std; //node structure for doubly linked list struct node{ int data; struct node *next; struct node *prev; }; //node creation struct node* getNode(){ return ((struct node *)malloc(sizeof(struct node))); } //printing the list int print_list(struct node *temp){ struct node *t = temp; if(temp == NULL) return 0; else { cout<<"List: "; while(temp->next != t) { cout<<temp->data<<" "; temp = temp->next; } cout<<temp->data; return 1; } } //converting array to linked list void convert_array(int arr[], int n, struct node **start) { //declaring new pointer struct node *newNode,*temp; int i; //moving through all the elements for(i=0;i<n;i++){ newNode = getNode(); newNode->data = arr[i]; if(i==0) { *start = newNode; newNode->prev = *start; newNode->next = *start; } else { //calculating the last node temp = (*start)->prev; temp->next = newNode; newNode->next = *start; newNode->prev = temp; temp = *start; temp->prev = newNode; } } } int main(){ int arr[] = {1,2,3,4,5}; int n = sizeof(arr) / sizeof(arr[0]); struct node *start = NULL; convert_array(arr, n, &start); print_list(start); return 0; } List: 1 2 3 4 5
[ { "code": null, "e": 1166, "s": 1062, "text": "In this tutorial, we will be discussing a program to convert an array to a circular doubly linked list." }, { "code": null, "e": 1313, "s": 1166, "text": "For this we will be provided with an array. Our task is to take the elements of the array and get it converted into a circular doubly linked list." }, { "code": null, "e": 1324, "s": 1313, "text": " Live Demo" }, { "code": null, "e": 2686, "s": 1324, "text": "#include<iostream>\nusing namespace std;\n//node structure for doubly linked list\nstruct node{\n int data;\n struct node *next;\n struct node *prev;\n};\n//node creation\nstruct node* getNode(){\n return ((struct node *)malloc(sizeof(struct node)));\n}\n//printing the list\nint print_list(struct node *temp){\n struct node *t = temp;\n if(temp == NULL)\n return 0;\n else {\n cout<<\"List: \";\n while(temp->next != t) {\n cout<<temp->data<<\" \";\n temp = temp->next;\n }\n cout<<temp->data;\n return 1;\n }\n}\n//converting array to linked list\nvoid convert_array(int arr[], int n, struct node **start) {\n //declaring new pointer\n struct node *newNode,*temp;\n int i;\n //moving through all the elements\n for(i=0;i<n;i++){\n newNode = getNode();\n newNode->data = arr[i];\n if(i==0) {\n *start = newNode;\n newNode->prev = *start;\n newNode->next = *start;\n } else {\n //calculating the last node\n temp = (*start)->prev;\n temp->next = newNode;\n newNode->next = *start;\n newNode->prev = temp;\n temp = *start;\n temp->prev = newNode;\n }\n }\n}\nint main(){\n int arr[] = {1,2,3,4,5};\n int n = sizeof(arr) / sizeof(arr[0]);\n struct node *start = NULL;\n convert_array(arr, n, &start);\n print_list(start);\n return 0;\n}" }, { "code": null, "e": 2702, "s": 2686, "text": "List: 1 2 3 4 5" } ]
Music Source Separation with Spleeter on Google Colab | by Sameeha Afrulbasha | Towards Data Science
Music recordings can come with a variety of instrumental tracks, such as lead vocals, piano, drums, bass, etc. Each track is called a stem and, for most people, isolating those stems comes quite naturally when they are listening to a song. For example, if you listen to Old Time Rock n Roll, you will hear the piano stem at the beginning, Bob Seger’s lead vocal stem, and the drum stem all come together and you can follow each stem throughout the song. However, it’s not possible to hear a singular stem without it being distorted by the many other stems. This is where Spleeter comes into play... Spleeter is a source separation library which the music-streaming company Deezer released in 2019. For those unfamiliar with Deezer, it is very similar to Spotify and mostly used in France. Spleeter is the closest we can get to extracting individual tracks of a song and it’s mostly used by researchers working on Music Information Retrieval. Deezer uses Spleeter for their own research and they wanted to release something accessible for others to use in their own ways as well. Besides research, you can do other things with Spleeter: make acapellas/instrumentals (karaoke as well) use it to extract acoustics/instrumentals to create your own version of a song you like (not copy, of course) use it to learn how a song comes together from the individual stems (source separation makes the stems sound much less distorted) play around mixing different tracks of artists you like; create mashups if you play piano, drums, or bass instruments, you can extract those specific tracks to hear and understand them in clarity and play/create something similar To follow along or execute this code yourself, you can find my Spleeter Google Colab in Github. I originally tried executing this on Jupyter Notebook but for reasons I am not sure of yet, it didn’t work but it worked fine on Google Colab. If you try this on a Python application, let me know if it works for you so I can figure out what I’m missing! I installed an imported 3 important libraries: youtube-dl, Spleeter, and pydub. pydub: module that works with audio files; specifically .wav files (Spleeter yields each stem as a .wav file) youtube-dl: for downloading video and audio files from youtube Spleeter: extracting the music stems You also want to import “Audio” from the IPython.display object to create an Audio object of your downloaded song as well as the display function to display your audio. import spleeterimport youtube_dlimport pydubimport IPython.display as ipdfrom IPython.display import Audio, displayfrom IPython.display import HTML Next, you have to create a variable to store the YouTube video’s arguments such as the “bestaudio” feature and the output name you want it to have. You can learn more about the different outputs you can get and documentation for the youtube-dl library here. ydl_args = { 'format' = 'bestaudio/best' 'outtmpl' = 'filename.mp3'} Next, I used the instance of youtube_dl called YoutubeDL to access those arguments and download them. ydl = youtube_dl.YoutubeDL(ydl_args)ydl.download(['url']) This next step is where Spleeter does its job. For more information about its documentation, go here. Spleeter gives you 3 options depending on how many stems you want to extract: 2stems, 4 stems, and 5 stems. 2stems = vocals and accompaniment 4stems = vocals, drums, bass, and other 5stems = vocals, drums, bass, piano, and other I used 4 stems for my project because I knew the song I chose mostly had vocals and drums. !spleeter separate -p spleeter:4stems -o output/ entertainment.mp3 “-o” stands for the output file name and “-p” is for providing the model settings (4stems). When you execute the Spleeter function, each stem will be written as a .wav file. Since I personally wanted to work with .mp3 files, I imported an instance of pydub called “AudioSegment” and its purpose is to read .wav audio files. After this, we can export that file as a .mp3 file. from pydub import AudioSegmentsound = AudioSegment.from_wav("output/filename/vocals.wav")sound.export("output/filename/vocals.mp3", format="mp3") If you repeat the process above for each stem (vocals, bass, drum, etc.), the last thing left to do is use IPython.display (shortened to ipd) to display your final stems. It should look something like this: That’s all there is! How you want to listen and play around with these files is up to you. I uploaded my stems to the app Audacity because it displays each stem separately and it allows you to turn on or turn off certain stems or play them all together. Here’s what it looks like if you want to use Audacity as well: I hope this provided a clear image of what Spleeter does and how to use it. If you are going to publish anything (music/audio) that you used with Spleeter, make sure to do it with the permission of the owner! I enjoyed this project a lot, however, I noticed that Spleeter is not really talked about so part of my intent for this article is to show easily accessible this is to everyone and spread the word. This could also serve as perfect Data Science and introduction to Artificial Intelligence for beginners who love the intricacies of music.
[ { "code": null, "e": 771, "s": 172, "text": "Music recordings can come with a variety of instrumental tracks, such as lead vocals, piano, drums, bass, etc. Each track is called a stem and, for most people, isolating those stems comes quite naturally when they are listening to a song. For example, if you listen to Old Time Rock n Roll, you will hear the piano stem at the beginning, Bob Seger’s lead vocal stem, and the drum stem all come together and you can follow each stem throughout the song. However, it’s not possible to hear a singular stem without it being distorted by the many other stems. This is where Spleeter comes into play..." }, { "code": null, "e": 1251, "s": 771, "text": "Spleeter is a source separation library which the music-streaming company Deezer released in 2019. For those unfamiliar with Deezer, it is very similar to Spotify and mostly used in France. Spleeter is the closest we can get to extracting individual tracks of a song and it’s mostly used by researchers working on Music Information Retrieval. Deezer uses Spleeter for their own research and they wanted to release something accessible for others to use in their own ways as well." }, { "code": null, "e": 1308, "s": 1251, "text": "Besides research, you can do other things with Spleeter:" }, { "code": null, "e": 1355, "s": 1308, "text": "make acapellas/instrumentals (karaoke as well)" }, { "code": null, "e": 1465, "s": 1355, "text": "use it to extract acoustics/instrumentals to create your own version of a song you like (not copy, of course)" }, { "code": null, "e": 1595, "s": 1465, "text": "use it to learn how a song comes together from the individual stems (source separation makes the stems sound much less distorted)" }, { "code": null, "e": 1667, "s": 1595, "text": "play around mixing different tracks of artists you like; create mashups" }, { "code": null, "e": 1825, "s": 1667, "text": "if you play piano, drums, or bass instruments, you can extract those specific tracks to hear and understand them in clarity and play/create something similar" }, { "code": null, "e": 2175, "s": 1825, "text": "To follow along or execute this code yourself, you can find my Spleeter Google Colab in Github. I originally tried executing this on Jupyter Notebook but for reasons I am not sure of yet, it didn’t work but it worked fine on Google Colab. If you try this on a Python application, let me know if it works for you so I can figure out what I’m missing!" }, { "code": null, "e": 2255, "s": 2175, "text": "I installed an imported 3 important libraries: youtube-dl, Spleeter, and pydub." }, { "code": null, "e": 2365, "s": 2255, "text": "pydub: module that works with audio files; specifically .wav files (Spleeter yields each stem as a .wav file)" }, { "code": null, "e": 2428, "s": 2365, "text": "youtube-dl: for downloading video and audio files from youtube" }, { "code": null, "e": 2465, "s": 2428, "text": "Spleeter: extracting the music stems" }, { "code": null, "e": 2634, "s": 2465, "text": "You also want to import “Audio” from the IPython.display object to create an Audio object of your downloaded song as well as the display function to display your audio." }, { "code": null, "e": 2782, "s": 2634, "text": "import spleeterimport youtube_dlimport pydubimport IPython.display as ipdfrom IPython.display import Audio, displayfrom IPython.display import HTML" }, { "code": null, "e": 3040, "s": 2782, "text": "Next, you have to create a variable to store the YouTube video’s arguments such as the “bestaudio” feature and the output name you want it to have. You can learn more about the different outputs you can get and documentation for the youtube-dl library here." }, { "code": null, "e": 3111, "s": 3040, "text": "ydl_args = { 'format' = 'bestaudio/best' 'outtmpl' = 'filename.mp3'}" }, { "code": null, "e": 3213, "s": 3111, "text": "Next, I used the instance of youtube_dl called YoutubeDL to access those arguments and download them." }, { "code": null, "e": 3271, "s": 3213, "text": "ydl = youtube_dl.YoutubeDL(ydl_args)ydl.download(['url'])" }, { "code": null, "e": 3481, "s": 3271, "text": "This next step is where Spleeter does its job. For more information about its documentation, go here. Spleeter gives you 3 options depending on how many stems you want to extract: 2stems, 4 stems, and 5 stems." }, { "code": null, "e": 3515, "s": 3481, "text": "2stems = vocals and accompaniment" }, { "code": null, "e": 3555, "s": 3515, "text": "4stems = vocals, drums, bass, and other" }, { "code": null, "e": 3602, "s": 3555, "text": "5stems = vocals, drums, bass, piano, and other" }, { "code": null, "e": 3693, "s": 3602, "text": "I used 4 stems for my project because I knew the song I chose mostly had vocals and drums." }, { "code": null, "e": 3760, "s": 3693, "text": "!spleeter separate -p spleeter:4stems -o output/ entertainment.mp3" }, { "code": null, "e": 3852, "s": 3760, "text": "“-o” stands for the output file name and “-p” is for providing the model settings (4stems)." }, { "code": null, "e": 4136, "s": 3852, "text": "When you execute the Spleeter function, each stem will be written as a .wav file. Since I personally wanted to work with .mp3 files, I imported an instance of pydub called “AudioSegment” and its purpose is to read .wav audio files. After this, we can export that file as a .mp3 file." }, { "code": null, "e": 4282, "s": 4136, "text": "from pydub import AudioSegmentsound = AudioSegment.from_wav(\"output/filename/vocals.wav\")sound.export(\"output/filename/vocals.mp3\", format=\"mp3\")" }, { "code": null, "e": 4489, "s": 4282, "text": "If you repeat the process above for each stem (vocals, bass, drum, etc.), the last thing left to do is use IPython.display (shortened to ipd) to display your final stems. It should look something like this:" }, { "code": null, "e": 4806, "s": 4489, "text": "That’s all there is! How you want to listen and play around with these files is up to you. I uploaded my stems to the app Audacity because it displays each stem separately and it allows you to turn on or turn off certain stems or play them all together. Here’s what it looks like if you want to use Audacity as well:" } ]
Adding binary strings together JavaScript
We are required to write a JavaScript function that takes in two binary strings. The function should return the sum of those two-binary string as another binary string. For example − If the two strings are − const str1 = "1010"; const str2 = "1011"; Then the output should be − const output = '10101'; const str1 = "1010"; const str2 = "1011"; const addBinary = (str1, str2) => { let carry = 0; const res = []; let l1 = str1.length, l2 = str2.length; for (let i = l1 - 1, j = l2 - 1; 0 <= i || 0 <= j; --i, --j) { let a = 0 <= i ? Number(str1[i]) : 0, b = 0 <= j ? Number(str2[j]) : 0; res.push((a + b + carry) % 2); carry = 1 < a + b + carry; }; if (carry){ res.push(1); } return res.reverse().join(''); }; console.log(addBinary(str1, str2)); And the output in the console will be − 10101
[ { "code": null, "e": 1231, "s": 1062, "text": "We are required to write a JavaScript function that takes in two binary strings. The function should return the sum of those two-binary string as another binary string." }, { "code": null, "e": 1245, "s": 1231, "text": "For example −" }, { "code": null, "e": 1270, "s": 1245, "text": "If the two strings are −" }, { "code": null, "e": 1312, "s": 1270, "text": "const str1 = \"1010\";\nconst str2 = \"1011\";" }, { "code": null, "e": 1340, "s": 1312, "text": "Then the output should be −" }, { "code": null, "e": 1364, "s": 1340, "text": "const output = '10101';" }, { "code": null, "e": 1860, "s": 1364, "text": "const str1 = \"1010\";\nconst str2 = \"1011\";\nconst addBinary = (str1, str2) => {\n let carry = 0;\n const res = [];\n let l1 = str1.length, l2 = str2.length;\n for (let i = l1 - 1, j = l2 - 1; 0 <= i || 0 <= j; --i, --j) {\n let a = 0 <= i ? Number(str1[i]) : 0,\n b = 0 <= j ? Number(str2[j]) : 0;\n res.push((a + b + carry) % 2);\n carry = 1 < a + b + carry;\n };\n if (carry){\n res.push(1);\n }\n return res.reverse().join('');\n};\nconsole.log(addBinary(str1, str2));" }, { "code": null, "e": 1900, "s": 1860, "text": "And the output in the console will be −" }, { "code": null, "e": 1906, "s": 1900, "text": "10101" } ]
Toppers Of Class | Practice | GeeksforGeeks
There is a class of N students and the task is to find the top K marks scorers. You need to print the index of the toppers of the class which will be same as the index of the student in the input array (use 0-based indexing). First print the index of the students having highest marks then the students with second highest and so on. If there are more than one students having same marks then print their indices in ascending order.Suppose k = 2 and the students having highest marks have indices 0 and 5 and students having second highest marks have indices 6 and 7 then output will be 0 5 6 7. Example 1: Input: N=5 K=3 arr[] = { 2, 2, 1, 3, 1 } Output: 3 0 1 2 4 Explanation: Topper with 3 marks is present at 3rd index, 2 marks is present at 0th index and next at 1st index. 1 marks is present at 2 and 4. Example 2: Input: N=4 K=1 arr[] = { 1, 2, 3, 4 } Output: 3 Explanation: The highest marks is at index 3. Your Task: Since this is a function problem. You don't need to take any input, as it is already accomplished by the driver code. You just need to complete the function kTop() that takes array A and integer N as parameters and change the given array according to the given conditions. You do not have to return anything Expected Time Complexity: O(NlogN). Expected Auxiliary Space: O(1). Constraints: 1 ≤ N ≤ 106 1 ≤ M ≤ 106 0 nmnishant3 months ago C++ [Only 3 lines solution]bool comp(node n1, node n2){ if(n1.marks != n2.marks) return n1.marks > n2.marks; else return n1.index < n2.index;} void kTop(node a[],int n){ sort(a, a+n, comp);} +1 amanshakya0073 months ago // JAVA SIMPLE CODE class pair implements Comparable<pair>{ int marks; int index; pair(int marks,int index){ this.marks = marks; this.index = index; } public int compareTo(pair o){ if(this.marks == o.marks){ return this.index - o.index; } else{ return o.marks - this.marks; } } } void kTop(node a[],int n) { pair[] arr = new pair[n]; for(int i=0;i<a.length;i++){ node d = a[i]; arr[i] = new pair(d.marks,d.index); } Arrays.sort(arr); for(int i=0;i<arr.length;i++){ pair p = arr[i]; node rr = new node(); rr.setMarks(p.marks); rr.setIndex(p.index); a[i] = rr; } } +1 badgujarsachin834 months ago bool com (node a,node b){ if(a.marks==b.marks){ return a.index<b.index; } return a.marks>b.marks; } void kTop(node a[],int n) { // Your code goes here sort(a,a+n,com); } +3 mayurmadhwani6 months ago bool cmp(node a,node b){ if(a.marks == b.marks) return a.index<b.index; return a.marks>b.marks; } void kTop(node a[],int n) { sort(a,a+n,cmp); } +1 admiral_general_aladeen6 months ago Fix the driver code in python. a.sort(key=lambda x:(-x[0],x[1])) This is simple solution but GFG never thinks of fixing the driver codes. 0 rahulsaidileep17 months ago I think the default given code (python) is incorrect 0 mjohnmwangi7 months ago k is not available in the args for kTop 0 sujankumarmitra7 months ago I think there's some error in the driver code. Code: class GFG { static final Comparator<node> CMP = Comparator .comparing((node n)-> n.marks,Comparator.reverseOrder()) .thenComparing(n -> n.index); void kTop(node a[],int n) { Arrays.sort(a, 0, n, CMP); } } Output: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3306 out of bounds for length 3306 at Array.main(File.java:53) 0 noobcoderdj8 months ago noobcoderdj c++ one liner void kTop(node a[],int n){ sort(a, a+n, [](struct node x, struct node y){ if(x.marks==y.marks) return x.index<y.index; return="" x.marks="">y.marks; });} +1 Rohit negi11 months ago Rohit negi bool compare(node n1, node n2){ if(n1.marks>n2.marks) return 1; else if((n1.marks==n2.marks)&&(n1.index<n2.index)) return="" 1;="" return="" 0;="" }="" void="" ktop(node="" a[],int="" n)="" {="" your="" code="" goes="" here="" sort(a,a+n,compare);="" cout<<"1";="" }=""> 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": 822, "s": 226, "text": "There is a class of N students and the task is to find the top K marks scorers. You need to print the index of the toppers of the class which will be same as the index of the student in the input array (use 0-based indexing). First print the index of the students having highest marks then the students with second highest and so on. If there are more than one students having same marks then print their indices in ascending order.Suppose k = 2 and the students having highest marks have indices 0 and 5 and students having second highest marks have indices 6 and 7 then output will be 0 5 6 7." }, { "code": null, "e": 833, "s": 822, "text": "Example 1:" }, { "code": null, "e": 1040, "s": 833, "text": "Input:\nN=5 K=3\narr[] = { 2, 2, 1, 3, 1 }\nOutput: 3 0 1 2 4\nExplanation: Topper with 3 marks is present \nat 3rd index, 2 marks is present at 0th \nindex and next at 1st index. 1 marks is present \nat 2 and 4.\n" }, { "code": null, "e": 1051, "s": 1040, "text": "Example 2:" }, { "code": null, "e": 1146, "s": 1051, "text": "Input:\nN=4 K=1\narr[] = { 1, 2, 3, 4 } \nOutput: 3\nExplanation: The highest marks is at index 3." }, { "code": null, "e": 1465, "s": 1146, "text": "Your Task:\nSince this is a function problem. You don't need to take any input, as it is already accomplished by the driver code. You just need to complete the function kTop() that takes array A and integer N as parameters and change the given array according to the given conditions. You do not have to return anything" }, { "code": null, "e": 1535, "s": 1467, "text": "Expected Time Complexity: O(NlogN).\nExpected Auxiliary Space: O(1)." }, { "code": null, "e": 1574, "s": 1537, "text": "Constraints:\n1 ≤ N ≤ 106\n1 ≤ M ≤ 106" }, { "code": null, "e": 1576, "s": 1574, "text": "0" }, { "code": null, "e": 1598, "s": 1576, "text": "nmnishant3 months ago" }, { "code": null, "e": 1745, "s": 1598, "text": "C++ [Only 3 lines solution]bool comp(node n1, node n2){ if(n1.marks != n2.marks) return n1.marks > n2.marks; else return n1.index < n2.index;}" }, { "code": null, "e": 1796, "s": 1745, "text": "void kTop(node a[],int n){ sort(a, a+n, comp);} " }, { "code": null, "e": 1799, "s": 1796, "text": "+1" }, { "code": null, "e": 1825, "s": 1799, "text": "amanshakya0073 months ago" }, { "code": null, "e": 2697, "s": 1825, "text": "// JAVA SIMPLE CODE\nclass pair implements Comparable<pair>{\n int marks;\n int index;\n pair(int marks,int index){\n this.marks = marks;\n this.index = index;\n }\n public int compareTo(pair o){\n if(this.marks == o.marks){\n return this.index - o.index;\n }\n else{\n return o.marks - this.marks;\n }\n }\n }\n void kTop(node a[],int n)\n {\n pair[] arr = new pair[n];\n for(int i=0;i<a.length;i++){\n node d = a[i];\n arr[i] = new pair(d.marks,d.index);\n }\n Arrays.sort(arr);\n for(int i=0;i<arr.length;i++){\n pair p = arr[i];\n node rr = new node();\n rr.setMarks(p.marks);\n rr.setIndex(p.index);\n a[i] = rr;\n }\n \n }" }, { "code": null, "e": 2700, "s": 2697, "text": "+1" }, { "code": null, "e": 2729, "s": 2700, "text": "badgujarsachin834 months ago" }, { "code": null, "e": 2927, "s": 2729, "text": "bool com (node a,node b){\n if(a.marks==b.marks){\n return a.index<b.index;\n }\n return a.marks>b.marks;\n}\nvoid kTop(node a[],int n)\n{\n // Your code goes here\n sort(a,a+n,com);\n}" }, { "code": null, "e": 2930, "s": 2927, "text": "+3" }, { "code": null, "e": 2956, "s": 2930, "text": "mayurmadhwani6 months ago" }, { "code": null, "e": 3147, "s": 2956, "text": "bool cmp(node a,node b){\n \n if(a.marks == b.marks)\n return a.index<b.index;\n \n return a.marks>b.marks;\n \n}\n\nvoid kTop(node a[],int n)\n{\n \n sort(a,a+n,cmp);\n \n}" }, { "code": null, "e": 3150, "s": 3147, "text": "+1" }, { "code": null, "e": 3186, "s": 3150, "text": "admiral_general_aladeen6 months ago" }, { "code": null, "e": 3217, "s": 3186, "text": "Fix the driver code in python." }, { "code": null, "e": 3251, "s": 3217, "text": "a.sort(key=lambda x:(-x[0],x[1]))" }, { "code": null, "e": 3324, "s": 3251, "text": "This is simple solution but GFG never thinks of fixing the driver codes." }, { "code": null, "e": 3326, "s": 3324, "text": "0" }, { "code": null, "e": 3354, "s": 3326, "text": "rahulsaidileep17 months ago" }, { "code": null, "e": 3407, "s": 3354, "text": "I think the default given code (python) is incorrect" }, { "code": null, "e": 3409, "s": 3407, "text": "0" }, { "code": null, "e": 3433, "s": 3409, "text": "mjohnmwangi7 months ago" }, { "code": null, "e": 3474, "s": 3433, "text": " k is not available in the args for kTop" }, { "code": null, "e": 3476, "s": 3474, "text": "0" }, { "code": null, "e": 3504, "s": 3476, "text": "sujankumarmitra7 months ago" }, { "code": null, "e": 3551, "s": 3504, "text": "I think there's some error in the driver code." }, { "code": null, "e": 3561, "s": 3555, "text": "Code:" }, { "code": null, "e": 3832, "s": 3561, "text": "class GFG\n{\n \n static final Comparator<node> CMP = Comparator\n .comparing((node n)-> n.marks,Comparator.reverseOrder())\n .thenComparing(n -> n.index);\n \n void kTop(node a[],int n)\n {\n Arrays.sort(a, 0, n, CMP);\n }\n}" }, { "code": null, "e": 3840, "s": 3832, "text": "Output:" }, { "code": null, "e": 3978, "s": 3840, "text": "Exception in thread \"main\" java.lang.ArrayIndexOutOfBoundsException: Index 3306 out of bounds for length 3306 at Array.main(File.java:53)" }, { "code": null, "e": 3980, "s": 3978, "text": "0" }, { "code": null, "e": 4004, "s": 3980, "text": "noobcoderdj8 months ago" }, { "code": null, "e": 4016, "s": 4004, "text": "noobcoderdj" }, { "code": null, "e": 4030, "s": 4016, "text": "c++ one liner" }, { "code": null, "e": 4208, "s": 4030, "text": "void kTop(node a[],int n){ sort(a, a+n, [](struct node x, struct node y){ if(x.marks==y.marks) return x.index<y.index; return=\"\" x.marks=\"\">y.marks; });}" }, { "code": null, "e": 4211, "s": 4208, "text": "+1" }, { "code": null, "e": 4235, "s": 4211, "text": "Rohit negi11 months ago" }, { "code": null, "e": 4246, "s": 4235, "text": "Rohit negi" }, { "code": null, "e": 4526, "s": 4246, "text": "bool compare(node n1, node n2){ if(n1.marks>n2.marks) return 1; else if((n1.marks==n2.marks)&&(n1.index<n2.index)) return=\"\" 1;=\"\" return=\"\" 0;=\"\" }=\"\" void=\"\" ktop(node=\"\" a[],int=\"\" n)=\"\" {=\"\" your=\"\" code=\"\" goes=\"\" here=\"\" sort(a,a+n,compare);=\"\" cout<<\"1\";=\"\" }=\"\">" }, { "code": null, "e": 4672, "s": 4526, "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": 4708, "s": 4672, "text": " Login to access your submissions. " }, { "code": null, "e": 4718, "s": 4708, "text": "\nProblem\n" }, { "code": null, "e": 4728, "s": 4718, "text": "\nContest\n" }, { "code": null, "e": 4791, "s": 4728, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 4939, "s": 4791, "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": 5147, "s": 4939, "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": 5253, "s": 5147, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Jdbc Select Program Example | executeQuery() Example in JDBC
PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC EXCEPTIONS COLLECTIONS SWING JDBC JAVA 8 SPRING SPRING BOOT HIBERNATE PYTHON PHP JQUERY PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws In this tutorial, we are going to understand the basic JDBC select program example. As we already discussed in the previous tutorials steps to create jdbc example, to do the select operation in JDBC we need to use the executeQuery() method. While Executing the executeQuery() method, we need to keep in mind some important facts. We can call the executeQuery() method on statement object to select the data from the database. executeQuery() method returns ResultSet object. The ResultSet object contains rows of table. The ResultSet object maintains the cursor, and it is initially positioned at before of the first row. To read the data of row by row, we need to move the curson to the next row by calling next() method available in ResultSet. The next() method returns a boolean value, either true or false. When there is a row available in ResultSet object then next() returns true if no more rows then it returns false. By default ResultSet object is non-scrollable. That means, a cursor of the ResultSet object can be moved in forward direction only. If require, we can convert a ResultSet object into Scrollable type. If the ResultSet object is scrollable then the cursor will be moved in forward and backward direction. One statement object can create only one ResultSet object at a time. If another ResultSet object is created by same statement object, then it automatically closes the previous ResultSet object. ResultSet rs1 = stmt.executeQuery("select * from emp); ResultSet rs2 = stmt.executeQuery("select * from dept); Here rs1 is closed automatically, when rs2 is created. package com.onlinetutorialspoint.jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class Jdbc_Select_Example { public static void main(String[] args) throws Exception { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con = DriverManager.getConnection( "jdbc:mysql://localhost:3306/onlinetutorialspoint", "root", "123456"); Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("select * from student"); while (rs.next()) { System.out.println(rs.getInt(1) + " " + rs.getString(2) + " " + rs.getString(3)); } rs.close(); stmt.close(); con.close(); } } Output : 101 Chandra hyd 102 Shekhar hyd Happy Learning 🙂 JDBC Interview Questions and Answers Hibernate Query Language (HQL) Select Operation JDBC Insert Program Example JDBC Update Program Example JDBC Delete Program Example JDBC PreparedStatement Example Program Step by Step JDBC Program Example Insert an Image using JDBC in Mysql DB Read an Image in JDBC Example CallableStatement in jdbc Example ResultSetMetaData in JDBC Example DatabaseMetaData in JDBC Example Transaction Management in JDBC Example Batch Processing in JDBC Example JDBC Connection with Properties file JDBC Interview Questions and Answers Hibernate Query Language (HQL) Select Operation JDBC Insert Program Example JDBC Update Program Example JDBC Delete Program Example JDBC PreparedStatement Example Program Step by Step JDBC Program Example Insert an Image using JDBC in Mysql DB Read an Image in JDBC Example CallableStatement in jdbc Example ResultSetMetaData in JDBC Example DatabaseMetaData in JDBC Example Transaction Management in JDBC Example Batch Processing in JDBC Example JDBC Connection with Properties file Δ JDBC Driver Types Step by Step JDBC Program JDBC Select Program JDBC Insert Program JDBC Update Program JDBC Delete Program JDBC Connection – Properties File JDBC PreparedStatement Program JDBC – CallableStatement Example JDBC – Read an Image from DB JDBC – Insert an Image in DB JDBC – Updatable ResultSet JDBC – Scrollable ResultSet JDBC – ResultSetMetaData JDBC – DatabaseMetaData JDBC – Transaction Management JDBC – Batch Processing JDBC Interview Questions
[ { "code": null, "e": 158, "s": 123, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 172, "s": 158, "text": "Java Examples" }, { "code": null, "e": 183, "s": 172, "text": "C Examples" }, { "code": null, "e": 195, "s": 183, "text": "C Tutorials" }, { "code": null, "e": 199, "s": 195, "text": "aws" }, { "code": null, "e": 234, "s": 199, "text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC" }, { "code": null, "e": 245, "s": 234, "text": "EXCEPTIONS" }, { "code": null, "e": 257, "s": 245, "text": "COLLECTIONS" }, { "code": null, "e": 263, "s": 257, "text": "SWING" }, { "code": null, "e": 268, "s": 263, "text": "JDBC" }, { "code": null, "e": 275, "s": 268, "text": "JAVA 8" }, { "code": null, "e": 282, "s": 275, "text": "SPRING" }, { "code": null, "e": 294, "s": 282, "text": "SPRING BOOT" }, { "code": null, "e": 304, "s": 294, "text": "HIBERNATE" }, { "code": null, "e": 311, "s": 304, "text": "PYTHON" }, { "code": null, "e": 315, "s": 311, "text": "PHP" }, { "code": null, "e": 322, "s": 315, "text": "JQUERY" }, { "code": null, "e": 357, "s": 322, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 371, "s": 357, "text": "Java Examples" }, { "code": null, "e": 382, "s": 371, "text": "C Examples" }, { "code": null, "e": 394, "s": 382, "text": "C Tutorials" }, { "code": null, "e": 398, "s": 394, "text": "aws" }, { "code": null, "e": 639, "s": 398, "text": "In this tutorial, we are going to understand the basic JDBC select program example. As we already discussed in the previous tutorials steps to create jdbc example, to do the select operation in JDBC we need to use the executeQuery() method." }, { "code": null, "e": 728, "s": 639, "text": "While Executing the executeQuery() method, we need to keep in mind some important facts." }, { "code": null, "e": 824, "s": 728, "text": "We can call the executeQuery() method on statement object to select the data from the database." }, { "code": null, "e": 872, "s": 824, "text": "executeQuery() method returns ResultSet object." }, { "code": null, "e": 917, "s": 872, "text": "The ResultSet object contains rows of table." }, { "code": null, "e": 1019, "s": 917, "text": "The ResultSet object maintains the cursor, and it is initially positioned at before of the first row." }, { "code": null, "e": 1143, "s": 1019, "text": "To read the data of row by row, we need to move the curson to the next row by calling next() method available in ResultSet." }, { "code": null, "e": 1208, "s": 1143, "text": "The next() method returns a boolean value, either true or false." }, { "code": null, "e": 1322, "s": 1208, "text": "When there is a row available in ResultSet object then next() returns true if no more rows then it returns false." }, { "code": null, "e": 1454, "s": 1322, "text": "By default ResultSet object is non-scrollable. That means, a cursor of the ResultSet object can be moved in forward direction only." }, { "code": null, "e": 1625, "s": 1454, "text": "If require, we can convert a ResultSet object into Scrollable type. If the ResultSet object is scrollable then the cursor will be moved in forward and backward direction." }, { "code": null, "e": 1819, "s": 1625, "text": "One statement object can create only one ResultSet object at a time. If another ResultSet object is created by same statement object, then it automatically closes the previous ResultSet object." }, { "code": null, "e": 1930, "s": 1819, "text": "ResultSet rs1 = stmt.executeQuery(\"select * from emp);\nResultSet rs2 = stmt.executeQuery(\"select * from dept);" }, { "code": null, "e": 1987, "s": 1932, "text": "Here rs1 is closed automatically, when rs2 is created." }, { "code": null, "e": 2799, "s": 1987, "text": "package com.onlinetutorialspoint.jdbc; \n \nimport java.sql.Connection; \nimport java.sql.DriverManager; \nimport java.sql.ResultSet; \nimport java.sql.Statement; \n \npublic class Jdbc_Select_Example { \n \n public static void main(String[] args) throws Exception { \n Class.forName(\"sun.jdbc.odbc.JdbcOdbcDriver\"); \n Connection con = DriverManager.getConnection( \n \"jdbc:mysql://localhost:3306/onlinetutorialspoint\", \"root\", \"123456\"); \n Statement stmt = con.createStatement(); \n ResultSet rs = stmt.executeQuery(\"select * from student\"); \n while (rs.next()) { \n System.out.println(rs.getInt(1) + \" \" + rs.getString(2) + \" \" \n + rs.getString(3)); \n } \n rs.close(); \n stmt.close(); \n con.close(); \n } \n \n} " }, { "code": null, "e": 2808, "s": 2799, "text": "Output :" }, { "code": null, "e": 2840, "s": 2808, "text": "101 Chandra hyd\n102 Shekhar hyd" }, { "code": null, "e": 2857, "s": 2840, "text": "Happy Learning 🙂" }, { "code": null, "e": 3380, "s": 2857, "text": "\nJDBC Interview Questions and Answers\nHibernate Query Language (HQL) Select Operation\nJDBC Insert Program Example\nJDBC Update Program Example\nJDBC Delete Program Example\nJDBC PreparedStatement Example Program\nStep by Step JDBC Program Example\nInsert an Image using JDBC in Mysql DB\nRead an Image in JDBC Example\nCallableStatement in jdbc Example\nResultSetMetaData in JDBC Example\nDatabaseMetaData in JDBC Example\nTransaction Management in JDBC Example\nBatch Processing in JDBC Example\nJDBC Connection with Properties file\n" }, { "code": null, "e": 3417, "s": 3380, "text": "JDBC Interview Questions and Answers" }, { "code": null, "e": 3465, "s": 3417, "text": "Hibernate Query Language (HQL) Select Operation" }, { "code": null, "e": 3493, "s": 3465, "text": "JDBC Insert Program Example" }, { "code": null, "e": 3521, "s": 3493, "text": "JDBC Update Program Example" }, { "code": null, "e": 3549, "s": 3521, "text": "JDBC Delete Program Example" }, { "code": null, "e": 3588, "s": 3549, "text": "JDBC PreparedStatement Example Program" }, { "code": null, "e": 3622, "s": 3588, "text": "Step by Step JDBC Program Example" }, { "code": null, "e": 3661, "s": 3622, "text": "Insert an Image using JDBC in Mysql DB" }, { "code": null, "e": 3691, "s": 3661, "text": "Read an Image in JDBC Example" }, { "code": null, "e": 3725, "s": 3691, "text": "CallableStatement in jdbc Example" }, { "code": null, "e": 3759, "s": 3725, "text": "ResultSetMetaData in JDBC Example" }, { "code": null, "e": 3792, "s": 3759, "text": "DatabaseMetaData in JDBC Example" }, { "code": null, "e": 3831, "s": 3792, "text": "Transaction Management in JDBC Example" }, { "code": null, "e": 3864, "s": 3831, "text": "Batch Processing in JDBC Example" }, { "code": null, "e": 3901, "s": 3864, "text": "JDBC Connection with Properties file" }, { "code": null, "e": 3907, "s": 3905, "text": "Δ" }, { "code": null, "e": 3926, "s": 3907, "text": " JDBC Driver Types" }, { "code": null, "e": 3953, "s": 3926, "text": " Step by Step JDBC Program" }, { "code": null, "e": 3974, "s": 3953, "text": " JDBC Select Program" }, { "code": null, "e": 3995, "s": 3974, "text": " JDBC Insert Program" }, { "code": null, "e": 4016, "s": 3995, "text": " JDBC Update Program" }, { "code": null, "e": 4037, "s": 4016, "text": " JDBC Delete Program" }, { "code": null, "e": 4072, "s": 4037, "text": " JDBC Connection – Properties File" }, { "code": null, "e": 4104, "s": 4072, "text": " JDBC PreparedStatement Program" }, { "code": null, "e": 4138, "s": 4104, "text": " JDBC – CallableStatement Example" }, { "code": null, "e": 4168, "s": 4138, "text": " JDBC – Read an Image from DB" }, { "code": null, "e": 4198, "s": 4168, "text": " JDBC – Insert an Image in DB" }, { "code": null, "e": 4226, "s": 4198, "text": " JDBC – Updatable ResultSet" }, { "code": null, "e": 4255, "s": 4226, "text": " JDBC – Scrollable ResultSet" }, { "code": null, "e": 4281, "s": 4255, "text": " JDBC – ResultSetMetaData" }, { "code": null, "e": 4306, "s": 4281, "text": " JDBC – DatabaseMetaData" }, { "code": null, "e": 4337, "s": 4306, "text": " JDBC – Transaction Management" }, { "code": null, "e": 4362, "s": 4337, "text": " JDBC – Batch Processing" } ]
Biopython - Sequence Alignments
Sequence alignment is the process of arranging two or more sequences (of DNA, RNA or protein sequences) in a specific order to identify the region of similarity between them. Identifying the similar region enables us to infer a lot of information like what traits are conserved between species, how close different species genetically are, how species evolve, etc. Biopython provides extensive support for sequence alignment. Let us learn some of the important features provided by Biopython in this chapter − Biopython provides a module, Bio.AlignIO to read and write sequence alignments. In bioinformatics, there are lot of formats available to specify the sequence alignment data similar to earlier learned sequence data. Bio.AlignIO provides API similar to Bio.SeqIO except that the Bio.SeqIO works on the sequence data and Bio.AlignIO works on the sequence alignment data. Before starting to learn, let us download a sample sequence alignment file from the Internet. To download the sample file, follow the below steps − Step 1 − Open your favorite browser and go to http://pfam.xfam.org/family/browse website. It will show all the Pfam families in alphabetical order. Step 2 − Choose any one family having less number of seed value. It contains minimal data and enables us to work easily with the alignment. Here, we have selected/clicked PF18225 and it opens go to http://pfam.xfam.org/family/PF18225 and shows complete details about it, including sequence alignments. Step 3 − Go to alignment section and download the sequence alignment file in Stockholm format (PF18225_seed.txt). Let us try to read the downloaded sequence alignment file using Bio.AlignIO as below − >>> from Bio import AlignIO Read alignment using read method. read method is used to read single alignment data available in the given file. If the given file contain many alignment, we can use parse method. parse method returns iterable alignment object similar to parse method in Bio.SeqIO module. >>> alignment = AlignIO.read(open("PF18225_seed.txt"), "stockholm") >>> print(alignment) SingleLetterAlphabet() alignment with 6 rows and 65 columns MQNTPAERLPAIIEKAKSKHDINVWLLDRQGRDLLEQRVPAKVA...EGP B7RZ31_9GAMM/59-123 AKQRGIAGLEEWLHRLDHSEAIPIFLIDEAGKDLLEREVPADIT...KKP A0A0C3NPG9_9PROT/58-119 ARRHGQEYFQQWLERQPKKVKEQVFAVDQFGRELLGRPLPEDMA...KKP A0A143HL37_9GAMM/57-121 TRRHGPESFRFWLERQPVEARDRIYAIDRSGAEILDRPIPRGMA...NKP A0A0X3UC67_9GAMM/57-121 AINRNTQQLTQDLRAMPNWSLRFVYIVDRNNQDLLKRPLPPGIM...NRK B3PFT7_CELJU/62-126 AVNATEREFTERIRTLPHWARRNVFVLDSQGFEIFDRELPSPVA...NRT K4KEM7_SIMAS/61-125 >>> We can also check the sequences (SeqRecord) available in the alignment as well as below − >>> for align in alignment: ... print(align.seq) ... MQNTPAERLPAIIEKAKSKHDINVWLLDRQGRDLLEQRVPAKVATVANQLRGRKRRAFARHREGP AKQRGIAGLEEWLHRLDHSEAIPIFLIDEAGKDLLEREVPADITA---RLDRRREHGEHGVRKKP ARRHGQEYFQQWLERQPKKVKEQVFAVDQFGRELLGRPLPEDMAPMLIALNYRNRESHAQVDKKP TRRHGPESFRFWLERQPVEARDRIYAIDRSGAEILDRPIPRGMAPLFKVLSFRNREDQGLVNNKP AINRNTQQLTQDLRAMPNWSLRFVYIVDRNNQDLLKRPLPPGIMVLAPRLTAKHPYDKVQDRNRK AVNATEREFTERIRTLPHWARRNVFVLDSQGFEIFDRELPSPVADLMRKLDLDRPFKKLERKNRT >>> In general, most of the sequence alignment files contain single alignment data and it is enough to use read method to parse it. In multiple sequence alignment concept, two or more sequences are compared for best subsequence matches between them and results in multiple sequence alignment in a single file. If the input sequence alignment format contains more than one sequence alignment, then we need to use parse method instead of read method as specified below − >>> from Bio import AlignIO >>> alignments = AlignIO.parse(open("PF18225_seed.txt"), "stockholm") >>> print(alignments) <generator object parse at 0x000001CD1C7E0360> >>> for alignment in alignments: ... print(alignment) ... SingleLetterAlphabet() alignment with 6 rows and 65 columns MQNTPAERLPAIIEKAKSKHDINVWLLDRQGRDLLEQRVPAKVA...EGP B7RZ31_9GAMM/59-123 AKQRGIAGLEEWLHRLDHSEAIPIFLIDEAGKDLLEREVPADIT...KKP A0A0C3NPG9_9PROT/58-119 ARRHGQEYFQQWLERQPKKVKEQVFAVDQFGRELLGRPLPEDMA...KKP A0A143HL37_9GAMM/57-121 TRRHGPESFRFWLERQPVEARDRIYAIDRSGAEILDRPIPRGMA...NKP A0A0X3UC67_9GAMM/57-121 AINRNTQQLTQDLRAMPNWSLRFVYIVDRNNQDLLKRPLPPGIM...NRK B3PFT7_CELJU/62-126 AVNATEREFTERIRTLPHWARRNVFVLDSQGFEIFDRELPSPVA...NRT K4KEM7_SIMAS/61-125 >>> Here, parse method returns iterable alignment object and it can be iterated to get actual alignments. Pairwise sequence alignment compares only two sequences at a time and provides best possible sequence alignments. Pairwise is easy to understand and exceptional to infer from the resulting sequence alignment. Biopython provides a special module, Bio.pairwise2 to identify the alignment sequence using pairwise method. Biopython applies the best algorithm to find the alignment sequence and it is par with other software. Let us write an example to find the sequence alignment of two simple and hypothetical sequences using pairwise module. This will help us understand the concept of sequence alignment and how to program it using Biopython. Import the module pairwise2 with the command given below − >>> from Bio import pairwise2 Create two sequences, seq1 and seq2 − >>> from Bio.Seq import Seq >>> seq1 = Seq("ACCGGT") >>> seq2 = Seq("ACGT") Call method pairwise2.align.globalxx along with seq1 and seq2 to find the alignments using the below line of code − >>> alignments = pairwise2.align.globalxx(seq1, seq2) Here, globalxx method performs the actual work and finds all the best possible alignments in the given sequences. Actually, Bio.pairwise2 provides quite a set of methods which follows the below convention to find alignments in different scenarios. <sequence alignment type>XY Here, the sequence alignment type refers to the alignment type which may be global or local. global type is finding sequence alignment by taking entire sequence into consideration. local type is finding sequence alignment by looking into the subset of the given sequences as well. This will be tedious but provides better idea about the similarity between the given sequences. X refers to matching score. The possible values are x (exact match), m (score based on identical chars), d (user provided dictionary with character and match score) and finally c (user defined function to provide custom scoring algorithm). X refers to matching score. The possible values are x (exact match), m (score based on identical chars), d (user provided dictionary with character and match score) and finally c (user defined function to provide custom scoring algorithm). Y refers to gap penalty. The possible values are x (no gap penalties), s (same penalties for both sequences), d (different penalties for each sequence) and finally c (user defined function to provide custom gap penalties) Y refers to gap penalty. The possible values are x (no gap penalties), s (same penalties for both sequences), d (different penalties for each sequence) and finally c (user defined function to provide custom gap penalties) So, localds is also a valid method, which finds the sequence alignment using local alignment technique, user provided dictionary for matches and user provided gap penalty for both sequences. >>> test_alignments = pairwise2.align.localds(seq1, seq2, blosum62, -10, -1) Here, blosum62 refers to a dictionary available in the pairwise2 module to provide match score. -10 refers to gap open penalty and -1 refers to gap extension penalty. Loop over the iterable alignments object and get each individual alignment object and print it. >>> for alignment in alignments: ... print(alignment) ... ('ACCGGT', 'A-C-GT', 4.0, 0, 6) ('ACCGGT', 'AC--GT', 4.0, 0, 6) ('ACCGGT', 'A-CG-T', 4.0, 0, 6) ('ACCGGT', 'AC-G-T', 4.0, 0, 6) Bio.pairwise2 module provides a formatting method, format_alignment to better visualize the result − >>> from Bio.pairwise2 import format_alignment >>> alignments = pairwise2.align.globalxx(seq1, seq2) >>> for alignment in alignments: ... print(format_alignment(*alignment)) ... ACCGGT | | || A-C-GT Score=4 ACCGGT || || AC--GT Score=4 ACCGGT | || | A-CG-T Score=4 ACCGGT || | | AC-G-T Score=4 >>> Biopython also provides another module to do sequence alignment, Align. This module provides a different set of API to simply the setting of parameter like algorithm, mode, match score, gap penalties, etc., A simple look into the Align object is as follows − >>> from Bio import Align >>> aligner = Align.PairwiseAligner() >>> print(aligner) Pairwise sequence aligner with parameters match score: 1.000000 mismatch score: 0.000000 target open gap score: 0.000000 target extend gap score: 0.000000 target left open gap score: 0.000000 target left extend gap score: 0.000000 target right open gap score: 0.000000 target right extend gap score: 0.000000 query open gap score: 0.000000 query extend gap score: 0.000000 query left open gap score: 0.000000 query left extend gap score: 0.000000 query right open gap score: 0.000000 query right extend gap score: 0.000000 mode: global >>> Biopython provides interface to a lot of sequence alignment tools through Bio.Align.Applications module. Some of the tools are listed below − ClustalW MUSCLE EMBOSS needle and water Let us write a simple example in Biopython to create sequence alignment through the most popular alignment tool, ClustalW. Step 1 − Download the Clustalw program from http://www.clustal.org/download/current/ and install it. Also, update the system PATH with the “clustal” installation path. Step 2 − import ClustalwCommanLine from module Bio.Align.Applications. >>> from Bio.Align.Applications import ClustalwCommandline Step 3 − Set cmd by calling ClustalwCommanLine with input file, opuntia.fasta available in Biopython package. https://raw.githubusercontent.com/biopython/biopython/master/Doc/examples/opuntia.fasta >>> cmd = ClustalwCommandline("clustalw2", infile="/path/to/biopython/sample/opuntia.fasta") >>> print(cmd) clustalw2 -infile=fasta/opuntia.fasta Step 4 − Calling cmd() will run the clustalw command and give an output of the resultant alignment file, opuntia.aln. >>> stdout, stderr = cmd() Step 5 − Read and print the alignment file as below − >>> from Bio import AlignIO >>> align = AlignIO.read("/path/to/biopython/sample/opuntia.aln", "clustal") >>> print(align) SingleLetterAlphabet() alignment with 7 rows and 906 columns TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273285|gb|AF191659.1|AF191 TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273284|gb|AF191658.1|AF191 TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273287|gb|AF191661.1|AF191 TATACATAAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273286|gb|AF191660.1|AF191 TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273290|gb|AF191664.1|AF191 TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273289|gb|AF191663.1|AF191 TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273291|gb|AF191665.1|AF191 >>> Print Add Notes Bookmark this page
[ { "code": null, "e": 2281, "s": 2106, "text": "Sequence alignment is the process of arranging two or more sequences (of DNA, RNA or protein sequences) in a specific order to identify the region of similarity between them." }, { "code": null, "e": 2532, "s": 2281, "text": "Identifying the similar region enables us to infer a lot of information like what traits are conserved between species, how close different species genetically are, how species evolve, etc. Biopython provides extensive support for sequence alignment." }, { "code": null, "e": 2616, "s": 2532, "text": "Let us learn some of the important features provided by Biopython in this chapter −" }, { "code": null, "e": 2984, "s": 2616, "text": "Biopython provides a module, Bio.AlignIO to read and write sequence alignments. In bioinformatics, there are lot of formats available to specify the sequence alignment data similar to earlier learned sequence data. Bio.AlignIO provides API similar to Bio.SeqIO except that the Bio.SeqIO works on the sequence data and Bio.AlignIO works on the sequence alignment data." }, { "code": null, "e": 3078, "s": 2984, "text": "Before starting to learn, let us download a sample sequence alignment file from the Internet." }, { "code": null, "e": 3132, "s": 3078, "text": "To download the sample file, follow the below steps −" }, { "code": null, "e": 3280, "s": 3132, "text": "Step 1 − Open your favorite browser and go to http://pfam.xfam.org/family/browse website. It will show all the Pfam families in alphabetical order." }, { "code": null, "e": 3582, "s": 3280, "text": "Step 2 − Choose any one family having less number of seed value. It contains minimal data and enables us to work easily with the alignment. Here, we have selected/clicked PF18225 and it opens go to http://pfam.xfam.org/family/PF18225 and shows complete details about it, including sequence alignments." }, { "code": null, "e": 3696, "s": 3582, "text": "Step 3 − Go to alignment section and download the sequence alignment file in Stockholm format (PF18225_seed.txt)." }, { "code": null, "e": 3783, "s": 3696, "text": "Let us try to read the downloaded sequence alignment file using Bio.AlignIO as below −" }, { "code": null, "e": 3811, "s": 3783, "text": ">>> from Bio import AlignIO" }, { "code": null, "e": 4083, "s": 3811, "text": "Read alignment using read method. read method is used to read single alignment data available in the given file. If the given file contain many alignment, we can use parse method. parse method returns iterable alignment object similar to parse method in Bio.SeqIO module." }, { "code": null, "e": 4151, "s": 4083, "text": ">>> alignment = AlignIO.read(open(\"PF18225_seed.txt\"), \"stockholm\")" }, { "code": null, "e": 4679, "s": 4151, "text": ">>> print(alignment)\nSingleLetterAlphabet() alignment with 6 rows and 65 columns\nMQNTPAERLPAIIEKAKSKHDINVWLLDRQGRDLLEQRVPAKVA...EGP B7RZ31_9GAMM/59-123 \nAKQRGIAGLEEWLHRLDHSEAIPIFLIDEAGKDLLEREVPADIT...KKP A0A0C3NPG9_9PROT/58-119 \nARRHGQEYFQQWLERQPKKVKEQVFAVDQFGRELLGRPLPEDMA...KKP A0A143HL37_9GAMM/57-121 \nTRRHGPESFRFWLERQPVEARDRIYAIDRSGAEILDRPIPRGMA...NKP A0A0X3UC67_9GAMM/57-121 \nAINRNTQQLTQDLRAMPNWSLRFVYIVDRNNQDLLKRPLPPGIM...NRK B3PFT7_CELJU/62-126 \nAVNATEREFTERIRTLPHWARRNVFVLDSQGFEIFDRELPSPVA...NRT K4KEM7_SIMAS/61-125\n>>>" }, { "code": null, "e": 4769, "s": 4679, "text": "We can also check the sequences (SeqRecord) available in the alignment as well as below −" }, { "code": null, "e": 5231, "s": 4769, "text": ">>> for align in alignment: \n... print(align.seq) \n... \nMQNTPAERLPAIIEKAKSKHDINVWLLDRQGRDLLEQRVPAKVATVANQLRGRKRRAFARHREGP \nAKQRGIAGLEEWLHRLDHSEAIPIFLIDEAGKDLLEREVPADITA---RLDRRREHGEHGVRKKP \nARRHGQEYFQQWLERQPKKVKEQVFAVDQFGRELLGRPLPEDMAPMLIALNYRNRESHAQVDKKP \nTRRHGPESFRFWLERQPVEARDRIYAIDRSGAEILDRPIPRGMAPLFKVLSFRNREDQGLVNNKP \nAINRNTQQLTQDLRAMPNWSLRFVYIVDRNNQDLLKRPLPPGIMVLAPRLTAKHPYDKVQDRNRK \nAVNATEREFTERIRTLPHWARRNVFVLDSQGFEIFDRELPSPVADLMRKLDLDRPFKKLERKNRT \n>>>" }, { "code": null, "e": 5537, "s": 5231, "text": "In general, most of the sequence alignment files contain single alignment data and it is enough to use read method to parse it. In multiple sequence alignment concept, two or more sequences are compared for best subsequence matches between them and results in multiple sequence alignment in a single file." }, { "code": null, "e": 5696, "s": 5537, "text": "If the input sequence alignment format contains more than one sequence alignment, then we need to use parse method instead of read method as specified below −" }, { "code": null, "e": 6436, "s": 5696, "text": ">>> from Bio import AlignIO \n>>> alignments = AlignIO.parse(open(\"PF18225_seed.txt\"), \"stockholm\") \n>>> print(alignments) \n<generator object parse at 0x000001CD1C7E0360> \n>>> for alignment in alignments: \n... print(alignment) \n... \nSingleLetterAlphabet() alignment with 6 rows and 65 columns \nMQNTPAERLPAIIEKAKSKHDINVWLLDRQGRDLLEQRVPAKVA...EGP B7RZ31_9GAMM/59-123 \nAKQRGIAGLEEWLHRLDHSEAIPIFLIDEAGKDLLEREVPADIT...KKP A0A0C3NPG9_9PROT/58-119 \nARRHGQEYFQQWLERQPKKVKEQVFAVDQFGRELLGRPLPEDMA...KKP A0A143HL37_9GAMM/57-121 \nTRRHGPESFRFWLERQPVEARDRIYAIDRSGAEILDRPIPRGMA...NKP A0A0X3UC67_9GAMM/57-121 \nAINRNTQQLTQDLRAMPNWSLRFVYIVDRNNQDLLKRPLPPGIM...NRK B3PFT7_CELJU/62-126 \nAVNATEREFTERIRTLPHWARRNVFVLDSQGFEIFDRELPSPVA...NRT K4KEM7_SIMAS/61-125\n>>>" }, { "code": null, "e": 6538, "s": 6436, "text": "Here, parse method returns iterable alignment object and it can be iterated to get actual alignments." }, { "code": null, "e": 6747, "s": 6538, "text": "Pairwise sequence alignment compares only two sequences at a time and provides best possible sequence alignments. Pairwise is easy to understand and exceptional to infer from the resulting sequence alignment." }, { "code": null, "e": 6959, "s": 6747, "text": "Biopython provides a special module, Bio.pairwise2 to identify the alignment sequence using pairwise method. Biopython applies the best algorithm to find the alignment sequence and it is par with other software." }, { "code": null, "e": 7180, "s": 6959, "text": "Let us write an example to find the sequence alignment of two simple and hypothetical sequences using pairwise module. This will help us understand the concept of sequence alignment and how to program it using Biopython." }, { "code": null, "e": 7239, "s": 7180, "text": "Import the module pairwise2 with the command given below −" }, { "code": null, "e": 7269, "s": 7239, "text": ">>> from Bio import pairwise2" }, { "code": null, "e": 7307, "s": 7269, "text": "Create two sequences, seq1 and seq2 −" }, { "code": null, "e": 7385, "s": 7307, "text": ">>> from Bio.Seq import Seq \n>>> seq1 = Seq(\"ACCGGT\") \n>>> seq2 = Seq(\"ACGT\")" }, { "code": null, "e": 7501, "s": 7385, "text": "Call method pairwise2.align.globalxx along with seq1 and seq2 to find the alignments using the below line of code −" }, { "code": null, "e": 7555, "s": 7501, "text": ">>> alignments = pairwise2.align.globalxx(seq1, seq2)" }, { "code": null, "e": 7803, "s": 7555, "text": "Here, globalxx method performs the actual work and finds all the best possible alignments in the given sequences. Actually, Bio.pairwise2 provides quite a set of methods which follows the below convention to find alignments in different scenarios." }, { "code": null, "e": 7831, "s": 7803, "text": "<sequence alignment type>XY" }, { "code": null, "e": 8208, "s": 7831, "text": "Here, the sequence alignment type refers to the alignment type which may be global or local. global type is finding sequence alignment by taking entire sequence into consideration. local type is finding sequence alignment by looking into the subset of the given sequences as well. This will be tedious but provides better idea about the similarity between the given sequences." }, { "code": null, "e": 8448, "s": 8208, "text": "X refers to matching score. The possible values are x (exact match), m (score based on identical chars), d (user provided dictionary with character and match score) and finally c (user defined function to provide custom scoring algorithm)." }, { "code": null, "e": 8688, "s": 8448, "text": "X refers to matching score. The possible values are x (exact match), m (score based on identical chars), d (user provided dictionary with character and match score) and finally c (user defined function to provide custom scoring algorithm)." }, { "code": null, "e": 8910, "s": 8688, "text": "Y refers to gap penalty. The possible values are x (no gap penalties), s (same penalties for both sequences), d (different penalties for each sequence) and finally c (user defined function to provide custom gap penalties)" }, { "code": null, "e": 9132, "s": 8910, "text": "Y refers to gap penalty. The possible values are x (no gap penalties), s (same penalties for both sequences), d (different penalties for each sequence) and finally c (user defined function to provide custom gap penalties)" }, { "code": null, "e": 9323, "s": 9132, "text": "So, localds is also a valid method, which finds the sequence alignment using local alignment technique, user provided dictionary for matches and user provided gap penalty for both sequences." }, { "code": null, "e": 9400, "s": 9323, "text": ">>> test_alignments = pairwise2.align.localds(seq1, seq2, blosum62, -10, -1)" }, { "code": null, "e": 9567, "s": 9400, "text": "Here, blosum62 refers to a dictionary available in the pairwise2 module to provide match score. -10 refers to gap open penalty and -1 refers to gap extension penalty." }, { "code": null, "e": 9663, "s": 9567, "text": "Loop over the iterable alignments object and get each individual alignment object and print it." }, { "code": null, "e": 9855, "s": 9663, "text": ">>> for alignment in alignments: \n... print(alignment) \n... \n('ACCGGT', 'A-C-GT', 4.0, 0, 6) \n('ACCGGT', 'AC--GT', 4.0, 0, 6) \n('ACCGGT', 'A-CG-T', 4.0, 0, 6) \n('ACCGGT', 'AC-G-T', 4.0, 0, 6)" }, { "code": null, "e": 9956, "s": 9855, "text": "Bio.pairwise2 module provides a formatting method, format_alignment to better visualize the result −" }, { "code": null, "e": 10292, "s": 9956, "text": ">>> from Bio.pairwise2 import format_alignment \n>>> alignments = pairwise2.align.globalxx(seq1, seq2) \n>>> for alignment in alignments: \n... print(format_alignment(*alignment)) \n...\n\nACCGGT \n| | || \nA-C-GT \n Score=4 \n \nACCGGT \n|| || \nAC--GT \n Score=4 \n\nACCGGT \n| || | \nA-CG-T \n Score=4 \n\nACCGGT \n|| | | \nAC-G-T \n Score=4\n\n>>>" }, { "code": null, "e": 10551, "s": 10292, "text": "Biopython also provides another module to do sequence alignment, Align. This module provides a different set of API to simply the setting of parameter like algorithm, mode, match score, gap penalties, etc., A simple look into the Align object is as follows −" }, { "code": null, "e": 11219, "s": 10551, "text": ">>> from Bio import Align\n>>> aligner = Align.PairwiseAligner()\n>>> print(aligner)\nPairwise sequence aligner with parameters\n match score: 1.000000\n mismatch score: 0.000000\n target open gap score: 0.000000\n target extend gap score: 0.000000\n target left open gap score: 0.000000\n target left extend gap score: 0.000000\n target right open gap score: 0.000000\n target right extend gap score: 0.000000\n query open gap score: 0.000000\n query extend gap score: 0.000000\n query left open gap score: 0.000000\n query left extend gap score: 0.000000\n query right open gap score: 0.000000\n query right extend gap score: 0.000000\n mode: global\n>>>" }, { "code": null, "e": 11361, "s": 11219, "text": "Biopython provides interface to a lot of sequence alignment tools through Bio.Align.Applications module. Some of the tools are listed below −" }, { "code": null, "e": 11370, "s": 11361, "text": "ClustalW" }, { "code": null, "e": 11377, "s": 11370, "text": "MUSCLE" }, { "code": null, "e": 11401, "s": 11377, "text": "EMBOSS needle and water" }, { "code": null, "e": 11524, "s": 11401, "text": "Let us write a simple example in Biopython to create sequence alignment through the most popular alignment tool, ClustalW." }, { "code": null, "e": 11692, "s": 11524, "text": "Step 1 − Download the Clustalw program from http://www.clustal.org/download/current/ and install it. Also, update the system PATH with the “clustal” installation path." }, { "code": null, "e": 11763, "s": 11692, "text": "Step 2 − import ClustalwCommanLine from module Bio.Align.Applications." }, { "code": null, "e": 11822, "s": 11763, "text": ">>> from Bio.Align.Applications import ClustalwCommandline" }, { "code": null, "e": 12020, "s": 11822, "text": "Step 3 − Set cmd by calling ClustalwCommanLine with input file, opuntia.fasta available in Biopython package.\nhttps://raw.githubusercontent.com/biopython/biopython/master/Doc/examples/opuntia.fasta" }, { "code": null, "e": 12166, "s": 12020, "text": ">>> cmd = ClustalwCommandline(\"clustalw2\",\ninfile=\"/path/to/biopython/sample/opuntia.fasta\")\n>>> print(cmd)\nclustalw2 -infile=fasta/opuntia.fasta" }, { "code": null, "e": 12284, "s": 12166, "text": "Step 4 − Calling cmd() will run the clustalw command and give an output of the resultant\nalignment file, opuntia.aln." }, { "code": null, "e": 12311, "s": 12284, "text": ">>> stdout, stderr = cmd()" }, { "code": null, "e": 12365, "s": 12311, "text": "Step 5 − Read and print the alignment file as below −" }, { "code": null, "e": 13126, "s": 12365, "text": ">>> from Bio import AlignIO\n>>> align = AlignIO.read(\"/path/to/biopython/sample/opuntia.aln\", \"clustal\")\n>>> print(align)\nSingleLetterAlphabet() alignment with 7 rows and 906 columns\nTATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA\ngi|6273285|gb|AF191659.1|AF191\nTATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA\ngi|6273284|gb|AF191658.1|AF191\nTATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA\ngi|6273287|gb|AF191661.1|AF191\nTATACATAAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA\ngi|6273286|gb|AF191660.1|AF191\nTATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA\ngi|6273290|gb|AF191664.1|AF191\nTATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA\ngi|6273289|gb|AF191663.1|AF191\nTATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA\ngi|6273291|gb|AF191665.1|AF191\n>>>" }, { "code": null, "e": 13133, "s": 13126, "text": " Print" }, { "code": null, "e": 13144, "s": 13133, "text": " Add Notes" } ]
Add Bold Tag in String in C++
Suppose we have a string s and a list of strings called dict, we have to add a closed pair of bold tag <b> and </b> to wrap the substrings in s that exist in that dict. When two such substrings overlap, then we have to wrap them together by only one pair of the closed bold tags. Also, if two substrings wrapped by bold tags are consecutive, we need to combine them. So, if the input is like s = "abcxyz123" dict is ["abc","123"], then the output will be "<b>abc</b>xyz<b>123</b>" To solve this, we will follow these steps − n := size of s n := size of s Define an array bold of size n Define an array bold of size n ret := blank string ret := blank string for initialize i := 0, end := 0, when i < size of s, update (increase i by 1), do −for initialize j := 0, when j < size of dict, update (increase j by 1), do −if substring of s from index (i to size of dict[j] - 1) is same as dict[j], then −end := maximum of end and i + size of dict[j]bold[i] := end > i for initialize i := 0, end := 0, when i < size of s, update (increase i by 1), do − for initialize j := 0, when j < size of dict, update (increase j by 1), do −if substring of s from index (i to size of dict[j] - 1) is same as dict[j], then −end := maximum of end and i + size of dict[j] for initialize j := 0, when j < size of dict, update (increase j by 1), do − if substring of s from index (i to size of dict[j] - 1) is same as dict[j], then −end := maximum of end and i + size of dict[j] if substring of s from index (i to size of dict[j] - 1) is same as dict[j], then − end := maximum of end and i + size of dict[j] end := maximum of end and i + size of dict[j] bold[i] := end > i bold[i] := end > i for initialize i := 0, when i < size of s, update i = j, do −if bold[i] is zero, then −ret := ret + s[i]j := i + 1Ignore following part, skip to the next iterationj := iwhile (j < size of s and bold[j] is non-zero), do −(increase j by 1)ret := substring of ret from index i to j - i - 1 concatenate "<b>" concatenate s for initialize i := 0, when i < size of s, update i = j, do − if bold[i] is zero, then −ret := ret + s[i]j := i + 1Ignore following part, skip to the next iteration if bold[i] is zero, then − ret := ret + s[i] ret := ret + s[i] j := i + 1 j := i + 1 Ignore following part, skip to the next iteration Ignore following part, skip to the next iteration j := i j := i while (j < size of s and bold[j] is non-zero), do −(increase j by 1) while (j < size of s and bold[j] is non-zero), do − (increase j by 1) (increase j by 1) ret := substring of ret from index i to j - i - 1 concatenate "<b>" concatenate s ret := substring of ret from index i to j - i - 1 concatenate "<b>" concatenate s return ret return ret Let us see the following implementation to get better understanding − Live Demo #include <bits/stdc++.h> using namespace std; class Solution { public: string addBoldTag(string s, vector<string>& dict) { int n = s.size(); vector<int> bold(n); string ret = ""; for (int i = 0, end = 0; i < s.size(); i++) { for (int j = 0; j < dict.size(); j++) { if (s.substr(i, dict[j].size()) == dict[j]) { end = max(end, i + (int)dict[j].size()); } } bold[i] = end > i; } int j; for (int i = 0; i < s.size(); i = j) { if (!bold[i]) { ret += s[i]; j = i + 1; continue; } j = i; while (j < s.size() && bold[j]) j++; ret += "<b>" + s.substr(i, j - i) + "</b>"; } return ret; } }; main(){ Solution ob; vector<string> v = {"abc","123"}; cout << (ob.addBoldTag("abcxyz123", v)); } "abcxyz123", ["abc","123"] <b>abc</b>xyz<b>123</b>
[ { "code": null, "e": 1429, "s": 1062, "text": "Suppose we have a string s and a list of strings called dict, we have to add a closed pair of bold tag <b> and </b> to wrap the substrings in s that exist in that dict. When two such substrings overlap, then we have to wrap them together by only one pair of the closed bold tags. Also, if two substrings wrapped by bold tags are consecutive, we need to combine them." }, { "code": null, "e": 1543, "s": 1429, "text": "So, if the input is like s = \"abcxyz123\" dict is [\"abc\",\"123\"], then the output will be \"<b>abc</b>xyz<b>123</b>\"" }, { "code": null, "e": 1587, "s": 1543, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1602, "s": 1587, "text": "n := size of s" }, { "code": null, "e": 1617, "s": 1602, "text": "n := size of s" }, { "code": null, "e": 1648, "s": 1617, "text": "Define an array bold of size n" }, { "code": null, "e": 1679, "s": 1648, "text": "Define an array bold of size n" }, { "code": null, "e": 1699, "s": 1679, "text": "ret := blank string" }, { "code": null, "e": 1719, "s": 1699, "text": "ret := blank string" }, { "code": null, "e": 2024, "s": 1719, "text": "for initialize i := 0, end := 0, when i < size of s, update (increase i by 1), do −for initialize j := 0, when j < size of dict, update (increase j by 1), do −if substring of s from index (i to size of dict[j] - 1) is same as dict[j], then −end := maximum of end and i + size of dict[j]bold[i] := end > i" }, { "code": null, "e": 2108, "s": 2024, "text": "for initialize i := 0, end := 0, when i < size of s, update (increase i by 1), do −" }, { "code": null, "e": 2312, "s": 2108, "text": "for initialize j := 0, when j < size of dict, update (increase j by 1), do −if substring of s from index (i to size of dict[j] - 1) is same as dict[j], then −end := maximum of end and i + size of dict[j]" }, { "code": null, "e": 2389, "s": 2312, "text": "for initialize j := 0, when j < size of dict, update (increase j by 1), do −" }, { "code": null, "e": 2517, "s": 2389, "text": "if substring of s from index (i to size of dict[j] - 1) is same as dict[j], then −end := maximum of end and i + size of dict[j]" }, { "code": null, "e": 2600, "s": 2517, "text": "if substring of s from index (i to size of dict[j] - 1) is same as dict[j], then −" }, { "code": null, "e": 2646, "s": 2600, "text": "end := maximum of end and i + size of dict[j]" }, { "code": null, "e": 2692, "s": 2646, "text": "end := maximum of end and i + size of dict[j]" }, { "code": null, "e": 2711, "s": 2692, "text": "bold[i] := end > i" }, { "code": null, "e": 2730, "s": 2711, "text": "bold[i] := end > i" }, { "code": null, "e": 3049, "s": 2730, "text": "for initialize i := 0, when i < size of s, update i = j, do −if bold[i] is zero, then −ret := ret + s[i]j := i + 1Ignore following part, skip to the next iterationj := iwhile (j < size of s and bold[j] is non-zero), do −(increase j by 1)ret := substring of ret from index i to j - i - 1 concatenate \"<b>\" concatenate s" }, { "code": null, "e": 3111, "s": 3049, "text": "for initialize i := 0, when i < size of s, update i = j, do −" }, { "code": null, "e": 3214, "s": 3111, "text": "if bold[i] is zero, then −ret := ret + s[i]j := i + 1Ignore following part, skip to the next iteration" }, { "code": null, "e": 3241, "s": 3214, "text": "if bold[i] is zero, then −" }, { "code": null, "e": 3259, "s": 3241, "text": "ret := ret + s[i]" }, { "code": null, "e": 3277, "s": 3259, "text": "ret := ret + s[i]" }, { "code": null, "e": 3288, "s": 3277, "text": "j := i + 1" }, { "code": null, "e": 3299, "s": 3288, "text": "j := i + 1" }, { "code": null, "e": 3349, "s": 3299, "text": "Ignore following part, skip to the next iteration" }, { "code": null, "e": 3399, "s": 3349, "text": "Ignore following part, skip to the next iteration" }, { "code": null, "e": 3406, "s": 3399, "text": "j := i" }, { "code": null, "e": 3413, "s": 3406, "text": "j := i" }, { "code": null, "e": 3482, "s": 3413, "text": "while (j < size of s and bold[j] is non-zero), do −(increase j by 1)" }, { "code": null, "e": 3534, "s": 3482, "text": "while (j < size of s and bold[j] is non-zero), do −" }, { "code": null, "e": 3552, "s": 3534, "text": "(increase j by 1)" }, { "code": null, "e": 3570, "s": 3552, "text": "(increase j by 1)" }, { "code": null, "e": 3652, "s": 3570, "text": "ret := substring of ret from index i to j - i - 1 concatenate \"<b>\" concatenate s" }, { "code": null, "e": 3734, "s": 3652, "text": "ret := substring of ret from index i to j - i - 1 concatenate \"<b>\" concatenate s" }, { "code": null, "e": 3745, "s": 3734, "text": "return ret" }, { "code": null, "e": 3756, "s": 3745, "text": "return ret" }, { "code": null, "e": 3826, "s": 3756, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 3837, "s": 3826, "text": " Live Demo" }, { "code": null, "e": 4742, "s": 3837, "text": "#include <bits/stdc++.h>\nusing namespace std;\nclass Solution {\npublic:\n string addBoldTag(string s, vector<string>& dict) {\n int n = s.size();\n vector<int> bold(n);\n string ret = \"\";\n for (int i = 0, end = 0; i < s.size(); i++) {\n for (int j = 0; j < dict.size(); j++) {\n if (s.substr(i, dict[j].size()) == dict[j]) {\n end = max(end, i + (int)dict[j].size());\n }\n }\n bold[i] = end > i;\n }\n int j;\n for (int i = 0; i < s.size(); i = j) {\n if (!bold[i]) {\n ret += s[i];\n j = i + 1;\n continue;\n }\n j = i;\n while (j < s.size() && bold[j])\n j++;\n ret += \"<b>\" + s.substr(i, j - i) + \"</b>\";\n }\n return ret;\n }\n};\nmain(){\n Solution ob;\n vector<string> v = {\"abc\",\"123\"};\n cout << (ob.addBoldTag(\"abcxyz123\", v));\n}" }, { "code": null, "e": 4769, "s": 4742, "text": "\"abcxyz123\", [\"abc\",\"123\"]" }, { "code": null, "e": 4793, "s": 4769, "text": "<b>abc</b>xyz<b>123</b>" } ]
Floyd Cycle Detection Algorithm to detect the cycle in a linear Data Structure
Floyd Cycle is one of the cycle detection algorithms to detect the cycle in a given singly linked list. In the Floyd Cycle algorithm, we have two pointers that initially point at the head. In Hare and Tortoise’s story, Hare moves twice as fast as Tortoise, and whenever the hare reaches the end of the path, the tortoise reaches the middle of the path. Initialize Hare and Tortoise at the head node of the List. Initialize Hare and Tortoise at the head node of the List. Initially, the hare moves twice as fast as the tortoise. Initially, the hare moves twice as fast as the tortoise. Move the hare and tortoise both and find if the hare reaches the end of the Linked List, return as there is no loop in the list. Move the hare and tortoise both and find if the hare reaches the end of the Linked List, return as there is no loop in the list. Otherwise, both Hare and Tortoise will go forward. Otherwise, both Hare and Tortoise will go forward. If Hare and Tortoise are at the same Node, then return since we have found the list cycle. If Hare and Tortoise are at the same Node, then return since we have found the list cycle. Else, start with step 2. Else, start with step 2. tortoise := headNode hare := headNode foreach: if hare == end return 'There is No Loop Found.' hare := hare.next if hare == end return 'No Loop Found' hare = hare.next tortoise = tortoise.next if hare == tortoise return 'Cycle Detected'
[ { "code": null, "e": 1166, "s": 1062, "text": "Floyd Cycle is one of the cycle detection algorithms to detect the cycle in a given singly linked list." }, { "code": null, "e": 1415, "s": 1166, "text": "In the Floyd Cycle algorithm, we have two pointers that initially point at the head. In Hare and Tortoise’s story, Hare moves twice as fast as Tortoise, and whenever the hare reaches the end of the path, the tortoise reaches the middle of the path." }, { "code": null, "e": 1474, "s": 1415, "text": "Initialize Hare and Tortoise at the head node of the List." }, { "code": null, "e": 1533, "s": 1474, "text": "Initialize Hare and Tortoise at the head node of the List." }, { "code": null, "e": 1590, "s": 1533, "text": "Initially, the hare moves twice as fast as the tortoise." }, { "code": null, "e": 1647, "s": 1590, "text": "Initially, the hare moves twice as fast as the tortoise." }, { "code": null, "e": 1776, "s": 1647, "text": "Move the hare and tortoise both and find if the hare reaches the end of the Linked List, return as there is no loop in the list." }, { "code": null, "e": 1905, "s": 1776, "text": "Move the hare and tortoise both and find if the hare reaches the end of the Linked List, return as there is no loop in the list." }, { "code": null, "e": 1956, "s": 1905, "text": "Otherwise, both Hare and Tortoise will go forward." }, { "code": null, "e": 2007, "s": 1956, "text": "Otherwise, both Hare and Tortoise will go forward." }, { "code": null, "e": 2098, "s": 2007, "text": "If Hare and Tortoise are at the same Node, then return since we have found the list cycle." }, { "code": null, "e": 2189, "s": 2098, "text": "If Hare and Tortoise are at the same Node, then return since we have found the list cycle." }, { "code": null, "e": 2214, "s": 2189, "text": "Else, start with step 2." }, { "code": null, "e": 2239, "s": 2214, "text": "Else, start with step 2." }, { "code": null, "e": 2512, "s": 2239, "text": "tortoise := headNode\nhare := headNode\nforeach:\n if hare == end\n return 'There is No Loop Found.'\n hare := hare.next\n if hare == end\n return 'No Loop Found'\n hare = hare.next\n tortoise = tortoise.next\n if hare == tortoise\n return 'Cycle Detected'" } ]
What are unary operators in C#?
The following are the unary operators in C# − + - ! ~ ++ -- (type)* & sizeof Let us learn about the sizeof operator. The sizeof returns the size of a data type. Let’s say you need to find the size of int datatype − sizeof(int) For double datatype − sizeof(double) Let us see the complete example to find the size of various datatypes − Live Demo using System; namespace Demo { class Program { static void Main(string[] args) { Console.WriteLine("The size of int is {0}", sizeof(int)); Console.WriteLine("The size of int is {0}", sizeof(char)); Console.WriteLine("The size of short is {0}", sizeof(short)); Console.WriteLine("The size of long is {0}", sizeof(long)); Console.WriteLine("The size of double is {0}", sizeof(double)); Console.ReadLine(); } } } The size of int is 4 The size of int is 2 The size of short is 2 The size of long is 8 The size of double is 8
[ { "code": null, "e": 1108, "s": 1062, "text": "The following are the unary operators in C# −" }, { "code": null, "e": 1139, "s": 1108, "text": "+ - ! ~ ++ -- (type)* & sizeof" }, { "code": null, "e": 1223, "s": 1139, "text": "Let us learn about the sizeof operator. The sizeof returns the size of a data type." }, { "code": null, "e": 1277, "s": 1223, "text": "Let’s say you need to find the size of int datatype −" }, { "code": null, "e": 1289, "s": 1277, "text": "sizeof(int)" }, { "code": null, "e": 1311, "s": 1289, "text": "For double datatype −" }, { "code": null, "e": 1326, "s": 1311, "text": "sizeof(double)" }, { "code": null, "e": 1398, "s": 1326, "text": "Let us see the complete example to find the size of various datatypes −" }, { "code": null, "e": 1409, "s": 1398, "text": " Live Demo" }, { "code": null, "e": 1896, "s": 1409, "text": "using System;\n\nnamespace Demo {\n\n class Program {\n\n static void Main(string[] args) {\n\n Console.WriteLine(\"The size of int is {0}\", sizeof(int));\n Console.WriteLine(\"The size of int is {0}\", sizeof(char));\n Console.WriteLine(\"The size of short is {0}\", sizeof(short));\n Console.WriteLine(\"The size of long is {0}\", sizeof(long));\n Console.WriteLine(\"The size of double is {0}\", sizeof(double));\n\n Console.ReadLine();\n }\n }\n}" }, { "code": null, "e": 2007, "s": 1896, "text": "The size of int is 4\nThe size of int is 2\nThe size of short is 2\nThe size of long is 8\nThe size of double is 8" } ]
Least-square Polynomial Fitting using C++ Eigen Package | by Rahul Bhadani | Towards Data Science
Often while working with sensor data (or signal), we find that data are often not clean and exhibit a significant amount of noise. Such noise makes it harder to perform further mathematical operations such as differentiation, integration, convolution, etc. Further, such noise poses a great challenge if we are meant to use such signals for real-time operations such as controlling an autonomous vehicle, a robotic arm, or an industrial plant, as noise tends to amplify in any downstream mathematical operations. In such a case, one generic approach is to smooth out the data to remove the noise. We seek smoothing of such data in a real-time manner for applications in control engineering such as intelligent control of autonomous vehicles or robots. A number of methods have already been developed to smoothen out signals in a real-time manner, for example, Kalman Filter, Extended Kalman Filter, and their variants. However, designing a Kalman Filter requires knowledge of system dynamics which might or might not be known. Under such circumstances, a simpler approach is to perform least-squares polynomial fitting of last n data-points received. The mathematics of least-squares polynomial fitting is very simple. Consider a set of n datapoints In such a case, a polynomial fit of order k can be written as: Residual in this case is given by The objective of the least-square polynomial fitting is to minimize R2. The usual approach is to take the partial derivative of Equation 2 with respect to coefficients a and equate to zero. This leads to a system of k equations. Such a system of equations comes out as Vandermonde matrix equations which can be simplified and written as follows: In matrix notation, we can write Equation 3 as Equation 4 can be solved by pre-multiplying by the transpose of T, thus the solution vector comes out to be As said in the beginning, the application of concern here is a real-time system that may have to deal with safety-critical systems such as autonomous vehicles and robotic arms. For such systems, the speed of the implementation matter where the target is usually an embedded system. Hence, a common choice of the programming language for implementation in C++. In this article, we use the Eigen package written in C++ for solving Equation 5. For sample data points obtained from the speed profile of a passenger car, the implementation code is provided below. I merely fitted a cubic polynomial. Note that fitting a polynomial of higher degree is computation expensive and might not be needed at all. The above code is written with the Linux system in the mind. A prerequisite for compilation is the availability of a g++ compiler preferable g++ 8 or above with C++ standard 11 or above. Further, we assume the Eigen package is installed in the system. An interested user can download the Eigen package, version 3 tarball from https://eigen.tuxfamily.org/dox/ and extract it in the desired folder. In my case, the Eigen package is at /usr/include/eigen3 with a directory structure that looks like as shown in Figure 1 and Figure 2. Eigen package allows performing matrix mathematics very fast which is desirable for real-time systems. Once you have set up your Eigen package, you can compile eigen_polyfit.cpp program by g++ command and execute it as g++ -I /usr/include/eigen3 eigen_polyfit.cpp && ./a.out For visualization, I created a scatter plot shown below: As you can see, the fitted data points are smoother compared to the original data points and we can expect its derivative to be smoother as well.
[ { "code": null, "e": 684, "s": 171, "text": "Often while working with sensor data (or signal), we find that data are often not clean and exhibit a significant amount of noise. Such noise makes it harder to perform further mathematical operations such as differentiation, integration, convolution, etc. Further, such noise poses a great challenge if we are meant to use such signals for real-time operations such as controlling an autonomous vehicle, a robotic arm, or an industrial plant, as noise tends to amplify in any downstream mathematical operations." }, { "code": null, "e": 1322, "s": 684, "text": "In such a case, one generic approach is to smooth out the data to remove the noise. We seek smoothing of such data in a real-time manner for applications in control engineering such as intelligent control of autonomous vehicles or robots. A number of methods have already been developed to smoothen out signals in a real-time manner, for example, Kalman Filter, Extended Kalman Filter, and their variants. However, designing a Kalman Filter requires knowledge of system dynamics which might or might not be known. Under such circumstances, a simpler approach is to perform least-squares polynomial fitting of last n data-points received." }, { "code": null, "e": 1421, "s": 1322, "text": "The mathematics of least-squares polynomial fitting is very simple. Consider a set of n datapoints" }, { "code": null, "e": 1484, "s": 1421, "text": "In such a case, a polynomial fit of order k can be written as:" }, { "code": null, "e": 1518, "s": 1484, "text": "Residual in this case is given by" }, { "code": null, "e": 1864, "s": 1518, "text": "The objective of the least-square polynomial fitting is to minimize R2. The usual approach is to take the partial derivative of Equation 2 with respect to coefficients a and equate to zero. This leads to a system of k equations. Such a system of equations comes out as Vandermonde matrix equations which can be simplified and written as follows:" }, { "code": null, "e": 1911, "s": 1864, "text": "In matrix notation, we can write Equation 3 as" }, { "code": null, "e": 2019, "s": 1911, "text": "Equation 4 can be solved by pre-multiplying by the transpose of T, thus the solution vector comes out to be" }, { "code": null, "e": 2460, "s": 2019, "text": "As said in the beginning, the application of concern here is a real-time system that may have to deal with safety-critical systems such as autonomous vehicles and robotic arms. For such systems, the speed of the implementation matter where the target is usually an embedded system. Hence, a common choice of the programming language for implementation in C++. In this article, we use the Eigen package written in C++ for solving Equation 5." }, { "code": null, "e": 2719, "s": 2460, "text": "For sample data points obtained from the speed profile of a passenger car, the implementation code is provided below. I merely fitted a cubic polynomial. Note that fitting a polynomial of higher degree is computation expensive and might not be needed at all." }, { "code": null, "e": 3353, "s": 2719, "text": "The above code is written with the Linux system in the mind. A prerequisite for compilation is the availability of a g++ compiler preferable g++ 8 or above with C++ standard 11 or above. Further, we assume the Eigen package is installed in the system. An interested user can download the Eigen package, version 3 tarball from https://eigen.tuxfamily.org/dox/ and extract it in the desired folder. In my case, the Eigen package is at /usr/include/eigen3 with a directory structure that looks like as shown in Figure 1 and Figure 2. Eigen package allows performing matrix mathematics very fast which is desirable for real-time systems." }, { "code": null, "e": 3469, "s": 3353, "text": "Once you have set up your Eigen package, you can compile eigen_polyfit.cpp program by g++ command and execute it as" }, { "code": null, "e": 3525, "s": 3469, "text": "g++ -I /usr/include/eigen3 eigen_polyfit.cpp && ./a.out" }, { "code": null, "e": 3582, "s": 3525, "text": "For visualization, I created a scatter plot shown below:" } ]
Get values from all rows and display it a single row separated by comma with MySQL
For this, use GROUP_CONCAT(). Do not use GROUP BY clause, since GROUP_CONTACT() is a better and quick solution. Let us first create a table − mysql> create table DemoTable1371 -> ( -> Id int, -> CountryName varchar(40) -> ); Query OK, 0 rows affected (0.89 sec) Insert some records in the table using insert command − mysql> insert into DemoTable1371 values(100,'US'); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable1371 values(100,'UK'); Query OK, 1 row affected (0.21 sec) mysql> insert into DemoTable1371 values(101,'AUS'); Query OK, 1 row affected (0.27 sec) mysql> insert into DemoTable1371 values(101,'Angola'); Query OK, 1 row affected (0.14 sec) Display all records from the table using select statement − mysql> select * from DemoTable1371; This will produce the following output − +------+-------------+ | Id | CountryName | +------+-------------+ | 100 | US | | 100 | UK | | 101 | AUS | | 101 | Angola | +------+-------------+ 4 rows in set (0.00 sec) Here is the query to get values from all rows and display it a single row separated by comma − mysql> select group_concat(CountryName separator ',') from DemoTable1371; This will produce the following output − +-----------------------------------------+ | group_concat(CountryName separator ',') | +-----------------------------------------+ | US,UK,AUS,Angola | +-----------------------------------------+ 1 row in set (0.00 sec)
[ { "code": null, "e": 1174, "s": 1062, "text": "For this, use GROUP_CONCAT(). Do not use GROUP BY clause, since GROUP_CONTACT() is a better and quick solution." }, { "code": null, "e": 1204, "s": 1174, "text": "Let us first create a table −" }, { "code": null, "e": 1336, "s": 1204, "text": "mysql> create table DemoTable1371\n -> (\n -> Id int,\n -> CountryName varchar(40)\n -> );\nQuery OK, 0 rows affected (0.89 sec)" }, { "code": null, "e": 1392, "s": 1336, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1745, "s": 1392, "text": "mysql> insert into DemoTable1371 values(100,'US');\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into DemoTable1371 values(100,'UK');\nQuery OK, 1 row affected (0.21 sec)\nmysql> insert into DemoTable1371 values(101,'AUS');\nQuery OK, 1 row affected (0.27 sec)\nmysql> insert into DemoTable1371 values(101,'Angola');\nQuery OK, 1 row affected (0.14 sec)" }, { "code": null, "e": 1805, "s": 1745, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1841, "s": 1805, "text": "mysql> select * from DemoTable1371;" }, { "code": null, "e": 1882, "s": 1841, "text": "This will produce the following output −" }, { "code": null, "e": 2091, "s": 1882, "text": "+------+-------------+\n| Id | CountryName |\n+------+-------------+\n| 100 | US |\n| 100 | UK |\n| 101 | AUS |\n| 101 | Angola |\n+------+-------------+\n4 rows in set (0.00 sec)" }, { "code": null, "e": 2186, "s": 2091, "text": "Here is the query to get values from all rows and display it a single row separated by comma −" }, { "code": null, "e": 2260, "s": 2186, "text": "mysql> select group_concat(CountryName separator ',') from DemoTable1371;" }, { "code": null, "e": 2301, "s": 2260, "text": "This will produce the following output −" }, { "code": null, "e": 2545, "s": 2301, "text": "+-----------------------------------------+\n| group_concat(CountryName separator ',') |\n+-----------------------------------------+\n| US,UK,AUS,Angola |\n+-----------------------------------------+\n1 row in set (0.00 sec)" } ]
C++ Program to Implement Interpolation Search Algorithm
For the binary search technique, the lists are divided into equal parts. For the interpolation searching technique, the procedure will try to locate the exact position using interpolation formula. After finding the estimated location, it can separate the list using that location. As it tries to find exact location every time, so the searching time reduces. This technique can find items easily if the items are uniformly distributed. Time Complexity: O(log2(log2 n)) for average case, and O(n) for worst case (when items are distributed exponentially) Time Complexity: O(log2(log2 n)) for average case, and O(n) for worst case (when items are distributed exponentially) Space Complexity: O(1) Space Complexity: O(1) Input − A sorted list of data 10 13 15 26 28 50 56 88 94 127 159 356 480 567 689 699 780 850 956 995. The search key 780 Output − Item found at location: 16 Input: An sorted array, start and end location, and the search key Output: location of the key (if found), otherwise wrong location. Begin while start <= end AND key >= array[start] AND key <= array[end] do dist := key – array[start] valRange := array[end] – array[start] fraction := dist / valRange indexRange := end – start estimate := start + (fraction * indexRange) if array[estimate] = key then return estimate position if array[estimate] < key then start := estimate + 1 else end = estimate -1 done return invalid position End #include<iostream> using namespace std; int interpolationSearch(int array[], int start, int end, int key) { int dist, valRange, indexRange, estimate; float fraction; while(start <= end && key >= array[start] && key <= array[end]) { dist = key - array[start]; valRange = array[end] - array[start]; //range of value fraction = dist / valRange; indexRange = end - start; estimate = start + (fraction * indexRange); //estimated position of the key if(array[estimate] == key) return estimate; if(array[estimate] < key) start = estimate +1; else end = estimate - 1; } return -1; } int main() { int n, searchKey, loc; cout << "Enter number of items: "; cin >> n; int arr[n]; //create an array of size n cout << "Enter items: " << endl; for(int i = 0; i< n; i++) { cin >> arr[i]; } cout << "Enter search key to search in the list: "; cin >> searchKey; if((loc = interpolationSearch(arr, 0, n-1, searchKey)) >= 0) cout << "Item found at location: " << loc << endl; else cout << "Item is not found in the list." << endl; } Enter number of items: 20 Enter items: 10 13 15 26 28 50 56 88 94 127 159 356 480 567 689 699 780 850 956 995 Enter search key to search in the list: 780 Item found at location: 16
[ { "code": null, "e": 1498, "s": 1062, "text": "For the binary search technique, the lists are divided into equal parts. For the interpolation searching technique, the procedure will try to locate the exact position using interpolation formula. After finding the estimated location, it can separate the list using that location. As it tries to find exact location every time, so the searching time reduces. This technique can find items easily if the items are uniformly distributed." }, { "code": null, "e": 1616, "s": 1498, "text": "Time Complexity: O(log2(log2 n)) for average case, and O(n) for worst case (when items are distributed exponentially)" }, { "code": null, "e": 1734, "s": 1616, "text": "Time Complexity: O(log2(log2 n)) for average case, and O(n) for worst case (when items are distributed exponentially)" }, { "code": null, "e": 1757, "s": 1734, "text": "Space Complexity: O(1)" }, { "code": null, "e": 1780, "s": 1757, "text": "Space Complexity: O(1)" }, { "code": null, "e": 1938, "s": 1780, "text": "Input − A sorted list of data\n10 13 15 26 28 50 56 88 94 127 159 356 480 567 689 699 780 850 956 995. \nThe search key 780\nOutput − Item found at location: 16" }, { "code": null, "e": 2005, "s": 1938, "text": "Input: An sorted array, start and end location, and the search key" }, { "code": null, "e": 2071, "s": 2005, "text": "Output: location of the key (if found), otherwise wrong location." }, { "code": null, "e": 2555, "s": 2071, "text": "Begin\n while start <= end AND key >= array[start] AND key <= array[end] do\n dist := key – array[start]\n valRange := array[end] – array[start]\n fraction := dist / valRange\n indexRange := end – start\n estimate := start + (fraction * indexRange)\n if array[estimate] = key then\n return estimate position\n if array[estimate] < key then\n start := estimate + 1\n else\n end = estimate -1\n done\n return invalid position\nEnd" }, { "code": null, "e": 3723, "s": 2555, "text": "#include<iostream>\nusing namespace std;\nint interpolationSearch(int array[], int start, int end, int key) {\n int dist, valRange, indexRange, estimate;\n float fraction;\n while(start <= end && key >= array[start] && key <= array[end]) {\n dist = key - array[start];\n valRange = array[end] - array[start]; //range of value\n fraction = dist / valRange;\n indexRange = end - start;\n estimate = start + (fraction * indexRange); //estimated position of the key\n if(array[estimate] == key)\n return estimate;\n if(array[estimate] < key)\n start = estimate +1;\n else\n end = estimate - 1;\n }\n return -1;\n}\nint main() {\n int n, searchKey, loc;\n cout << \"Enter number of items: \";\n cin >> n;\n int arr[n]; //create an array of size n\n cout << \"Enter items: \" << endl;\n for(int i = 0; i< n; i++) {\n cin >> arr[i];\n }\n cout << \"Enter search key to search in the list: \";\n cin >> searchKey;\n if((loc = interpolationSearch(arr, 0, n-1, searchKey)) >= 0)\n cout << \"Item found at location: \" << loc << endl;\n else\n cout << \"Item is not found in the list.\" << endl;\n}" }, { "code": null, "e": 3904, "s": 3723, "text": "Enter number of items: 20\nEnter items:\n10 13 15 26 28 50 56 88 94 127 159 356 480 567 689 699 780 850 956\n995\nEnter search key to search in the list: 780\nItem found at location: 16" } ]
Python String encode() Method
Python string method encode() returns an encoded version of the string. Default encoding is the current default string encoding. The errors may be given to set a different error handling scheme. str.encode(encoding='UTF-8',errors='strict') encoding − This is the encodings to be used. For a list of all encoding schemes please visit: Standard Encodings. encoding − This is the encodings to be used. For a list of all encoding schemes please visit: Standard Encodings. errors − This may be given to set a different error handling scheme. The default for errors is 'strict', meaning that encoding errors raise a UnicodeError. Other possible values are 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' and any other name registered via codecs.register_error(). errors − This may be given to set a different error handling scheme. The default for errors is 'strict', meaning that encoding errors raise a UnicodeError. Other possible values are 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' and any other name registered via codecs.register_error(). Decoded string. #!/usr/bin/python str = "this is string example....wow!!!"; print "Encoded String: " + str.encode('base64','strict') Encoded String: dGhpcyBpcyBzdHJpbmcgZXhhbXBsZS4uLi53b3chISE= 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": 2440, "s": 2244, "text": "Python string method encode() returns an encoded version of the string. Default encoding is the current default string encoding. The errors may be given to set a different error handling scheme." }, { "code": null, "e": 2486, "s": 2440, "text": "str.encode(encoding='UTF-8',errors='strict')\n" }, { "code": null, "e": 2600, "s": 2486, "text": "encoding − This is the encodings to be used. For a list of all encoding schemes please visit: Standard Encodings." }, { "code": null, "e": 2714, "s": 2600, "text": "encoding − This is the encodings to be used. For a list of all encoding schemes please visit: Standard Encodings." }, { "code": null, "e": 3016, "s": 2714, "text": "errors − This may be given to set a different error handling scheme. The default for errors is 'strict', meaning that encoding errors raise a UnicodeError. Other possible values are 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' and any other name registered via codecs.register_error()." }, { "code": null, "e": 3318, "s": 3016, "text": "errors − This may be given to set a different error handling scheme. The default for errors is 'strict', meaning that encoding errors raise a UnicodeError. Other possible values are 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' and any other name registered via codecs.register_error()." }, { "code": null, "e": 3334, "s": 3318, "text": "Decoded string." }, { "code": null, "e": 3452, "s": 3334, "text": "#!/usr/bin/python\n\nstr = \"this is string example....wow!!!\";\nprint \"Encoded String: \" + str.encode('base64','strict')" }, { "code": null, "e": 3514, "s": 3452, "text": "Encoded String: dGhpcyBpcyBzdHJpbmcgZXhhbXBsZS4uLi53b3chISE=\n" }, { "code": null, "e": 3551, "s": 3514, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 3567, "s": 3551, "text": " Malhar Lathkar" }, { "code": null, "e": 3600, "s": 3567, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 3619, "s": 3600, "text": " Arnab Chakraborty" }, { "code": null, "e": 3654, "s": 3619, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 3676, "s": 3654, "text": " In28Minutes Official" }, { "code": null, "e": 3710, "s": 3676, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 3738, "s": 3710, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3773, "s": 3738, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 3787, "s": 3773, "text": " Lets Kode It" }, { "code": null, "e": 3820, "s": 3787, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 3837, "s": 3820, "text": " Abhilash Nelson" }, { "code": null, "e": 3844, "s": 3837, "text": " Print" }, { "code": null, "e": 3855, "s": 3844, "text": " Add Notes" } ]
jQuery - hasClass( class ) Method
The hasClass( class ) method returns true if the specified class is present on at least one of the set of matched elements otherwise it returns false. Here is the simple syntax to use this method − selector.hasClass( class ) Here is the description of all the parameters used by this method − class − The name of CSS class. class − The name of CSS class. Following example would check which para has class red − <html> <head> <title>The Selecter Example</title> <script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script> <script type = "text/javascript" language = "javascript"> $(document).ready(function() { $("#result1").text( $("p#pid1").hasClass("red") ); $("#result2").text( $("p#pid2").hasClass("red") ); }); </script> <style> .red { color:red; } .green { color:green; } </style> </head> <body> <p class = "red" id = "pid1">This is first paragraph.</p> <p class = "green" id = "pid2">This is second paragraph.</p> <div id = "result1"></div> <div id = "result2"></div> </body> </html> This will produce following result − This is first paragraph. This is second paragraph. 27 Lectures 1 hours Mahesh Kumar 27 Lectures 1.5 hours Pratik Singh 72 Lectures 4.5 hours Frahaan Hussain 60 Lectures 9 hours Eduonix Learning Solutions 17 Lectures 2 hours Sandip Bhattacharya 12 Lectures 53 mins Laurence Svekis Print Add Notes Bookmark this page
[ { "code": null, "e": 2473, "s": 2322, "text": "The hasClass( class ) method returns true if the specified class is present on at least one of the set of matched elements otherwise it returns false." }, { "code": null, "e": 2520, "s": 2473, "text": "Here is the simple syntax to use this method −" }, { "code": null, "e": 2548, "s": 2520, "text": "selector.hasClass( class )\n" }, { "code": null, "e": 2616, "s": 2548, "text": "Here is the description of all the parameters used by this method −" }, { "code": null, "e": 2647, "s": 2616, "text": "class − The name of CSS class." }, { "code": null, "e": 2678, "s": 2647, "text": "class − The name of CSS class." }, { "code": null, "e": 2735, "s": 2678, "text": "Following example would check which para has class red −" }, { "code": null, "e": 3530, "s": 2735, "text": "<html>\n <head>\n <title>The Selecter Example</title>\n <script type = \"text/javascript\" \n src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\">\n </script>\n \n <script type = \"text/javascript\" language = \"javascript\">\n $(document).ready(function() {\n $(\"#result1\").text( $(\"p#pid1\").hasClass(\"red\") );\n $(\"#result2\").text( $(\"p#pid2\").hasClass(\"red\") );\n });\n </script>\n\t\t\n <style>\n .red { color:red; }\n .green { color:green; }\n </style>\n </head>\n\t\n <body>\n <p class = \"red\" id = \"pid1\">This is first paragraph.</p>\n <p class = \"green\" id = \"pid2\">This is second paragraph.</p>\n\n <div id = \"result1\"></div>\n <div id = \"result2\"></div>\n </body>\n</html>" }, { "code": null, "e": 3567, "s": 3530, "text": "This will produce following result −" }, { "code": null, "e": 3592, "s": 3567, "text": "This is first paragraph." }, { "code": null, "e": 3618, "s": 3592, "text": "This is second paragraph." }, { "code": null, "e": 3651, "s": 3618, "text": "\n 27 Lectures \n 1 hours \n" }, { "code": null, "e": 3665, "s": 3651, "text": " Mahesh Kumar" }, { "code": null, "e": 3700, "s": 3665, "text": "\n 27 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3714, "s": 3700, "text": " Pratik Singh" }, { "code": null, "e": 3749, "s": 3714, "text": "\n 72 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3766, "s": 3749, "text": " Frahaan Hussain" }, { "code": null, "e": 3799, "s": 3766, "text": "\n 60 Lectures \n 9 hours \n" }, { "code": null, "e": 3827, "s": 3799, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3860, "s": 3827, "text": "\n 17 Lectures \n 2 hours \n" }, { "code": null, "e": 3881, "s": 3860, "text": " Sandip Bhattacharya" }, { "code": null, "e": 3913, "s": 3881, "text": "\n 12 Lectures \n 53 mins\n" }, { "code": null, "e": 3930, "s": 3913, "text": " Laurence Svekis" }, { "code": null, "e": 3937, "s": 3930, "text": " Print" }, { "code": null, "e": 3948, "s": 3937, "text": " Add Notes" } ]
How to implement expand and collapse notification in Android?
This example demonstrate about How to implement expand and collapse notification in Android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <? xml version = "1.0" encoding = "utf-8" ?> <RelativeLayout xmlns: android = "http://schemas.android.com/apk/res/android" xmlns: tools = "http://schemas.android.com/tools" android :layout_width = "match_parent" android :layout_height = "match_parent" tools :context = ".MainActivity" > <Button android :layout_width = "match_parent" android :layout_height = "wrap_content" android :layout_centerInParent = "true" android :layout_margin = "16dp" android :onClick = "createNotification" android :text = "create notification" /> </RelativeLayout> Step 3 − Add the following code to src/MainActivity. package app.tutorialspoint.com.notifyme ; import android.app.NotificationChannel ; import android.app.NotificationManager ; import android.os.Bundle ; import android.support.v4.app.NotificationCompat ; import android.support.v7.app.AppCompatActivity ; import android.view.View ; public class MainActivity extends AppCompatActivity { public static final String NOTIFICATION_CHANNEL_ID = "10001" ; private final static String default_notification_channel_id = "default" ; @Override protected void onCreate (Bundle savedInstanceState) { super .onCreate(savedInstanceState) ; setContentView(R.layout. activity_main ) ; } public void createNotification (View view) { NotificationManager mNotificationManager = (NotificationManager) getSystemService( NOTIFICATION_SERVICE ) ; NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(MainActivity. this, default_notification_channel_id ) ; mBuilder.setContentTitle( "Notify Me" ) ; mBuilder.setContentText(getResources().getString(R.string. lorem_ipsum )) ; mBuilder.setStyle( new NotificationCompat.BigTextStyle().bigText(getResources().getString(R.string. lorem_ipsum ))) ; mBuilder.setSmallIcon(R.drawable. ic_launcher_foreground ) ; mBuilder.setAutoCancel( true ) ; if (android.os.Build.VERSION. SDK_INT >= android.os.Build.VERSION_CODES. O ) { int importance = NotificationManager. IMPORTANCE_HIGH ; NotificationChannel notificationChannel = new NotificationChannel( NOTIFICATION_CHANNEL_ID , "NOTIFICATION_CHANNEL_NAME" , importance) ; mBuilder.setChannelId( NOTIFICATION_CHANNEL_ID ) ; assert mNotificationManager != null; mNotificationManager.createNotificationChannel(notificationChannel) ; } assert mNotificationManager != null; mNotificationManager.notify(( int ) System. currentTimeMillis () , mBuilder.build()) ; } } Step 4 − Add the following code to AndroidManifest.xml <? xml version = "1.0" encoding = "utf-8" ?> <manifest xmlns: android = "http://schemas.android.com/apk/res/android" package = "app.tutorialspoint.com.notifyme" > <uses-permission android :name = "android.permission.VIBRATE" /> <application android :allowBackup = "true" android :icon = "@mipmap/ic_launcher" android :label = "@string/app_name" android :roundIcon = "@mipmap/ic_launcher_round" android :supportsRtl = "true" android :theme = "@style/AppTheme" > <activity android :name = ".MainActivity" > <intent-filter> <action android :name = "android.intent.action.MAIN" /> <category android :name = "android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen − Click here to download the project code
[ { "code": null, "e": 1155, "s": 1062, "text": "This example demonstrate about How to implement expand and collapse notification in Android." }, { "code": null, "e": 1284, "s": 1155, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1349, "s": 1284, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 1945, "s": 1349, "text": "<? xml version = \"1.0\" encoding = \"utf-8\" ?>\n<RelativeLayout xmlns: android = \"http://schemas.android.com/apk/res/android\"\n xmlns: tools = \"http://schemas.android.com/tools\"\n android :layout_width = \"match_parent\"\n android :layout_height = \"match_parent\"\n tools :context = \".MainActivity\" >\n <Button\n android :layout_width = \"match_parent\"\n android :layout_height = \"wrap_content\"\n android :layout_centerInParent = \"true\"\n android :layout_margin = \"16dp\"\n android :onClick = \"createNotification\"\n android :text = \"create notification\" />\n</RelativeLayout>" }, { "code": null, "e": 1998, "s": 1945, "text": "Step 3 − Add the following code to src/MainActivity." }, { "code": null, "e": 3927, "s": 1998, "text": "package app.tutorialspoint.com.notifyme ;\nimport android.app.NotificationChannel ;\nimport android.app.NotificationManager ;\nimport android.os.Bundle ;\nimport android.support.v4.app.NotificationCompat ;\nimport android.support.v7.app.AppCompatActivity ;\nimport android.view.View ;\npublic class MainActivity extends AppCompatActivity {\n public static final String NOTIFICATION_CHANNEL_ID = \"10001\" ;\n private final static String default_notification_channel_id = \"default\" ;\n @Override\n protected void onCreate (Bundle savedInstanceState) {\n super .onCreate(savedInstanceState) ;\n setContentView(R.layout. activity_main ) ;\n }\n public void createNotification (View view) {\n NotificationManager mNotificationManager = (NotificationManager) getSystemService( NOTIFICATION_SERVICE ) ;\n NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(MainActivity. this, default_notification_channel_id ) ;\n mBuilder.setContentTitle( \"Notify Me\" ) ;\n mBuilder.setContentText(getResources().getString(R.string. lorem_ipsum )) ;\n mBuilder.setStyle( new NotificationCompat.BigTextStyle().bigText(getResources().getString(R.string. lorem_ipsum ))) ;\n mBuilder.setSmallIcon(R.drawable. ic_launcher_foreground ) ;\n mBuilder.setAutoCancel( true ) ;\n if (android.os.Build.VERSION. SDK_INT >= android.os.Build.VERSION_CODES. O ) {\n int importance = NotificationManager. IMPORTANCE_HIGH ;\n NotificationChannel notificationChannel = new NotificationChannel( NOTIFICATION_CHANNEL_ID , \"NOTIFICATION_CHANNEL_NAME\" , importance) ;\n mBuilder.setChannelId( NOTIFICATION_CHANNEL_ID ) ;\n assert mNotificationManager != null;\n mNotificationManager.createNotificationChannel(notificationChannel) ;\n }\n assert mNotificationManager != null;\n mNotificationManager.notify(( int ) System. currentTimeMillis () , mBuilder.build()) ;\n }\n}" }, { "code": null, "e": 3982, "s": 3927, "text": "Step 4 − Add the following code to AndroidManifest.xml" }, { "code": null, "e": 4781, "s": 3982, "text": "<? xml version = \"1.0\" encoding = \"utf-8\" ?>\n<manifest xmlns: android = \"http://schemas.android.com/apk/res/android\"\n package = \"app.tutorialspoint.com.notifyme\" >\n <uses-permission android :name = \"android.permission.VIBRATE\" />\n <application\n android :allowBackup = \"true\"\n android :icon = \"@mipmap/ic_launcher\"\n android :label = \"@string/app_name\"\n android :roundIcon = \"@mipmap/ic_launcher_round\"\n android :supportsRtl = \"true\"\n android :theme = \"@style/AppTheme\" >\n <activity android :name = \".MainActivity\" >\n <intent-filter>\n <action android :name = \"android.intent.action.MAIN\" />\n <category android :name = \"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 5128, "s": 4781, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −" }, { "code": null, "e": 5170, "s": 5128, "text": "Click here to download the project code" } ]
Postman - Mock Server
A mock server is not a real server and it is created to simulate and function as a real server to verify APIs and their responses. These are commonly used if certain responses need to be verified but are not available on the web servers due to security concerns on the actual server. A Mock Server is created for the reasons listed below − A Mock Server is created if the APIs to be used in Production are still in development. A Mock Server is created if the APIs to be used in Production are still in development. A Mock Server is used if we want to avoid sending requests on real time data. A Mock Server is used if we want to avoid sending requests on real time data. The benefits of Mock Server are listed below − Simulation of real API features with examples. Simulation of real API features with examples. Mock server can be appended to a Collection. Mock server can be appended to a Collection. Verify APIs with mocking data. Verify APIs with mocking data. To identify errors and defects early. To identify errors and defects early. To identify dependencies in API before it is released for actual usage. To identify dependencies in API before it is released for actual usage. It is used by engineers to build a prototype for a concept and showcase it to higher management. It is used by engineers to build a prototype for a concept and showcase it to higher management. While developing the front end of an application, the developer should have some idea on the response features that shall be obtained from the real server on sending a request. A Mock Server can be really helpful at this time. While developing the front end of an application, the developer should have some idea on the response features that shall be obtained from the real server on sending a request. A Mock Server can be really helpful at this time. Follow the steps given below for creation of mock server in Postman − Step 1 − Click on the New icon from the Postman application. Then, click on Mock Server. Step 2 − Select GET from the Method dropdown, enter a Request Path as /user/home, Response Code as 200, and a Response Body. Then, click on Next. Step 3 − Enter a Mock Server name and click on the Create Mock Server button. Step 4 − The Mock Server gets created along with the Mock URL. The Copy Mock URL button is used to copy the Mock link. Click on the Close button to proceed. Step 5 − Select Mock Server as the Environment from the No Environment dropdown and click on Send. The Response code obtained is 200 OK which means that the request is successful. Also the Response Body shows the message – This is Postman Tutorial for Tutorialspoint which is the same as we passed as a Response Body in the Step 2. Step 6 − The value of URL can be obtained by clicking on the eye icon at the right upper corner of the screen. So the complete request Mock URL should be − https://05303abe-b842-4c47-ab8c-db2af9334f57.mock.pstmn.io/user/home(represented by {{url}}/user/home in the address bar in Step 5). We have appended /user/home at the end of the url value since it is the Request Path we have set for the Mock Server in Step2. Step 7 − We have seen that the Response Body is in text format. We can get the response in JSON format as well. To achieve this select the option Save as example from the Save Response dropdown. Step 8 − Provide an Example name and select JSON from the Response Body section. Step 9 − Add the below Response Body in JSON format. Then click on Save Example. { "name": "Tutorialspoint", "subject": "Postman" } Step 10 − Finally, send the GET request on the same endpoint, and we shall receive the same Response Body as we have passed in the Example request. The below image shows Response is in HTML format − The below image shows Response is in JSON format − Follow the steps given below for Mock Server Creation by example request − Step 1 − Create a Collection and add a request to it. The details on how to create a Collection is discussed in detail in the Chapter – Postman Create Collections. Step 2 − Add the endpoint https://postman-echo.com/get?test=123 and send a GET request. Step 3 − From Response Body, select the option Save as Example from the Save Response dropdown. Step 4 − Give an Example name and click on the Save Example button. Step 5 − Click on the Collection name Mock Server (that we have created) and click on the Mock tab. Then, click on Create a mock server. Step 6 − The Create mock server pop-up comes up. Provide a name to the Mock Server and then click on the Create Mock Server button. Please note − We can make a Mock Server private or public. To make a Mock Server private, we have to check the checkbox Make this mock server private. Then, we need to utilise the Postman API key. Step 7 − The message – Mock server created shall come up. Also, we shall get the Mock URL. We can copy it with the Copy Mock URL button. Then, click on Close. Step 8 − The Mock Server which we have created gets reflected under the Mock tab in the Collections sidebar. Click on the same. Step 9 − We shall add a new request and paste the URL we have copied in Step 7. To send a GET request, we shall append the value - /get at the end of the pasted URL. For example, here, the Mock URL generated is − https://f270f73a-6fdd-4ae2-aeae-cb0379234c87.mock.pstmn.io. Now to send a GET request, the endpoint should be − https://f270f73a-6fdd-4ae2-aeae-cb0379234c87.mock.pstmn.io/get. The Response Body received by mocking the server is the same as the Example request. Response obtained in the Example request is as follows − 12 Lectures 1 hours Taurius Litvinavicius 25 Lectures 2 hours Anuja Jain 18 Lectures 2.5 hours Spotle Learn Print Add Notes Bookmark this page
[ { "code": null, "e": 2392, "s": 2108, "text": "A mock server is not a real server and it is created to simulate and function as a real server to verify APIs and their responses. These are commonly used if certain responses need to be verified but are not available on the web servers due to security concerns on the actual server." }, { "code": null, "e": 2448, "s": 2392, "text": "A Mock Server is created for the reasons listed below −" }, { "code": null, "e": 2536, "s": 2448, "text": "A Mock Server is created if the APIs to be used in Production are still in development." }, { "code": null, "e": 2624, "s": 2536, "text": "A Mock Server is created if the APIs to be used in Production are still in development." }, { "code": null, "e": 2702, "s": 2624, "text": "A Mock Server is used if we want to avoid sending requests on real time data." }, { "code": null, "e": 2780, "s": 2702, "text": "A Mock Server is used if we want to avoid sending requests on real time data." }, { "code": null, "e": 2827, "s": 2780, "text": "The benefits of Mock Server are listed below −" }, { "code": null, "e": 2874, "s": 2827, "text": "Simulation of real API features with examples." }, { "code": null, "e": 2921, "s": 2874, "text": "Simulation of real API features with examples." }, { "code": null, "e": 2966, "s": 2921, "text": "Mock server can be appended to a Collection." }, { "code": null, "e": 3011, "s": 2966, "text": "Mock server can be appended to a Collection." }, { "code": null, "e": 3042, "s": 3011, "text": "Verify APIs with mocking data." }, { "code": null, "e": 3073, "s": 3042, "text": "Verify APIs with mocking data." }, { "code": null, "e": 3111, "s": 3073, "text": "To identify errors and defects early." }, { "code": null, "e": 3149, "s": 3111, "text": "To identify errors and defects early." }, { "code": null, "e": 3221, "s": 3149, "text": "To identify dependencies in API before it is released for actual usage." }, { "code": null, "e": 3293, "s": 3221, "text": "To identify dependencies in API before it is released for actual usage." }, { "code": null, "e": 3390, "s": 3293, "text": "It is used by engineers to build a prototype for a concept and showcase it to higher management." }, { "code": null, "e": 3487, "s": 3390, "text": "It is used by engineers to build a prototype for a concept and showcase it to higher management." }, { "code": null, "e": 3714, "s": 3487, "text": "While developing the front end of an application, the developer should have some idea on the response features that shall be obtained from the real server on sending a request. A Mock Server can be really helpful at this time." }, { "code": null, "e": 3941, "s": 3714, "text": "While developing the front end of an application, the developer should have some idea on the response features that shall be obtained from the real server on sending a request. A Mock Server can be really helpful at this time." }, { "code": null, "e": 4011, "s": 3941, "text": "Follow the steps given below for creation of mock server in Postman −" }, { "code": null, "e": 4100, "s": 4011, "text": "Step 1 − Click on the New icon from the Postman application. Then, click on Mock Server." }, { "code": null, "e": 4246, "s": 4100, "text": "Step 2 − Select GET from the Method dropdown, enter a Request Path as /user/home, Response Code as 200, and a Response Body. Then, click on Next." }, { "code": null, "e": 4324, "s": 4246, "text": "Step 3 − Enter a Mock Server name and click on the Create Mock Server button." }, { "code": null, "e": 4481, "s": 4324, "text": "Step 4 − The Mock Server gets created along with the Mock URL. The Copy Mock URL button is used to copy the Mock link. Click on the Close button to proceed." }, { "code": null, "e": 4661, "s": 4481, "text": "Step 5 − Select Mock Server as the Environment from the No Environment dropdown and click on Send. The Response code obtained is 200 OK which means that the request is successful." }, { "code": null, "e": 4813, "s": 4661, "text": "Also the Response Body shows the message – This is Postman Tutorial for Tutorialspoint which is the same as we passed as a Response Body in the Step 2." }, { "code": null, "e": 4924, "s": 4813, "text": "Step 6 − The value of URL can be obtained by clicking on the eye icon at the right upper corner of the screen." }, { "code": null, "e": 5229, "s": 4924, "text": "So the complete request Mock URL should be − https://05303abe-b842-4c47-ab8c-db2af9334f57.mock.pstmn.io/user/home(represented by {{url}}/user/home in the address bar in Step 5). We have appended /user/home at the end of the url value since it is the Request Path we have set for the Mock Server in Step2." }, { "code": null, "e": 5424, "s": 5229, "text": "Step 7 − We have seen that the Response Body is in text format. We can get the response in JSON format as well. To achieve this select the option Save as example from the Save Response dropdown." }, { "code": null, "e": 5505, "s": 5424, "text": "Step 8 − Provide an Example name and select JSON from the Response Body section." }, { "code": null, "e": 5586, "s": 5505, "text": "Step 9 − Add the below Response Body in JSON format. Then click on Save Example." }, { "code": null, "e": 5640, "s": 5586, "text": "{\n\t\"name\": \"Tutorialspoint\",\n\t\"subject\": \"Postman\"\n}\n" }, { "code": null, "e": 5788, "s": 5640, "text": "Step 10 − Finally, send the GET request on the same endpoint, and we shall receive the same Response Body as we have passed in the Example request." }, { "code": null, "e": 5839, "s": 5788, "text": "The below image shows Response is in HTML format −" }, { "code": null, "e": 5890, "s": 5839, "text": "The below image shows Response is in JSON format −" }, { "code": null, "e": 5965, "s": 5890, "text": "Follow the steps given below for Mock Server Creation by example request −" }, { "code": null, "e": 6019, "s": 5965, "text": "Step 1 − Create a Collection and add a request to it." }, { "code": null, "e": 6129, "s": 6019, "text": "The details on how to create a Collection is discussed in detail in the Chapter – Postman Create Collections." }, { "code": null, "e": 6217, "s": 6129, "text": "Step 2 − Add the endpoint https://postman-echo.com/get?test=123 and send a GET request." }, { "code": null, "e": 6313, "s": 6217, "text": "Step 3 − From Response Body, select the option Save as Example from the Save Response dropdown." }, { "code": null, "e": 6381, "s": 6313, "text": "Step 4 − Give an Example name and click on the Save Example button." }, { "code": null, "e": 6518, "s": 6381, "text": "Step 5 − Click on the Collection name Mock Server (that we have created) and click on the Mock tab. Then, click on Create a mock server." }, { "code": null, "e": 6650, "s": 6518, "text": "Step 6 − The Create mock server pop-up comes up. Provide a name to the Mock Server and then click on the Create Mock Server button." }, { "code": null, "e": 6847, "s": 6650, "text": "Please note − We can make a Mock Server private or public. To make a Mock Server private, we have to check the checkbox Make this mock server private. Then, we need to utilise the Postman API key." }, { "code": null, "e": 7006, "s": 6847, "text": "Step 7 − The message – Mock server created shall come up. Also, we shall get the Mock URL. We can copy it with the Copy Mock URL button. Then, click on Close." }, { "code": null, "e": 7134, "s": 7006, "text": "Step 8 − The Mock Server which we have created gets reflected under the Mock tab in the Collections sidebar. Click on the same." }, { "code": null, "e": 7300, "s": 7134, "text": "Step 9 − We shall add a new request and paste the URL we have copied in Step 7. To send a GET request, we shall append the value - /get at the end of the pasted URL." }, { "code": null, "e": 7407, "s": 7300, "text": "For example, here, the Mock URL generated is − https://f270f73a-6fdd-4ae2-aeae-cb0379234c87.mock.pstmn.io." }, { "code": null, "e": 7523, "s": 7407, "text": "Now to send a GET request, the endpoint should be − https://f270f73a-6fdd-4ae2-aeae-cb0379234c87.mock.pstmn.io/get." }, { "code": null, "e": 7608, "s": 7523, "text": "The Response Body received by mocking the server is the same as the Example request." }, { "code": null, "e": 7665, "s": 7608, "text": "Response obtained in the Example request is as follows −" }, { "code": null, "e": 7698, "s": 7665, "text": "\n 12 Lectures \n 1 hours \n" }, { "code": null, "e": 7721, "s": 7698, "text": " Taurius Litvinavicius" }, { "code": null, "e": 7754, "s": 7721, "text": "\n 25 Lectures \n 2 hours \n" }, { "code": null, "e": 7766, "s": 7754, "text": " Anuja Jain" }, { "code": null, "e": 7801, "s": 7766, "text": "\n 18 Lectures \n 2.5 hours \n" }, { "code": null, "e": 7815, "s": 7801, "text": " Spotle Learn" }, { "code": null, "e": 7822, "s": 7815, "text": " Print" }, { "code": null, "e": 7833, "s": 7822, "text": " Add Notes" } ]
How to set local date/time in a table using LocalDateTime class in Java?
The java.time package of Java8 provides a class named LocalDateTime is used to get the current value of local date and time. Using this in addition to date and time values you can also get other date and time fields, such as day-of-year, day-of-week and week-of-year. To set the local date and time value to a column in a table − Obtain the LocalDateTime object − You can obtain the LocalDateTime object by invoking the static method now() as − //Getting the LocalDateTime object LocalDateTime localDateTime = LocalDateTime.now(); Get the LocalDate and LocalTime objects from the above obtained LocalDateTime as − LocalDate localDate = localDateTime.toLocalDate(); LocalTime localTime = localDateTime.toLocalTime() Now, pass the LocalDate and LocalTime objects to the valueOf() method of the java.sql.Date and java.sql.Time classes respectively as− java.sql.Date date = java.sql.Date.valueOf(localDate); java.sql.Time time = java.sql.Time.valueOf(localTime); Let us create a table with name dispatches in MySQL database using CREATE statement as follows − CREATE TABLE dispatches( ProductName VARCHAR(255), CustomerName VARCHAR(255), DispatchDate date, DeliveryTime time, Price INT, Location VARCHAR(255) ); Now, we will insert 5 records in dispatches table using INSERT statements − insert into dispatches values('Key-Board', 'Raja', DATE('2019-09-01'), TIME('11:00:00'), 7000, 'Hyderabad'); insert into dispatches values('Earphones', 'Roja', DATE('2019-05-01'), TIME('11:00:00'), 2000, 'Vishakhapatnam'); insert into dispatches values('Mouse', 'Puja', DATE('2019-03-01'), TIME('10:59:59'), 3000, 'Vijayawada'); insert into dispatches values('Mobile', 'Vanaja', DATE('2019-03-01'), TIME('10:10:52'), 9000, 'Chennai'); insert into dispatches values('Headset', 'Jalaja', DATE('2019-04-06'), TIME('11:08:59'), 6000, 'Goa'); Following JDBC program inserts a new record into the dispatches table by passing the required values. In here, we are getting the current local date and time values and inserting them as values of the Date and Time columns of the table. import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.time.LocalDateTime; public class settingLocatDate { public static void main(String args[]) throws SQLException { //Registering the Driver DriverManager.registerDriver(new com.mysql.jdbc.Driver()); //Getting the connection String mysqlUrl = "jdbc:mysql://localhost/mydatabase"; Connection con = DriverManager.getConnection(mysqlUrl, "root", "password"); System.out.println("Connection established......"); //Getting the LocalDateTime object LocalDateTime localDateTime = LocalDateTime.now(); System.out.println(localDateTime.toString()); //Converting date and time values from local to SQL java.sql.Date date = java.sql.Date.valueOf(localDateTime.toLocalDate()); java.sql.Time time = java.sql.Time.valueOf(localDateTime.toLocalTime()); //Creating a Prepared Statement String query = "INSERT INTO Dispatches VALUES (?, ?, ?, ?, ?, ?)"; PreparedStatement pstmt = con.prepareStatement(query); pstmt.setString(1, "Watch"); pstmt.setString(2, "Rajan"); pstmt.setDate(3, date); pstmt.setObject(4, time); pstmt.setInt(5, 4000); pstmt.setString(6, "Chennai"); pstmt.execute(); System.out.println("Rows inserted ...."); //Retrieving values Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("select * from dispatches"); while(rs.next()) { System.out.println("Product Name: "+rs.getString("ProductName")); System.out.println("Customer Name: "+rs.getString("CustomerName")); System.out.println("Date Of Dispatch: "+rs.getDate("DispatchDate")); System.out.println("Delivery Time: "+rs.getTime("DeliveryTime")); System.out.println("Location: "+rs.getString("Location")); System.out.println(); } } } Connection established...... 2019-05-14T15:48:42.457 Rows inserted .... Product Name: Key-Board Customer Name: Raja Date Of Dispatch: 2019-09-01 Delivery Time: 11:00:00 Location: Hyderabad Product Name: Earphones Customer Name: Roja Date Of Dispatch: 2019-05-01 Delivery Time: 11:00:00 Location: Vishakhapatnam Product Name: Mouse Customer Name: Puja Date Of Dispatch: 2019-03-01 Delivery Time: 10:59:59 Location: Vijayawada Product Name: Mobile Customer Name: Vanaja Date Of Dispatch: 2019-03-01 Delivery Time: 10:10:52 Location: Chennai Product Name: Headset Customer Name: Jalaja Date Of Dispatch: 2019-04-06 Delivery Time: 11:08:59 Location: Goa Product Name: Watch Customer Name: Rajan Date Of Dispatch: 2019-05-14 Delivery Time: 15:48:42 Location: Chennai
[ { "code": null, "e": 1330, "s": 1062, "text": "The java.time package of Java8 provides a class named LocalDateTime is used to get the current value of local date and time. Using this in addition to date and time values you can also get other date and time fields, such as day-of-year, day-of-week and week-of-year." }, { "code": null, "e": 1392, "s": 1330, "text": "To set the local date and time value to a column in a table −" }, { "code": null, "e": 1507, "s": 1392, "text": "Obtain the LocalDateTime object − You can obtain the LocalDateTime object by invoking the static method now() as −" }, { "code": null, "e": 1593, "s": 1507, "text": "//Getting the LocalDateTime object\nLocalDateTime localDateTime = LocalDateTime.now();" }, { "code": null, "e": 1676, "s": 1593, "text": "Get the LocalDate and LocalTime objects from the above obtained LocalDateTime as −" }, { "code": null, "e": 1777, "s": 1676, "text": "LocalDate localDate = localDateTime.toLocalDate();\nLocalTime localTime = localDateTime.toLocalTime()" }, { "code": null, "e": 1911, "s": 1777, "text": "Now, pass the LocalDate and LocalTime objects to the valueOf() method of the java.sql.Date and java.sql.Time classes respectively as−" }, { "code": null, "e": 2021, "s": 1911, "text": "java.sql.Date date = java.sql.Date.valueOf(localDate);\njava.sql.Time time = java.sql.Time.valueOf(localTime);" }, { "code": null, "e": 2118, "s": 2021, "text": "Let us create a table with name dispatches in MySQL database using CREATE statement as follows −" }, { "code": null, "e": 2288, "s": 2118, "text": "CREATE TABLE dispatches(\n ProductName VARCHAR(255),\n CustomerName VARCHAR(255),\n DispatchDate date,\n DeliveryTime time,\n Price INT,\n Location VARCHAR(255)\n);" }, { "code": null, "e": 2364, "s": 2288, "text": "Now, we will insert 5 records in dispatches table using INSERT statements −" }, { "code": null, "e": 2902, "s": 2364, "text": "insert into dispatches values('Key-Board', 'Raja', DATE('2019-09-01'), TIME('11:00:00'), 7000, 'Hyderabad');\ninsert into dispatches values('Earphones', 'Roja', DATE('2019-05-01'), TIME('11:00:00'), 2000, 'Vishakhapatnam');\ninsert into dispatches values('Mouse', 'Puja', DATE('2019-03-01'), TIME('10:59:59'), 3000, 'Vijayawada');\ninsert into dispatches values('Mobile', 'Vanaja', DATE('2019-03-01'), TIME('10:10:52'), 9000, 'Chennai');\ninsert into dispatches values('Headset', 'Jalaja', DATE('2019-04-06'), TIME('11:08:59'), 6000, 'Goa');" }, { "code": null, "e": 3139, "s": 2902, "text": "Following JDBC program inserts a new record into the dispatches table by passing the required values. In here, we are getting the current local date and time values and inserting them as values of the Date and Time columns of the table." }, { "code": null, "e": 5164, "s": 3139, "text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.PreparedStatement;\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\nimport java.sql.Statement;\nimport java.time.LocalDateTime;\npublic class settingLocatDate {\n public static void main(String args[]) throws SQLException {\n //Registering the Driver\n DriverManager.registerDriver(new com.mysql.jdbc.Driver());\n //Getting the connection\n String mysqlUrl = \"jdbc:mysql://localhost/mydatabase\";\n Connection con = DriverManager.getConnection(mysqlUrl, \"root\", \"password\");\n System.out.println(\"Connection established......\");\n //Getting the LocalDateTime object\n LocalDateTime localDateTime = LocalDateTime.now();\n System.out.println(localDateTime.toString());\n //Converting date and time values from local to SQL\n java.sql.Date date = java.sql.Date.valueOf(localDateTime.toLocalDate());\n java.sql.Time time = java.sql.Time.valueOf(localDateTime.toLocalTime());\n //Creating a Prepared Statement\n String query = \"INSERT INTO Dispatches VALUES (?, ?, ?, ?, ?, ?)\";\n PreparedStatement pstmt = con.prepareStatement(query);\n pstmt.setString(1, \"Watch\");\n pstmt.setString(2, \"Rajan\");\n pstmt.setDate(3, date);\n pstmt.setObject(4, time);\n pstmt.setInt(5, 4000);\n pstmt.setString(6, \"Chennai\");\n pstmt.execute();\n System.out.println(\"Rows inserted ....\");\n //Retrieving values\n Statement stmt = con.createStatement();\n ResultSet rs = stmt.executeQuery(\"select * from dispatches\");\n while(rs.next()) {\n System.out.println(\"Product Name: \"+rs.getString(\"ProductName\"));\n System.out.println(\"Customer Name: \"+rs.getString(\"CustomerName\"));\n System.out.println(\"Date Of Dispatch: \"+rs.getDate(\"DispatchDate\"));\n System.out.println(\"Delivery Time: \"+rs.getTime(\"DeliveryTime\"));\n System.out.println(\"Location: \"+rs.getString(\"Location\"));\n System.out.println();\n }\n }\n}" }, { "code": null, "e": 5926, "s": 5164, "text": "Connection established......\n2019-05-14T15:48:42.457\nRows inserted ....\nProduct Name: Key-Board\nCustomer Name: Raja\nDate Of Dispatch: 2019-09-01\nDelivery Time: 11:00:00\nLocation: Hyderabad\nProduct Name: Earphones\nCustomer Name: Roja\nDate Of Dispatch: 2019-05-01\nDelivery Time: 11:00:00\nLocation: Vishakhapatnam\nProduct Name: Mouse\nCustomer Name: Puja\nDate Of Dispatch: 2019-03-01\nDelivery Time: 10:59:59\nLocation: Vijayawada\nProduct Name: Mobile\nCustomer Name: Vanaja\nDate Of Dispatch: 2019-03-01\nDelivery Time: 10:10:52\nLocation: Chennai\nProduct Name: Headset\nCustomer Name: Jalaja\nDate Of Dispatch: 2019-04-06\nDelivery Time: 11:08:59\nLocation: Goa\nProduct Name: Watch\nCustomer Name: Rajan\nDate Of Dispatch: 2019-05-14\nDelivery Time: 15:48:42\nLocation: Chennai" } ]
Changing Ownership of schema in SAP HANA Database
I don’t think you can change ownership of schema in database. Easiest way to change ownership of schema is by exporting a schema, drop it from the database and then recreate the schema owned by the target user and import the objects back into the database. In recent version, you can create schema and set other users as an owner of the schema however you can’t change it later − Create SCHEMA TEST123 owned by Demo; In same way, you can collect the script for "Create procedure" from database and drop the procedures in the earlier user schema and then these can be recreated in new user schema. You can do in the script with the dynamic SQL which would create the object into the target schema and drop the object in source schema.
[ { "code": null, "e": 1319, "s": 1062, "text": "I don’t think you can change ownership of schema in database. Easiest way to change ownership of schema is by exporting a schema, drop it from the database and then recreate the schema owned by the target user and import the objects back into the database." }, { "code": null, "e": 1442, "s": 1319, "text": "In recent version, you can create schema and set other users as an owner of the schema however you can’t change it later −" }, { "code": null, "e": 1479, "s": 1442, "text": "Create SCHEMA TEST123 owned by Demo;" }, { "code": null, "e": 1796, "s": 1479, "text": "In same way, you can collect the script for \"Create procedure\" from database and drop the procedures in the earlier user schema and then these can be recreated in new user schema. You can do in the script with the dynamic SQL which would create the object into the target schema and drop the object in source schema." } ]
How to aggregate two lists if at least one element matches in MongoDB?
For this, use groupinMongoDB.Withinthat,useunwind, group,addToSet, etc. Let us create a collection with documents − > db.demo456.insertOne( ... { _id: 101, StudentName: ["Chris", "David"] } ... ); { "acknowledged" : true, "insertedId" : 101 } > > db.demo456.insertOne( ... { _id: 102, StudentName: ["Mike", "Sam"] } ... ); { "acknowledged" : true, "insertedId" : 102 } > db.demo456.insertOne( ... { _id: 103, StudentName: ["John", "Jace"] } ... ); { "acknowledged" : true, "insertedId" : 103 } > db.demo456.insertOne( ... { _id: 104, StudentName: ["Robert", "John"] } ... ); { "acknowledged" : true, "insertedId" : 104 } Display all documents from a collection with the help of find() method − > db.demo456.find(); This will produce the following output − { "_id" : 101, "StudentName" : [ "Chris", "David" ] } { "_id" : 102, "StudentName" : [ "Mike", "Sam" ] } { "_id" : 103, "StudentName" : [ "John", "Jace" ] } { "_id" : 104, "StudentName" : [ "Robert", "John" ] } Following is the query to aggregate two lists if at least one element matches − > db.demo456.aggregate([ ... {$unwind:"$StudentName"}, ... {$group:{_id:"$StudentName", combine:{$addToSet:"$_id"}, size:{$sum:1}}}, ... {$match:{size: {$gt: 1}}}, ... {$project:{_id: 1, combine:1, size: 1, combine1: "$combine"}}, ... {$unwind:"$combine"}, ... {$unwind:"$combine1"}, ... {$group:{_id:"$combine", l:{$first:"$_id"}, size:{$sum: 1}, set: {$addToSet:"$combine1"}}}, ... {$sort:{size:1}}, ... {$group:{_id: "$l", combineIds:{$last:"$set"}, size:{$sum:1}}}, ... {$match: {size:{$gt:1}}} ... ]) This will produce the following output − { "_id" : "John", "combineIds" : [ 103, 104 ], "size" : 2 }
[ { "code": null, "e": 1178, "s": 1062, "text": "For this, use groupinMongoDB.Withinthat,useunwind, group,addToSet, etc. Let us create a collection with documents −" }, { "code": null, "e": 1683, "s": 1178, "text": "> db.demo456.insertOne(\n... { _id: 101, StudentName: [\"Chris\", \"David\"] }\n... );\n{ \"acknowledged\" : true, \"insertedId\" : 101 }\n>\n> db.demo456.insertOne(\n... { _id: 102, StudentName: [\"Mike\", \"Sam\"] }\n... );\n{ \"acknowledged\" : true, \"insertedId\" : 102 }\n> db.demo456.insertOne(\n... { _id: 103, StudentName: [\"John\", \"Jace\"] }\n... );\n{ \"acknowledged\" : true, \"insertedId\" : 103 }\n> db.demo456.insertOne(\n... { _id: 104, StudentName: [\"Robert\", \"John\"] }\n... );\n{ \"acknowledged\" : true, \"insertedId\" : 104 }" }, { "code": null, "e": 1756, "s": 1683, "text": "Display all documents from a collection with the help of find() method −" }, { "code": null, "e": 1777, "s": 1756, "text": "> db.demo456.find();" }, { "code": null, "e": 1818, "s": 1777, "text": "This will produce the following output −" }, { "code": null, "e": 2029, "s": 1818, "text": "{ \"_id\" : 101, \"StudentName\" : [ \"Chris\", \"David\" ] }\n{ \"_id\" : 102, \"StudentName\" : [ \"Mike\", \"Sam\" ] }\n{ \"_id\" : 103, \"StudentName\" : [ \"John\", \"Jace\" ] }\n{ \"_id\" : 104, \"StudentName\" : [ \"Robert\", \"John\" ] }" }, { "code": null, "e": 2109, "s": 2029, "text": "Following is the query to aggregate two lists if at least one element matches −" }, { "code": null, "e": 2615, "s": 2109, "text": "> db.demo456.aggregate([\n... {$unwind:\"$StudentName\"},\n... {$group:{_id:\"$StudentName\", combine:{$addToSet:\"$_id\"}, size:{$sum:1}}},\n... {$match:{size: {$gt: 1}}},\n... {$project:{_id: 1, combine:1, size: 1, combine1: \"$combine\"}},\n... {$unwind:\"$combine\"},\n... {$unwind:\"$combine1\"},\n... {$group:{_id:\"$combine\", l:{$first:\"$_id\"}, size:{$sum: 1}, set: {$addToSet:\"$combine1\"}}},\n... {$sort:{size:1}},\n... {$group:{_id: \"$l\", combineIds:{$last:\"$set\"}, size:{$sum:1}}},\n... {$match: {size:{$gt:1}}}\n... ])" }, { "code": null, "e": 2656, "s": 2615, "text": "This will produce the following output −" }, { "code": null, "e": 2716, "s": 2656, "text": "{ \"_id\" : \"John\", \"combineIds\" : [ 103, 104 ], \"size\" : 2 }" } ]
Write a java program to reverse each word in string?
StringBuffer class of the java.lang package provides reverse() method. This method returns a reverse sequence of the characters in the current String. Using this method you can reverse a string in Java. To reverse each word in a string you need to split the string, store it in an array of strings and reverse each word using the reverse() method of the StringBuffer class. Live Demo import java.lang.*; public class StringBufferDemo { public static void main(String[] args) { StringBuffer buff = new StringBuffer("tutorials point"); System.out.println("buffer = " + buff); // reverse characters of the buffer and prints it System.out.println("reverse = " + buff.reverse()); // reverse of the buffer is equivalent to the actual buffer buff = new StringBuffer("malyalam"); System.out.println("buffer = " + buff); // reverse characters of the buffer and prints it System.out.println("reverse = " + buff.reverse()); } } buffer = tutorials point reverse = tniop slairotut buffer = malyalam reverse = malaylam
[ { "code": null, "e": 1265, "s": 1062, "text": "StringBuffer class of the java.lang package provides reverse() method. This method returns a reverse sequence of the characters in the current String. Using this method you can reverse a string in Java." }, { "code": null, "e": 1436, "s": 1265, "text": "To reverse each word in a string you need to split the string, store it in an array of strings and reverse each word using the reverse() method of the StringBuffer class." }, { "code": null, "e": 1446, "s": 1436, "text": "Live Demo" }, { "code": null, "e": 2042, "s": 1446, "text": "import java.lang.*;\npublic class StringBufferDemo {\n public static void main(String[] args) {\n StringBuffer buff = new StringBuffer(\"tutorials point\");\n System.out.println(\"buffer = \" + buff);\n\n // reverse characters of the buffer and prints it\n System.out.println(\"reverse = \" + buff.reverse());\n\n // reverse of the buffer is equivalent to the actual buffer\n buff = new StringBuffer(\"malyalam\");\n System.out.println(\"buffer = \" + buff);\n\n // reverse characters of the buffer and prints it\n System.out.println(\"reverse = \" + buff.reverse());\n }\n}" }, { "code": null, "e": 2130, "s": 2042, "text": "buffer = tutorials point\nreverse = tniop slairotut\nbuffer = malyalam\nreverse = malaylam" } ]
Water Connection Problem | Practice | GeeksforGeeks
There are n houses and p water pipes in Geek Colony. Every house has at most one pipe going into it and at most one pipe going out of it. Geek needs to install pairs of tanks and taps in the colony according to the following guidelines. 1. Every house with one outgoing pipe but no incoming pipe gets a tank on its roof. 2. Every house with only one incoming and no outgoing pipe gets a tap. The Geek council has proposed a network of pipes where connections are denoted by three input values: ai, bi, di denoting the pipe of diameter di from house ai to house bi. Find a more efficient way for the construction of this network of pipes. Minimize the diameter of pipes wherever possible. Note: The generated output will have the following format. The first line will contain t, denoting the total number of pairs of tanks and taps installed. The next t lines contain three integers each: house number of tank, house number of tap, and the minimum diameter of pipe between them. Example 1: Input: n = 9, p = 6 a[] = {7,5,4,2,9,3} b[] = {4,9,6,8,7,1} d[] = {98,72,10,22,17,66} Output: 3 2 8 22 3 1 66 5 6 10 Explanation: Connected components are 3->1, 5->9->7->4->6 and 2->8. Therefore, our answer is 3 followed by 2 8 22, 3 1 66, 5 6 10. Your Task: You don't need to read input or print anything. Your task is to complete the function solve() which takes an integer n(the number of houses), p(the number of pipes),the array a[] , b[] and d[] (where d[i] denoting the diameter of the ith pipe from the house a[i] to house b[i]) as input parameter and returns the array of pairs of tanks and taps installed i.e ith element of the array contains three integers: house number of tank, house number of tap and the minimum diameter of pipe between them. Expected Time Complexity: O(n+p) Expected Auxiliary Space: O(n+p) Constraints: 1<=n<=20 1<=p<=50 1<=a[i],b[i]<=20 1<=d[i]<=100 0 milindprajapatmst19 This comment was deleted. +1 rp212 weeks ago Guys try to concise your code, otherwise things may messed up. If this problem can be solved using just for loops then why to go for other recursive DFS, topo sort etc., int in[21], out[21]; memset(in, -1, 21 << 2); memset(out, -1, 21 << 2); for(int i = 0; i < p; i++) out[a[i]] = in[b[i]] = i; vector<vector<int>> res; for(int i = 1; i <= 20; i++) if(out[i] != -1 && in[i] == -1) { int mn = 1000; int x = i; while(out[x] != -1) { mn = min(mn, d[out[x]]); x = b[out[x]]; } res.push_back({i, x, mn}); } return res; -1 tea_lover3 weeks ago Simple Solution : vector<vector<int>> solve(int n,int p,vector<int> a,vector<int> b,vector<int> d) { int A[n+1]={0}; int vis[n+1]={0}; vector<int>V(n+1,0); for(int i=1;i<=p;i++){ A[a[i-1]] = b[i-1]; V[a[i-1]] = d[i-1]; } for(int i=1;i<=n;i++){ if(vis[i]==0){ int k = i; while(A[k] != 0 and A[k] != i){ V[i] = min(V[i],V[k]); k = A[k]; vis[k]=1; } if(i != k) A[i] = k; } } vector<vector<int>>X; for(int i=1;i<=n;i++){ if(vis[i]==0 and A[A[i]] != i and A[i] != 0){ vector<int>temp(3); temp[0] = i; temp[1] = A[i]; temp[2] = V[i]; X.push_back(temp); } } return X; } 0 vatsalsrivastava283 weeks ago is this a graph problem? +1 aaravarya11 month ago C++ DFS solution pair<int,int> dfs(int index, vector<pair<int,int>> adj[], int mini) { if(adj[index].size()==0) return {index,mini}; else { for(int i=0; i<adj[index].size(); i++) { if(adj[index][i].second< mini) mini=adj[index][i].second; return dfs(adj[index][i].first,adj,mini); } } } vector<vector<int>> solve(int n,int p,vector<int> a,vector<int> b,vector<int> d) { // code here vector<pair<int,int>> adj[n+1]; vector<int> starting(n+1,true); for(int i=0; i<p; i++) { adj[a[i]].push_back({b[i],d[i]}); starting[b[i]]=false; } vector<vector<int>> aarav; for(int i=1; i<=n; i++) { if(starting[i]) { if(adj[i].size()==0)continue; vector<int> v; pair<int,int> p= dfs(i,adj,INT_MAX); v.push_back(i); v.push_back(p.first); v.push_back(p.second); aarav.push_back(v); } } sort(aarav.begin(),aarav.end()); return aarav; } 0 sangamchoudhary71 month ago for each component find toposort and while finding toposort also take care for minimum diameter class Solution{ public: void dfs(int node,vector<int> adj[],vector<bool> &vis,vector<int> &toposort,int &mini,vector<int> &d,unordered_map<int,int> &mp){ vis[node] = true; for(auto &it : adj[node]){ if(!vis[it]){ int pos = mp[it]; mini = min(mini,d[pos]); dfs(it,adj,vis,toposort,mini,d,mp); } } toposort.push_back(node); } vector<vector<int>> solve(int n,int p,vector<int> a,vector<int> b,vector<int> d){ unordered_map<int,int> mp; for(int i=0;i<b.size();i++){ mp[b[i]] = i; } vector<int> adj[n+1]; for(int i=0;i<b.size();i++){ adj[a[i]].push_back(b[i]); } vector<vector<int>> ans; vector<bool> vis(n+1); for(int i=1;i<n+1;i++){ if(adj[i].empty() or mp.find(i) != mp.end()) continue; if(!vis[i]){ int mini = 1e9; vector<int> toposort; dfs(i,adj,vis,toposort,mini,d,mp); ans.push_back({toposort.back(),toposort.front(),mini}); } } return ans; } }; -1 tthakare731 month ago Please help me Optimize this → 0.3 TC but using large space //Java Solution class Solution { static class pair{ int dest, dmeter; pair(int destination, int dm){ dest = destination; dmeter = dm; } } static int check; public static int DFS(int src, int dest, HashMap<Integer, pair> map, int dimiter, HashSet<Integer> setOutlet){ if(setOutlet.contains(dest)) { check = dest; dimiter = Math.min(dimiter, map.get(src).dmeter); return dimiter; } dimiter = DFS(dest, map.get(dest).dest, map, dimiter, setOutlet); dimiter = Math.min(dimiter, map.get(src).dmeter); return dimiter; } ArrayList<ArrayList<Integer>> solve(int n, int p, ArrayList<Integer> a ,ArrayList<Integer> b ,ArrayList<Integer> d) { // code here HashSet<Integer> setOut = new HashSet<>(); HashSet<Integer> setIn = new HashSet<>(); HashSet<Integer> setOutlet = new HashSet<>(); HashMap<Integer, pair> map = new HashMap<>(); for(int i = 0; i < p; i++){ setOut.add(b.get(i)); setIn.add(a.get(i)); map.put(a.get(i), new pair(b.get(i), d.get(i))); } ArrayList<Integer> inlet = new ArrayList<>(); ArrayList<Integer> sortedTanks = a; Collections.sort(sortedTanks); for(int i = 0; i < p; i++){ if(!setOut.contains(sortedTanks.get(i))){ inlet.add(sortedTanks.get(i)); } if(!setIn.contains(b.get(i))){ setOutlet.add(b.get(i)); } } ArrayList<ArrayList<Integer>> result = new ArrayList<>();; for(int i = 0; i < inlet.size(); i++){ check = 0; ArrayList<Integer> result1 = new ArrayList<>(); int dimiter = map.get(inlet.get(i)).dmeter; dimiter = DFS(inlet.get(i), map.get(inlet.get(i)).dest, map, dimiter, setOutlet); result1.add(inlet.get(i)); result1.add(check); result1.add(dimiter); check = 0; result.add(result1); } return result; } } 0 kritikasinha2562 months ago PYTHON class Solution: def solve(self, n, p ,a, b, d): bidx,aidx={},{} for i in range(p): aidx[a[i]]=i bidx[b[i]]=i #print(aidx) #print(bidx) start=[] for i in a: if i not in bidx: start.append(i) #print(start) ans=[] for node in start: root=node index=aidx[node] mn=d[index] while True: index=aidx[node] mn=min(d[index],mn) if b[index] not in aidx: #it has no further outgoing pipe ans.append([root,b[index],mn]) #print(ans) break else: node=b[index] ans.sort() return ans +1 ashutoshrastogi2 months ago Java Code class Solution { static int ans=0; ArrayList<ArrayList<Integer>> solve(int n, int p, ArrayList<Integer> a ,ArrayList<Integer> b ,ArrayList<Integer> d) { ArrayList<ArrayList<Integer>> res = new ArrayList<>(); int i= 0; int[] ith_ends = new int[n+1]; int[] ith_receives = new int[n+1]; int[] dia = new int[n+1]; for(i=0;i<p;i++){ int q = a.get(i); int h = b.get(i); int t = d.get(i); ith_ends[q] = h; dia[q] = t; ith_receives[h] = q; } for(i=1;i<=n;i++){ if(ith_receives[i] == 0 && ith_ends[i]!=0){ ans = Integer.MAX_VALUE; //System.out.println("hi"); int w = dfs(i,ith_ends,dia); ArrayList<Integer> tem = new ArrayList<>(); tem.add(i); tem.add(w); tem.add(ans); res.add(tem); } } return res; } int dfs(int w, int[] ith_ends, int[]dia){ if(ith_ends[w]==0) return w; ans = Math.min(ans,dia[w]); return(dfs(ith_ends[w],ith_ends,dia)); } } 0 aloksinghbais022 months ago C++ solution by applying DFS on connected graph having time complexity as O(n+e) if sorting is not considered and space complexity as O(n+e) with complete explanation is as follows :- Execution Time :- 0.0 / 1.1 sec vector<int> adj[21]; // adjacency list for a connected component int diam[21][21]; // diameter array void dfs(int node,int &e,int &minDia){ e = node; // finding the last node in the current connected component for(auto choice: adj[node]){ // traversing to all the nodes(choices) which are starting from node minDia = min(minDia,diam[node][choice]); // minimise the diameter dfs(choice,e,minDia); // applying dfs on childs or choices } } vector<vector<int>> solve(int n,int p,vector<int> a,vector<int> b,vector<int> d){ // initialize the diam 2d array memset(diam,0,sizeof(diam)); for(int i = 0; i < p; i++){ // assigning diameter of pipe a[i] to b[i] as d[i] diam[a[i]][b[i]] = d[i]; } unordered_set<int> s; for(int i = 0; i < p; i++){ // creating a node from a[i] to b[i] adj[a[i]].push_back(b[i]); s.insert(b[i]); } //vector which will contain all the nodes which are the starting node of a new connected component vector<int> st; for(int i = 0; i < p; i++){ if(s.find(a[i]) == s.end()) st.push_back(a[i]); } // vector which will include our ans vector<vector<int>> ans; for(int i = 0; i < st.size(); i++){ // s is starting node of the connected component // e is the ending node of the component // minDia is the min diameter in the whole connected component int s = st[i], e = 0, minDia = INT_MAX; dfs(s,e,minDia); // if starting (s) node is equal to ending (e) node then we won't include it in our ans if(s == e) continue; // otherwise include it in the ans ans.push_back(vector<int>{s,e,minDia}); } // sorting all the vectors present in ans as per need of the question sort(ans.begin(),ans.end()); return (ans); } We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 1218, "s": 238, "text": "There are n houses and p water pipes in Geek Colony. Every house has at most one pipe going into it and at most one pipe going out of it. Geek needs to install pairs of tanks and taps in the colony according to the following guidelines. \n1. Every house with one outgoing pipe but no incoming pipe gets a tank on its roof.\n2. Every house with only one incoming and no outgoing pipe gets a tap.\nThe Geek council has proposed a network of pipes where connections are denoted by three input values: ai, bi, di denoting the pipe of diameter di from house ai to house bi.\nFind a more efficient way for the construction of this network of pipes. Minimize the diameter of pipes wherever possible.\nNote: The generated output will have the following format. The first line will contain t, denoting the total number of pairs of tanks and taps installed. The next t lines contain three integers each: house number of tank, house number of tap, and the minimum diameter of pipe between them." }, { "code": null, "e": 1230, "s": 1218, "text": "\nExample 1:" }, { "code": null, "e": 1482, "s": 1230, "text": "Input:\nn = 9, p = 6\na[] = {7,5,4,2,9,3}\nb[] = {4,9,6,8,7,1}\nd[] = {98,72,10,22,17,66} \nOutput: \n3\n2 8 22\n3 1 66\n5 6 10\nExplanation:\nConnected components are \n3->1, 5->9->7->4->6 and 2->8.\nTherefore, our answer is 3 \nfollowed by 2 8 22, 3 1 66, 5 6 10." }, { "code": null, "e": 1996, "s": 1484, "text": "Your Task:\nYou don't need to read input or print anything. Your task is to complete the function solve() which takes an integer n(the number of houses), p(the number of pipes),the array a[] , b[] and d[] (where d[i] denoting the diameter of the ith pipe from the house a[i] to house b[i]) as input parameter and returns the array of pairs of tanks and taps installed i.e ith element of the array contains three integers: house number of tank, house number of tap and the minimum diameter of pipe between them. " }, { "code": null, "e": 2064, "s": 1998, "text": "Expected Time Complexity: O(n+p)\nExpected Auxiliary Space: O(n+p)" }, { "code": null, "e": 2127, "s": 2066, "text": "Constraints:\n1<=n<=20\n1<=p<=50\n1<=a[i],b[i]<=20\n1<=d[i]<=100" }, { "code": null, "e": 2129, "s": 2127, "text": "0" }, { "code": null, "e": 2149, "s": 2129, "text": "milindprajapatmst19" }, { "code": null, "e": 2175, "s": 2149, "text": "This comment was deleted." }, { "code": null, "e": 2178, "s": 2175, "text": "+1" }, { "code": null, "e": 2194, "s": 2178, "text": "rp212 weeks ago" }, { "code": null, "e": 2372, "s": 2194, "text": "Guys try to concise your code, otherwise things may messed up. If this problem can be solved using just for loops then why to go for other recursive DFS, topo sort etc., " }, { "code": null, "e": 2928, "s": 2374, "text": " int in[21], out[21]; memset(in, -1, 21 << 2); memset(out, -1, 21 << 2); for(int i = 0; i < p; i++) out[a[i]] = in[b[i]] = i; vector<vector<int>> res; for(int i = 1; i <= 20; i++) if(out[i] != -1 && in[i] == -1) { int mn = 1000; int x = i; while(out[x] != -1) { mn = min(mn, d[out[x]]); x = b[out[x]]; } res.push_back({i, x, mn}); } return res;" }, { "code": null, "e": 2931, "s": 2928, "text": "-1" }, { "code": null, "e": 2952, "s": 2931, "text": "tea_lover3 weeks ago" }, { "code": null, "e": 2970, "s": 2952, "text": "Simple Solution :" }, { "code": null, "e": 3883, "s": 2970, "text": "vector<vector<int>> solve(int n,int p,vector<int> a,vector<int> b,vector<int> d)\n {\n int A[n+1]={0};\n int vis[n+1]={0};\n vector<int>V(n+1,0);\n for(int i=1;i<=p;i++){\n A[a[i-1]] = b[i-1];\n V[a[i-1]] = d[i-1];\n }\n for(int i=1;i<=n;i++){\n if(vis[i]==0){\n int k = i;\n while(A[k] != 0 and A[k] != i){\n V[i] = min(V[i],V[k]);\n k = A[k];\n vis[k]=1;\n }\n if(i != k) A[i] = k;\n }\n }\n vector<vector<int>>X;\n for(int i=1;i<=n;i++){\n if(vis[i]==0 and A[A[i]] != i and A[i] != 0){\n vector<int>temp(3);\n temp[0] = i;\n temp[1] = A[i];\n temp[2] = V[i];\n X.push_back(temp);\n }\n }\n return X;\n}" }, { "code": null, "e": 3885, "s": 3883, "text": "0" }, { "code": null, "e": 3915, "s": 3885, "text": "vatsalsrivastava283 weeks ago" }, { "code": null, "e": 3940, "s": 3915, "text": "is this a graph problem?" }, { "code": null, "e": 3945, "s": 3942, "text": "+1" }, { "code": null, "e": 3967, "s": 3945, "text": "aaravarya11 month ago" }, { "code": null, "e": 5219, "s": 3967, "text": "C++ DFS solution\n pair<int,int> dfs(int index, vector<pair<int,int>> adj[], int mini)\n {\n if(adj[index].size()==0)\n return {index,mini};\n else\n {\n for(int i=0; i<adj[index].size(); i++)\n {\n if(adj[index][i].second< mini)\n mini=adj[index][i].second;\n \n return dfs(adj[index][i].first,adj,mini);\n }\n }\n }\n \n vector<vector<int>> solve(int n,int p,vector<int> a,vector<int> b,vector<int> d)\n {\n // code here\n vector<pair<int,int>> adj[n+1];\n vector<int> starting(n+1,true);\n for(int i=0; i<p; i++)\n {\n adj[a[i]].push_back({b[i],d[i]});\n starting[b[i]]=false;\n }\n vector<vector<int>> aarav;\n for(int i=1; i<=n; i++)\n {\n if(starting[i])\n {\n if(adj[i].size()==0)continue;\n vector<int> v;\n pair<int,int> p= dfs(i,adj,INT_MAX);\n v.push_back(i);\n v.push_back(p.first);\n v.push_back(p.second);\n aarav.push_back(v);\n }\n }\n sort(aarav.begin(),aarav.end());\n return aarav;\n }" }, { "code": null, "e": 5221, "s": 5219, "text": "0" }, { "code": null, "e": 5249, "s": 5221, "text": "sangamchoudhary71 month ago" }, { "code": null, "e": 5345, "s": 5249, "text": "for each component find toposort and while finding toposort also take care for minimum diameter" }, { "code": null, "e": 6565, "s": 5345, "text": "class Solution{\n public:\n void dfs(int node,vector<int> adj[],vector<bool> &vis,vector<int> &toposort,int &mini,vector<int> &d,unordered_map<int,int> &mp){\n vis[node] = true;\n for(auto &it : adj[node]){\n if(!vis[it]){\n int pos = mp[it];\n mini = min(mini,d[pos]);\n dfs(it,adj,vis,toposort,mini,d,mp);\n }\n }\n toposort.push_back(node);\n }\n vector<vector<int>> solve(int n,int p,vector<int> a,vector<int> b,vector<int> d){\n unordered_map<int,int> mp;\n for(int i=0;i<b.size();i++){\n mp[b[i]] = i;\n }\n \n vector<int> adj[n+1];\n for(int i=0;i<b.size();i++){\n adj[a[i]].push_back(b[i]);\n }\n \n vector<vector<int>> ans;\n vector<bool> vis(n+1);\n \n for(int i=1;i<n+1;i++){\n if(adj[i].empty() or mp.find(i) != mp.end()) continue;\n if(!vis[i]){\n int mini = 1e9;\n vector<int> toposort;\n dfs(i,adj,vis,toposort,mini,d,mp);\n ans.push_back({toposort.back(),toposort.front(),mini});\n }\n }\n \n return ans;\n }\n};" }, { "code": null, "e": 6568, "s": 6565, "text": "-1" }, { "code": null, "e": 6590, "s": 6568, "text": "tthakare731 month ago" }, { "code": null, "e": 6629, "s": 6590, "text": "Please help me Optimize this → 0.3 TC " }, { "code": null, "e": 6651, "s": 6629, "text": "but using large space" }, { "code": null, "e": 8904, "s": 6651, "text": "//Java Solution\nclass Solution \n{ \n static class pair{\n int dest, dmeter;\n pair(int destination, int dm){\n dest = destination;\n dmeter = dm;\n }\n }\n \n static int check;\n \n public static int DFS(int src, int dest, HashMap<Integer, pair> map, int dimiter, HashSet<Integer> setOutlet){\n if(setOutlet.contains(dest)) {\n check = dest;\n dimiter = Math.min(dimiter, map.get(src).dmeter);\n return dimiter;\n }\n dimiter = DFS(dest, map.get(dest).dest, map, dimiter, setOutlet);\n dimiter = Math.min(dimiter, map.get(src).dmeter);\n return dimiter;\n }\n \n ArrayList<ArrayList<Integer>> solve(int n, int p, ArrayList<Integer> a ,ArrayList<Integer> b ,ArrayList<Integer> d) { \n // code here\n HashSet<Integer> setOut = new HashSet<>();\n HashSet<Integer> setIn = new HashSet<>();\n HashSet<Integer> setOutlet = new HashSet<>();\n HashMap<Integer, pair> map = new HashMap<>();\n for(int i = 0; i < p; i++){\n setOut.add(b.get(i));\n setIn.add(a.get(i));\n map.put(a.get(i), new pair(b.get(i), d.get(i)));\n }\n \n ArrayList<Integer> inlet = new ArrayList<>();\n ArrayList<Integer> sortedTanks = a;\n Collections.sort(sortedTanks);\n \n for(int i = 0; i < p; i++){\n if(!setOut.contains(sortedTanks.get(i))){\n inlet.add(sortedTanks.get(i));\n }\n \n if(!setIn.contains(b.get(i))){\n setOutlet.add(b.get(i));\n }\n }\n \n ArrayList<ArrayList<Integer>> result = new ArrayList<>();;\n for(int i = 0; i < inlet.size(); i++){\n check = 0;\n ArrayList<Integer> result1 = new ArrayList<>();\n int dimiter = map.get(inlet.get(i)).dmeter;\n dimiter = DFS(inlet.get(i), map.get(inlet.get(i)).dest, map, dimiter, setOutlet);\n \n result1.add(inlet.get(i));\n result1.add(check);\n result1.add(dimiter);\n check = 0;\n result.add(result1);\n \n }\n return result;\n }\n}" }, { "code": null, "e": 8906, "s": 8904, "text": "0" }, { "code": null, "e": 8934, "s": 8906, "text": "kritikasinha2562 months ago" }, { "code": null, "e": 8941, "s": 8934, "text": "PYTHON" }, { "code": null, "e": 9719, "s": 8941, "text": "class Solution: def solve(self, n, p ,a, b, d): bidx,aidx={},{} for i in range(p): aidx[a[i]]=i bidx[b[i]]=i #print(aidx) #print(bidx) start=[] for i in a: if i not in bidx: start.append(i) #print(start) ans=[] for node in start: root=node index=aidx[node] mn=d[index] while True: index=aidx[node] mn=min(d[index],mn) if b[index] not in aidx: #it has no further outgoing pipe ans.append([root,b[index],mn]) #print(ans) break else: node=b[index] ans.sort() return ans" }, { "code": null, "e": 9722, "s": 9719, "text": "+1" }, { "code": null, "e": 9750, "s": 9722, "text": "ashutoshrastogi2 months ago" }, { "code": null, "e": 9760, "s": 9750, "text": "Java Code" }, { "code": null, "e": 11058, "s": 9762, "text": "class Solution \n{ \n static int ans=0;\n ArrayList<ArrayList<Integer>> solve(int n, int p, ArrayList<Integer> a ,ArrayList<Integer> b ,ArrayList<Integer> d) \n {\n ArrayList<ArrayList<Integer>> res = new ArrayList<>();\n int i= 0;\n int[] ith_ends = new int[n+1]; \n int[] ith_receives = new int[n+1];\n int[] dia = new int[n+1];\n \n for(i=0;i<p;i++){\n int q = a.get(i);\n int h = b.get(i);\n int t = d.get(i);\n \n ith_ends[q] = h;\n dia[q] = t;\n ith_receives[h] = q;\n }\n \n for(i=1;i<=n;i++){\n if(ith_receives[i] == 0 && ith_ends[i]!=0){\n ans = Integer.MAX_VALUE;\n //System.out.println(\"hi\");\n int w = dfs(i,ith_ends,dia);\n \n ArrayList<Integer> tem = new ArrayList<>();\n tem.add(i);\n tem.add(w);\n tem.add(ans);\n \n res.add(tem);\n }\n }\n return res;\n }\n \n int dfs(int w, int[] ith_ends, int[]dia){\n if(ith_ends[w]==0)\n return w;\n \n ans = Math.min(ans,dia[w]);\n \n return(dfs(ith_ends[w],ith_ends,dia));\n }\n} " }, { "code": null, "e": 11060, "s": 11058, "text": "0" }, { "code": null, "e": 11088, "s": 11060, "text": "aloksinghbais022 months ago" }, { "code": null, "e": 11273, "s": 11088, "text": "C++ solution by applying DFS on connected graph having time complexity as O(n+e) if sorting is not considered and space complexity as O(n+e) with complete explanation is as follows :- " }, { "code": null, "e": 11307, "s": 11275, "text": "Execution Time :- 0.0 / 1.1 sec" }, { "code": null, "e": 11880, "s": 11309, "text": "vector<int> adj[21]; // adjacency list for a connected component int diam[21][21]; // diameter array void dfs(int node,int &e,int &minDia){ e = node; // finding the last node in the current connected component for(auto choice: adj[node]){ // traversing to all the nodes(choices) which are starting from node minDia = min(minDia,diam[node][choice]); // minimise the diameter dfs(choice,e,minDia); // applying dfs on childs or choices } } vector<vector<int>> solve(int n,int p,vector<int> a,vector<int> b,vector<int> d){" }, { "code": null, "e": 11954, "s": 11880, "text": " // initialize the diam 2d array memset(diam,0,sizeof(diam));" }, { "code": null, "e": 13292, "s": 11954, "text": " for(int i = 0; i < p; i++){ // assigning diameter of pipe a[i] to b[i] as d[i] diam[a[i]][b[i]] = d[i]; } unordered_set<int> s; for(int i = 0; i < p; i++){ // creating a node from a[i] to b[i] adj[a[i]].push_back(b[i]); s.insert(b[i]); } //vector which will contain all the nodes which are the starting node of a new connected component vector<int> st; for(int i = 0; i < p; i++){ if(s.find(a[i]) == s.end()) st.push_back(a[i]); } // vector which will include our ans vector<vector<int>> ans; for(int i = 0; i < st.size(); i++){ // s is starting node of the connected component // e is the ending node of the component // minDia is the min diameter in the whole connected component int s = st[i], e = 0, minDia = INT_MAX; dfs(s,e,minDia); // if starting (s) node is equal to ending (e) node then we won't include it in our ans if(s == e) continue; // otherwise include it in the ans ans.push_back(vector<int>{s,e,minDia}); } // sorting all the vectors present in ans as per need of the question sort(ans.begin(),ans.end()); return (ans); }" }, { "code": null, "e": 13438, "s": 13292, "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": 13474, "s": 13438, "text": " Login to access your submissions. " }, { "code": null, "e": 13484, "s": 13474, "text": "\nProblem\n" }, { "code": null, "e": 13494, "s": 13484, "text": "\nContest\n" }, { "code": null, "e": 13557, "s": 13494, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 13705, "s": 13557, "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": 13913, "s": 13705, "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": 14019, "s": 13913, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Set vs Map in C++ STL
Set is an abstract data type in which each element has to be unique because the value of the element identifies it. The value of the element cannot be modified once it is added to the set, but it is possible to remove and add the modified value of that element. A Map is an associative container that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have the same key values. So, it is clear from above that, set contains the only key, and map contains a value with the key, both should have unique and sorted value. For unordered and unsorted elements there are unordered_set/unordered_map,multiset/multimap. Live Demo #include<iostream> #include <bits/stdc++.h> using namespace std; int main() { set<int> s; //initializing a empty set container set<int>::iterator it; //Initializing a set container as iterator s.insert(7); //inserting elements in the set container s s.insert(6); s.insert(1); s.insert(4); s.insert(2); s.insert(9); s.insert(10); cout << "Elements are in set:\n"; for ( auto it : s) cout << it << " "; //printing elements of the set container return 0; } 1 2 4 6 7 9 10 Live Demo #include<iostream> #include <bits/stdc++.h> using namespace std; int main() { map<char, int> m; //initialize a map map<char, int>::iterator iter; //initializing a map as iterator m.insert (pair<char, int>('a', 10)); //inserting values to the map m.insert (pair<char, int>('b', 20)); cout << "Elements in map:\n"; for (iter=m.begin();iter!=m.end();iter++) cout << "[ " << iter->first << ", "<< iter->second << "]\n"; //printing the values of the map return 0; } Elements in map: [ a, 10] [ b, 20]
[ { "code": null, "e": 1324, "s": 1062, "text": "Set is an abstract data type in which each element has to be unique because the value of the element identifies it. The value of the element cannot be modified once it is added to the set, but it is possible to remove and add the modified value of that element." }, { "code": null, "e": 1499, "s": 1324, "text": "A Map is an associative container that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have the same key values." }, { "code": null, "e": 1640, "s": 1499, "text": "So, it is clear from above that, set contains the only key, and map contains a value with the key, both should have unique and sorted value." }, { "code": null, "e": 1733, "s": 1640, "text": "For unordered and unsorted elements there are unordered_set/unordered_map,multiset/multimap." }, { "code": null, "e": 1744, "s": 1733, "text": " Live Demo" }, { "code": null, "e": 2240, "s": 1744, "text": "#include<iostream>\n#include <bits/stdc++.h>\nusing namespace std;\nint main() {\n set<int> s; //initializing a empty set container\n set<int>::iterator it; //Initializing a set container as iterator\n s.insert(7); //inserting elements in the set container s\n s.insert(6);\n s.insert(1);\n s.insert(4);\n s.insert(2);\n s.insert(9);\n s.insert(10);\n cout << \"Elements are in set:\\n\";\n for ( auto it : s)\n cout << it << \" \"; //printing elements of the set container\n return 0;\n}" }, { "code": null, "e": 2255, "s": 2240, "text": "1 2 4 6 7 9 10" }, { "code": null, "e": 2266, "s": 2255, "text": " Live Demo" }, { "code": null, "e": 2779, "s": 2266, "text": "#include<iostream>\n#include <bits/stdc++.h>\nusing namespace std;\n\nint main()\n{\n map<char, int> m; //initialize a map\n map<char, int>::iterator iter; //initializing a map as iterator\n m.insert (pair<char, int>('a', 10)); //inserting values to the map\n m.insert (pair<char, int>('b', 20));\n\n cout << \"Elements in map:\\n\";\n for (iter=m.begin();iter!=m.end();iter++)\n cout << \"[ \" << iter->first << \", \"<< iter->second << \"]\\n\"; //printing the values of the map\n return 0;\n}" }, { "code": null, "e": 2816, "s": 2779, "text": "Elements in map: \n[ a, 10] \n[ b, 20]" } ]
Click Module in Python | Making awesome Command Line Utilities - GeeksforGeeks
14 Mar, 2019 Since the dawn of the computer age and before the internet outburst, programmers have been using command line tools in an interactive shell as a means to communicate with the computers. It is kind of strange that with all the advancements in UI/UX technologies, very few people know that there are to create beautiful command line interfaces too.Ever wanted to create a command line tool yourself that is actually very user-friendly, efficient and easy to use? Well, click is a Python Package that does just that. There are many Python packages that we could use instead of click such as argparse, docopt, etc., so we will first look at why we are using click. Why Click? There are a couple of reasons why click is the better tool for the job. Click is lazily composable without restrictions. It is fully nested. Click has strong information available for all parameters and commands so that it can generate unified help pages for the full CLI and to assist the user in converting the input data as necessary. Click has a strong understanding of what types are and can give the user consistent error messages if something goes wrong. Installation: pip install click Basics of a Command Line Interface: Depending on the type and purpose of the CLI, it can have a variety of functionalities. You probably would already have used pip which is also a CLI. Some basics functions which all CLIs have are: An argument. An option, which is an optional parameter A flag, this is a special option which enables or disables a certain function. One of the most common flags is –help. Simple program using click : # importing clickimport click @click.command()def main(): click.echo("This cli is built with click. ") if __name__=="__main__": main() So let’s build a command line tool that will print a greeting for the name provided in the arguments. Argument Parsing: Click uses the python decorators for parsing arguments related to a function. @click.command()@click.argument('name')def greeting(name): click.echo("Hello, {}".format(name)) if __name__=="__main__": greeting() >>> python greet.py Gifoyle Hello, Gilfoyle Optional arguments: Click gives the option to include optional parameters in the form of flags. import click @click.command()@click.option('--string', default ='World', help ='This is a greeting')def hello(string): click.echo("Hello, {}".format(string)) if __name__=="__main__":hello() >>> python hello.py Hello, World >>> python hello.py --string Dinesh Hello, Dinesh Help: The most important and final step towards making the perfect CLI is to provide documentation to our code. Click provides a nice and formatted help text in the command line when used the optional argument --help. It uses the docstring specified in the function. import click @click.command()@click.argument(‘greeting’)def cli(greeting): ''' This is the default CLI method. Arguments: greeting: {string} ''' click.echo(greeting) click.echo ("This is a simple cli.") if __name__=="__main": cli() >>> python cli.py --helpThis is the default CLI method. Arguments: greeting: {string} Options: --string TEXT Hello --help Show this message and exit. >>> Error Handling: Error handling is an important part of a CLI. How your script handles and manages the errors matters a lot and also helps the user to better understand the mistake. >>> python cli.pyThis is a simple cli. >>> python cli.py hello Usage: greet.py [OPTIONS] Try "greet.py --help" for help. Error: Got unexpected extra argument (hello) Marketing python-modules Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Check if element exists in list in Python Selecting rows in pandas DataFrame based on conditions Python | os.path.join() method Defaultdict in Python Python | Get unique values from a list Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24292, "s": 24264, "text": "\n14 Mar, 2019" }, { "code": null, "e": 24953, "s": 24292, "text": "Since the dawn of the computer age and before the internet outburst, programmers have been using command line tools in an interactive shell as a means to communicate with the computers. It is kind of strange that with all the advancements in UI/UX technologies, very few people know that there are to create beautiful command line interfaces too.Ever wanted to create a command line tool yourself that is actually very user-friendly, efficient and easy to use? Well, click is a Python Package that does just that. There are many Python packages that we could use instead of click such as argparse, docopt, etc., so we will first look at why we are using click." }, { "code": null, "e": 24964, "s": 24953, "text": "Why Click?" }, { "code": null, "e": 25036, "s": 24964, "text": "There are a couple of reasons why click is the better tool for the job." }, { "code": null, "e": 25085, "s": 25036, "text": "Click is lazily composable without restrictions." }, { "code": null, "e": 25105, "s": 25085, "text": "It is fully nested." }, { "code": null, "e": 25302, "s": 25105, "text": "Click has strong information available for all parameters and commands so that it can generate unified help pages for the full CLI and to assist the user in converting the input data as necessary." }, { "code": null, "e": 25426, "s": 25302, "text": "Click has a strong understanding of what types are and can give the user consistent error messages if something goes wrong." }, { "code": null, "e": 25440, "s": 25426, "text": "Installation:" }, { "code": null, "e": 25458, "s": 25440, "text": "pip install click" }, { "code": null, "e": 25494, "s": 25458, "text": "Basics of a Command Line Interface:" }, { "code": null, "e": 25691, "s": 25494, "text": "Depending on the type and purpose of the CLI, it can have a variety of functionalities. You probably would already have used pip which is also a CLI. Some basics functions which all CLIs have are:" }, { "code": null, "e": 25704, "s": 25691, "text": "An argument." }, { "code": null, "e": 25746, "s": 25704, "text": "An option, which is an optional parameter" }, { "code": null, "e": 25864, "s": 25746, "text": "A flag, this is a special option which enables or disables a certain function. One of the most common flags is –help." }, { "code": null, "e": 25893, "s": 25864, "text": "Simple program using click :" }, { "code": "# importing clickimport click @click.command()def main(): click.echo(\"This cli is built with click. \") if __name__==\"__main__\": main()", "e": 26036, "s": 25893, "text": null }, { "code": null, "e": 26138, "s": 26036, "text": "So let’s build a command line tool that will print a greeting for the name provided in the arguments." }, { "code": null, "e": 26234, "s": 26138, "text": "Argument Parsing: Click uses the python decorators for parsing arguments related to a function." }, { "code": "@click.command()@click.argument('name')def greeting(name): click.echo(\"Hello, {}\".format(name)) if __name__==\"__main__\": greeting()", "e": 26373, "s": 26234, "text": null }, { "code": null, "e": 26401, "s": 26373, "text": ">>> python greet.py Gifoyle" }, { "code": null, "e": 26417, "s": 26401, "text": "Hello, Gilfoyle" }, { "code": null, "e": 26514, "s": 26417, "text": " Optional arguments: Click gives the option to include optional parameters in the form of flags." }, { "code": "import click @click.command()@click.option('--string', default ='World', help ='This is a greeting')def hello(string): click.echo(\"Hello, {}\".format(string)) if __name__==\"__main__\":hello() ", "e": 26720, "s": 26514, "text": null }, { "code": null, "e": 26740, "s": 26720, "text": ">>> python hello.py" }, { "code": null, "e": 26753, "s": 26740, "text": "Hello, World" }, { "code": null, "e": 26789, "s": 26753, "text": ">>> python hello.py --string Dinesh" }, { "code": null, "e": 26803, "s": 26789, "text": "Hello, Dinesh" }, { "code": null, "e": 27071, "s": 26803, "text": " Help: The most important and final step towards making the perfect CLI is to provide documentation to our code. Click provides a nice and formatted help text in the command line when used the optional argument --help. It uses the docstring specified in the function." }, { "code": "import click @click.command()@click.argument(‘greeting’)def cli(greeting): ''' This is the default CLI method. Arguments: greeting: {string} ''' click.echo(greeting) click.echo (\"This is a simple cli.\") if __name__==\"__main\": cli()", "e": 27345, "s": 27071, "text": null }, { "code": null, "e": 27401, "s": 27345, "text": ">>> python cli.py --helpThis is the default CLI method." }, { "code": null, "e": 27518, "s": 27401, "text": " \nArguments:\ngreeting: {string}\n\nOptions:\n --string TEXT Hello\n --help Show this message and exit.\n>>>" }, { "code": null, "e": 27700, "s": 27518, "text": " Error Handling: Error handling is an important part of a CLI. How your script handles and manages the errors matters a lot and also helps the user to better understand the mistake." }, { "code": null, "e": 27739, "s": 27700, "text": ">>> python cli.pyThis is a simple cli." }, { "code": null, "e": 27763, "s": 27739, "text": ">>> python cli.py hello" }, { "code": null, "e": 27867, "s": 27763, "text": "Usage: greet.py [OPTIONS]\nTry \"greet.py --help\" for help.\n\nError: Got unexpected extra argument (hello)" }, { "code": null, "e": 27877, "s": 27867, "text": "Marketing" }, { "code": null, "e": 27892, "s": 27877, "text": "python-modules" }, { "code": null, "e": 27899, "s": 27892, "text": "Python" }, { "code": null, "e": 27997, "s": 27899, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28029, "s": 27997, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28071, "s": 28029, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28127, "s": 28071, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28169, "s": 28127, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28224, "s": 28169, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 28255, "s": 28224, "text": "Python | os.path.join() method" }, { "code": null, "e": 28277, "s": 28255, "text": "Defaultdict in Python" }, { "code": null, "e": 28316, "s": 28277, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28345, "s": 28316, "text": "Create a directory in Python" } ]
Beginner’s Guide to LDA Topic Modelling with R | by Farren tang | Towards Data Science
Nowadays many people want to start out with Natural Language Processing(NLP). Yet they don’t know where and how to start. It might be because there are too many “guides” or “readings” available, but they don’t exactly tell you where and how to start. This article aims to give readers a step-by-step guide on how to do topic modelling using Latent Dirichlet Allocation (LDA) analysis with R. This technique is simple and works effectively on small dataset. Hence, I would suggest this technique for people who are trying out NLP and using topic modelling for the first time. What is topic modelling? In layman terms, topic modelling is trying to find similar topics across different documents, and trying to group different words together, such that each topic will consist of words with similar meanings. An analogy that I often like to give is — when you have a story book that is torn into different pages. After you try to run a topic modelling algorithm, you should be able to come up with various topics such that each topic would consist of words from each chapter. Otherwise, you may simply just use sentiment analysis — positive or negative review. In machine learning and natural language processing, a topic model is a type of statistical model for discovering the abstract “topics” that occur in a collection of documents. - wikipedia After a formal introduction to topic modelling, the remaining part of the article will describe a step by step process on how to go about topic modeling. It is made up of 4 parts: loading of data, pre-processing of data, building the model and visualisation of the words in a topic. As mentioned above, I will be using LDA model, a probabilistic model that assigns word a probabilistic score of the most probable topic that it could be potentially belong to. I will skip the technical explanation of LDA as there are many write-ups available.(Eg: Here) Not to worry, I will explain all terminologies if I am using it. Loading of data Loading of data The dataset we will be using for simplicity purpose will be the first 5000 rows of twitter sentiments data from kaggle. For our model, we do not need to have labelled data. All we need is a text column that we want to create topics from and a set of unique id. There was initially 18 columns and 13000 rows of data, but we will just be using the text and id columns. data <- fread(“~/Sentiment.csv”)#looking at top 5000 rowsdata <- data %>% select(text,id) %>% head(5000) 2. Pre-processing As we observe from the text, there are many tweets which consist of irrelevant information: such as RT, the twitter handle, punctuation, stopwords (and, or the, etc) and numbers. These will add unnecessary noise to our dataset which we need to remove during the pre-processing stage. data$text <- sub("RT.*:", "", data$text)data$text <- sub("@.* ", "", data$text)text_cleaning_tokens <- data %>% tidytext::unnest_tokens(word, text)text_cleaning_tokens$word <- gsub('[[:digit:]]+', '', text_cleaning_tokens$word)text_cleaning_tokens$word <- gsub('[[:punct:]]+', '', text_cleaning_tokens$word)text_cleaning_tokens <- text_cleaning_tokens %>% filter(!(nchar(word) == 1))%>% anti_join(stop_words)tokens <- text_cleaning_tokens %>% filter(!(word==""))tokens <- tokens %>% mutate(ind = row_number())tokens <- tokens %>% group_by(id) %>% mutate(ind = row_number()) %>% tidyr::spread(key = ind, value = word)tokens [is.na(tokens)] <- ""tokens <- tidyr::unite(tokens, text,-id,sep =" " )tokens$text <- trimws(tokens$text) 3. Model Building Finally here comes the fun part! Creating the model. First you will have to create a DTM(document term matrix), which is a sparse matrix containing your terms and documents as dimensions. When building the DTM, you can select how you want to tokenise(break up a sentence into 1 word or 2 words) your text. This will depend on how you want the LDA to read your words. You will need to ask yourself if singular words or bigram(phrases) makes sense in your context. For instance if your texts contain many words such as “failed executing” or “not appreciating”, then you will have to let the algorithm choose a window of maximum 2 words. Otherwise using a unigram will work just as fine. In our case, because it’s Twitter sentiment, we will go with a window size of 1–2 words, and let the algorithm decide for us, which are the more important phrases to concatenate together. We will also explore the term frequency matrix, which shows the number of times the word/phrase is occurring in the entire corpus of text. If the term is < 2 times, we discard them, as it does not add any value to the algorithm, and it will help to reduce computation time as well. #create DTMdtm <- CreateDtm(tokens$text, doc_names = tokens$ID, ngram_window = c(1, 2))#explore the basic frequencytf <- TermDocFreq(dtm = dtm)original_tf <- tf %>% select(term, term_freq,doc_freq)rownames(original_tf) <- 1:nrow(original_tf)# Eliminate words appearing less than 2 times or in more than half of the# documentsvocabulary <- tf$term[ tf$term_freq > 1 & tf$doc_freq < nrow(dtm) / 2 ]dtm = dtm With your DTM, you run the LDA algorithm for topic modelling. You will have to manually assign a number of topics k. Next, the algorithm will calculate a coherence score to allow us to choose the best topics from 1 to k. What is coherence and coherence score? Coherence gives the probabilistic coherence of each topic. Coherence score is a score that calculates if the words in the same topic make sense when they are put together. This gives us the quality of the topics being produced. The higher the score for the specific number of k, it means for each topic, there will be more related words together and the topic will make more sense. For instance: {dog, talk, television, book} vs {dog, ball, bark, bone}. The latter will yield a higher coherence score than the former as the words are more closely related. In our example, we set k = 20 and run the LDA on it, and plot the coherence score. It’s up to the analyst to define how many topics they want. k_list <- seq(1, 20, by = 1)model_dir <- paste0("models_", digest::digest(vocabulary, algo = "sha1"))if (!dir.exists(model_dir)) dir.create(model_dir)model_list <- TmParallelApply(X = k_list, FUN = function(k){ filename = file.path(model_dir, paste0(k, "_topics.rda")) if (!file.exists(filename)) { m <- FitLdaModel(dtm = dtm, k = k, iterations = 500) m$k <- k m$coherence <- CalcProbCoherence(phi = m$phi, dtm = dtm, M = 5) save(m, file = filename) } else { load(filename) } m}, export=c("dtm", "model_dir")) # export only needed for Windows machines#model tuning#choosing the best modelcoherence_mat <- data.frame(k = sapply(model_list, function(x) nrow(x$phi)), coherence = sapply(model_list, function(x) mean(x$coherence)), stringsAsFactors = FALSE)ggplot(coherence_mat, aes(x = k, y = coherence)) + geom_point() + geom_line(group = 1)+ ggtitle("Best Topic by Coherence Score") + theme_minimal() + scale_x_continuous(breaks = seq(1,20,1)) + ylab("Coherence") Upon plotting of the k, we realise that k = 12 gives us the highest coherence score. In this case, even though the coherence score is rather low and there will definitely be a need to tune the model, such as increasing k to achieve better results or have more texts. But for explanation purpose, we will ignore the value and just go with the highest coherence score. After understanding the optimal number of topics, we want to have a peek of the different words within the topic. Each topic will have each word/phrase assigned a phi value (pr(word|topic)) — probability of word given a topic. So we only take into account the top 20 values per word in each topic. The top 20 terms will then describe what the topic is about. model <- model_list[which.max(coherence_mat$coherence)][[ 1 ]]model$top_terms <- GetTopTerms(phi = model$phi, M = 20)top20_wide <- as.data.frame(model$top_terms) The above picture shows the first 5 topics out of the 12 topics. The words are in ascending order of phi-value. The higher the ranking, the more probable the word will belong to the topic. It seems like there are a couple of overlapping topics. It’s up to the analyst to think if we should combine the different topics together by eyeballing or we can run a Dendogram to see which topics should be grouped together. A Dendogram uses Hellinger distance(distance between 2 probability vectors) to decide if the topics are closely related. For instance, the Dendogram below suggests that there are greater similarity between topic 10 and 11. model$topic_linguistic_dist <- CalcHellingerDist(model$phi)model$hclust <- hclust(as.dist(model$topic_linguistic_dist), "ward.D")model$hclust$labels <- paste(model$hclust$labels, model$labels[ , 1])plot(model$hclust) 4. Visualisation We can create word cloud to see the words belonging to the certain topic, based on the probability. Below represents topic 2. As ‘gopdebate’ is the most probable word in topic2, the size will be the largest in the word cloud. #visualising topics of words based on the max value of phiset.seed(1234)final_summary_words <- data.frame(top_terms = t(model$top_terms))final_summary_words$topic <- rownames(final_summary_words)rownames(final_summary_words) <- 1:nrow(final_summary_words)final_summary_words <- final_summary_words %>% melt(id.vars = c("topic"))final_summary_words <- final_summary_words %>% rename(word = value) %>% select(-variable)final_summary_words <- left_join(final_summary_words,allterms)final_summary_words <- final_summary_words %>% group_by(topic,word) %>% arrange(desc(value))final_summary_words <- final_summary_words %>% group_by(topic, word) %>% filter(row_number() == 1) %>% ungroup() %>% tidyr::separate(topic, into =c("t","topic")) %>% select(-t)word_topic_freq <- left_join(final_summary_words, original_tf, by = c("word" = "term"))pdf("cluster.pdf")for(i in 1:length(unique(final_summary_words$topic))){ wordcloud(words = subset(final_summary_words ,topic == i)$word, freq = subset(final_summary_words ,topic == i)$value, min.freq = 1, max.words=200, random.order=FALSE, rot.per=0.35, colors=brewer.pal(8, "Dark2"))}dev.off() 5. Conclusion We are done with this simple topic modelling using LDA and visualisation with word cloud. You may refer to my github for the entire script and more details. This is not a full-fledged LDA tutorial, as there are other cool metrics available but I hope this article will provide you with a good guide on how to start with topic modelling in R using LDA. I would also strongly suggest everyone to read up on other kind of algorithms too. I’m sure you will not get bored by it! Feel free to drop me a message if you think that I am missing out on anything. Happy topic modeling! References: WikipediaTyler Doll, LDA Topic Modelling (2018)Thomas W. Jones, Topic Modelling (2019) Wikipedia Tyler Doll, LDA Topic Modelling (2018) Thomas W. Jones, Topic Modelling (2019)
[ { "code": null, "e": 439, "s": 47, "text": "Nowadays many people want to start out with Natural Language Processing(NLP). Yet they don’t know where and how to start. It might be because there are too many “guides” or “readings” available, but they don’t exactly tell you where and how to start. This article aims to give readers a step-by-step guide on how to do topic modelling using Latent Dirichlet Allocation (LDA) analysis with R." }, { "code": null, "e": 622, "s": 439, "text": "This technique is simple and works effectively on small dataset. Hence, I would suggest this technique for people who are trying out NLP and using topic modelling for the first time." }, { "code": null, "e": 1205, "s": 622, "text": "What is topic modelling? In layman terms, topic modelling is trying to find similar topics across different documents, and trying to group different words together, such that each topic will consist of words with similar meanings. An analogy that I often like to give is — when you have a story book that is torn into different pages. After you try to run a topic modelling algorithm, you should be able to come up with various topics such that each topic would consist of words from each chapter. Otherwise, you may simply just use sentiment analysis — positive or negative review." }, { "code": null, "e": 1394, "s": 1205, "text": "In machine learning and natural language processing, a topic model is a type of statistical model for discovering the abstract “topics” that occur in a collection of documents. - wikipedia" }, { "code": null, "e": 1677, "s": 1394, "text": "After a formal introduction to topic modelling, the remaining part of the article will describe a step by step process on how to go about topic modeling. It is made up of 4 parts: loading of data, pre-processing of data, building the model and visualisation of the words in a topic." }, { "code": null, "e": 2012, "s": 1677, "text": "As mentioned above, I will be using LDA model, a probabilistic model that assigns word a probabilistic score of the most probable topic that it could be potentially belong to. I will skip the technical explanation of LDA as there are many write-ups available.(Eg: Here) Not to worry, I will explain all terminologies if I am using it." }, { "code": null, "e": 2028, "s": 2012, "text": "Loading of data" }, { "code": null, "e": 2044, "s": 2028, "text": "Loading of data" }, { "code": null, "e": 2411, "s": 2044, "text": "The dataset we will be using for simplicity purpose will be the first 5000 rows of twitter sentiments data from kaggle. For our model, we do not need to have labelled data. All we need is a text column that we want to create topics from and a set of unique id. There was initially 18 columns and 13000 rows of data, but we will just be using the text and id columns." }, { "code": null, "e": 2516, "s": 2411, "text": "data <- fread(“~/Sentiment.csv”)#looking at top 5000 rowsdata <- data %>% select(text,id) %>% head(5000)" }, { "code": null, "e": 2534, "s": 2516, "text": "2. Pre-processing" }, { "code": null, "e": 2818, "s": 2534, "text": "As we observe from the text, there are many tweets which consist of irrelevant information: such as RT, the twitter handle, punctuation, stopwords (and, or the, etc) and numbers. These will add unnecessary noise to our dataset which we need to remove during the pre-processing stage." }, { "code": null, "e": 3552, "s": 2818, "text": "data$text <- sub(\"RT.*:\", \"\", data$text)data$text <- sub(\"@.* \", \"\", data$text)text_cleaning_tokens <- data %>% tidytext::unnest_tokens(word, text)text_cleaning_tokens$word <- gsub('[[:digit:]]+', '', text_cleaning_tokens$word)text_cleaning_tokens$word <- gsub('[[:punct:]]+', '', text_cleaning_tokens$word)text_cleaning_tokens <- text_cleaning_tokens %>% filter(!(nchar(word) == 1))%>% anti_join(stop_words)tokens <- text_cleaning_tokens %>% filter(!(word==\"\"))tokens <- tokens %>% mutate(ind = row_number())tokens <- tokens %>% group_by(id) %>% mutate(ind = row_number()) %>% tidyr::spread(key = ind, value = word)tokens [is.na(tokens)] <- \"\"tokens <- tidyr::unite(tokens, text,-id,sep =\" \" )tokens$text <- trimws(tokens$text)" }, { "code": null, "e": 3570, "s": 3552, "text": "3. Model Building" }, { "code": null, "e": 3623, "s": 3570, "text": "Finally here comes the fun part! Creating the model." }, { "code": null, "e": 4725, "s": 3623, "text": "First you will have to create a DTM(document term matrix), which is a sparse matrix containing your terms and documents as dimensions. When building the DTM, you can select how you want to tokenise(break up a sentence into 1 word or 2 words) your text. This will depend on how you want the LDA to read your words. You will need to ask yourself if singular words or bigram(phrases) makes sense in your context. For instance if your texts contain many words such as “failed executing” or “not appreciating”, then you will have to let the algorithm choose a window of maximum 2 words. Otherwise using a unigram will work just as fine. In our case, because it’s Twitter sentiment, we will go with a window size of 1–2 words, and let the algorithm decide for us, which are the more important phrases to concatenate together. We will also explore the term frequency matrix, which shows the number of times the word/phrase is occurring in the entire corpus of text. If the term is < 2 times, we discard them, as it does not add any value to the algorithm, and it will help to reduce computation time as well." }, { "code": null, "e": 5165, "s": 4725, "text": "#create DTMdtm <- CreateDtm(tokens$text, doc_names = tokens$ID, ngram_window = c(1, 2))#explore the basic frequencytf <- TermDocFreq(dtm = dtm)original_tf <- tf %>% select(term, term_freq,doc_freq)rownames(original_tf) <- 1:nrow(original_tf)# Eliminate words appearing less than 2 times or in more than half of the# documentsvocabulary <- tf$term[ tf$term_freq > 1 & tf$doc_freq < nrow(dtm) / 2 ]dtm = dtm" }, { "code": null, "e": 5981, "s": 5165, "text": "With your DTM, you run the LDA algorithm for topic modelling. You will have to manually assign a number of topics k. Next, the algorithm will calculate a coherence score to allow us to choose the best topics from 1 to k. What is coherence and coherence score? Coherence gives the probabilistic coherence of each topic. Coherence score is a score that calculates if the words in the same topic make sense when they are put together. This gives us the quality of the topics being produced. The higher the score for the specific number of k, it means for each topic, there will be more related words together and the topic will make more sense. For instance: {dog, talk, television, book} vs {dog, ball, bark, bone}. The latter will yield a higher coherence score than the former as the words are more closely related." }, { "code": null, "e": 6124, "s": 5981, "text": "In our example, we set k = 20 and run the LDA on it, and plot the coherence score. It’s up to the analyst to define how many topics they want." }, { "code": null, "e": 7171, "s": 6124, "text": "k_list <- seq(1, 20, by = 1)model_dir <- paste0(\"models_\", digest::digest(vocabulary, algo = \"sha1\"))if (!dir.exists(model_dir)) dir.create(model_dir)model_list <- TmParallelApply(X = k_list, FUN = function(k){ filename = file.path(model_dir, paste0(k, \"_topics.rda\")) if (!file.exists(filename)) { m <- FitLdaModel(dtm = dtm, k = k, iterations = 500) m$k <- k m$coherence <- CalcProbCoherence(phi = m$phi, dtm = dtm, M = 5) save(m, file = filename) } else { load(filename) } m}, export=c(\"dtm\", \"model_dir\")) # export only needed for Windows machines#model tuning#choosing the best modelcoherence_mat <- data.frame(k = sapply(model_list, function(x) nrow(x$phi)), coherence = sapply(model_list, function(x) mean(x$coherence)), stringsAsFactors = FALSE)ggplot(coherence_mat, aes(x = k, y = coherence)) + geom_point() + geom_line(group = 1)+ ggtitle(\"Best Topic by Coherence Score\") + theme_minimal() + scale_x_continuous(breaks = seq(1,20,1)) + ylab(\"Coherence\")" }, { "code": null, "e": 7897, "s": 7171, "text": "Upon plotting of the k, we realise that k = 12 gives us the highest coherence score. In this case, even though the coherence score is rather low and there will definitely be a need to tune the model, such as increasing k to achieve better results or have more texts. But for explanation purpose, we will ignore the value and just go with the highest coherence score. After understanding the optimal number of topics, we want to have a peek of the different words within the topic. Each topic will have each word/phrase assigned a phi value (pr(word|topic)) — probability of word given a topic. So we only take into account the top 20 values per word in each topic. The top 20 terms will then describe what the topic is about." }, { "code": null, "e": 8059, "s": 7897, "text": "model <- model_list[which.max(coherence_mat$coherence)][[ 1 ]]model$top_terms <- GetTopTerms(phi = model$phi, M = 20)top20_wide <- as.data.frame(model$top_terms)" }, { "code": null, "e": 8698, "s": 8059, "text": "The above picture shows the first 5 topics out of the 12 topics. The words are in ascending order of phi-value. The higher the ranking, the more probable the word will belong to the topic. It seems like there are a couple of overlapping topics. It’s up to the analyst to think if we should combine the different topics together by eyeballing or we can run a Dendogram to see which topics should be grouped together. A Dendogram uses Hellinger distance(distance between 2 probability vectors) to decide if the topics are closely related. For instance, the Dendogram below suggests that there are greater similarity between topic 10 and 11." }, { "code": null, "e": 8915, "s": 8698, "text": "model$topic_linguistic_dist <- CalcHellingerDist(model$phi)model$hclust <- hclust(as.dist(model$topic_linguistic_dist), \"ward.D\")model$hclust$labels <- paste(model$hclust$labels, model$labels[ , 1])plot(model$hclust)" }, { "code": null, "e": 8932, "s": 8915, "text": "4. Visualisation" }, { "code": null, "e": 9158, "s": 8932, "text": "We can create word cloud to see the words belonging to the certain topic, based on the probability. Below represents topic 2. As ‘gopdebate’ is the most probable word in topic2, the size will be the largest in the word cloud." }, { "code": null, "e": 10316, "s": 9158, "text": "#visualising topics of words based on the max value of phiset.seed(1234)final_summary_words <- data.frame(top_terms = t(model$top_terms))final_summary_words$topic <- rownames(final_summary_words)rownames(final_summary_words) <- 1:nrow(final_summary_words)final_summary_words <- final_summary_words %>% melt(id.vars = c(\"topic\"))final_summary_words <- final_summary_words %>% rename(word = value) %>% select(-variable)final_summary_words <- left_join(final_summary_words,allterms)final_summary_words <- final_summary_words %>% group_by(topic,word) %>% arrange(desc(value))final_summary_words <- final_summary_words %>% group_by(topic, word) %>% filter(row_number() == 1) %>% ungroup() %>% tidyr::separate(topic, into =c(\"t\",\"topic\")) %>% select(-t)word_topic_freq <- left_join(final_summary_words, original_tf, by = c(\"word\" = \"term\"))pdf(\"cluster.pdf\")for(i in 1:length(unique(final_summary_words$topic))){ wordcloud(words = subset(final_summary_words ,topic == i)$word, freq = subset(final_summary_words ,topic == i)$value, min.freq = 1, max.words=200, random.order=FALSE, rot.per=0.35, colors=brewer.pal(8, \"Dark2\"))}dev.off()" }, { "code": null, "e": 10330, "s": 10316, "text": "5. Conclusion" }, { "code": null, "e": 10804, "s": 10330, "text": "We are done with this simple topic modelling using LDA and visualisation with word cloud. You may refer to my github for the entire script and more details. This is not a full-fledged LDA tutorial, as there are other cool metrics available but I hope this article will provide you with a good guide on how to start with topic modelling in R using LDA. I would also strongly suggest everyone to read up on other kind of algorithms too. I’m sure you will not get bored by it!" }, { "code": null, "e": 10883, "s": 10804, "text": "Feel free to drop me a message if you think that I am missing out on anything." }, { "code": null, "e": 10905, "s": 10883, "text": "Happy topic modeling!" }, { "code": null, "e": 10917, "s": 10905, "text": "References:" }, { "code": null, "e": 11004, "s": 10917, "text": "WikipediaTyler Doll, LDA Topic Modelling (2018)Thomas W. Jones, Topic Modelling (2019)" }, { "code": null, "e": 11014, "s": 11004, "text": "Wikipedia" }, { "code": null, "e": 11053, "s": 11014, "text": "Tyler Doll, LDA Topic Modelling (2018)" } ]
Scala | Pattern Matching - GeeksforGeeks
17 Jan, 2019 Pattern matching is a way of checking the given sequence of tokens for the presence of the specific pattern. It is the most widely used feature in Scala. It is a technique for checking a value against a pattern. It is similar to the switch statement of Java and C. Here, “match” keyword is used instead of switch statement. “match” is always defined in Scala’s root class to make its availability to the all objects. This can contain a sequence of alternatives. Each alternative will start from case keyword. Each case statement includes a pattern and one or more expression which get evaluated if the specified pattern gets matched. To separate the pattern from the expressions, arrow symbol(=>) is used. Example 1: // Scala program to illustrate // the pattern matching object GeeksforGeeks { // main method def main(args: Array[String]) { // calling test method println(test(1)); } // method containing match keyword def test(x:Int): String = x match { // if value of x is 0, // this case will be executed case 0 => "Hello, Geeks!!" // if value of x is 1, // this case will be executed case 1 => "Are you learning Scala?" // if x doesnt match any sequence, // then this case will be executed case _ => "Good Luck!!" }} Output: Are you learning Scala? Explanation: In the above program, if the value of x which is passed in test method call matches any of the cases, the expression within that case is evaluated. Here we are passing 1 so case 1 will be evaluated. case_ => is the default case which will get executed if value of x is not 0 or 1. Example 2: // Scala program to illustrate // the pattern matching object GeeksforGeeks { // main method def main(args: Array[String]) { // calling test method println(test("Geeks")); } // method containing match keyword def test(x:String): String = x match { // if value of x is "G1", // this case will be executed case "G1" => "GFG" // if value of x is "G2", // this case will be executed case "G2" => "Scala Tutorials" // if x doesnt match any sequence, // then this case will be executed case _ => "Default Case Executed" }} Output: Default Case Executed Important Points: Each match keyword must have at least one case clause. The last “_“, is a “catch-all” case, will be executed if none of the cases matches. Cases are also called alternatives. Pattern matching does not have any break statement. Pattern matching always returns some value. Match blocks are expressions, not statements. This means that they evaluate the body of whichever case matches. This is a very important feature of functional programming. Pattern matching can also be used for value assignment and for comprehension, not only in match block. Pattern matching allows matching any sort of data with the first match policy. Each case statement returns a value, and the whole match statement is virtually a function that returns a matched value. Multiple values can be tested in a single line by using “|“. Scala Scala Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Scala Tutorial – Learn Scala with Step By Step Guide Scala List filter() method with example Scala Map Type Casting in Scala Scala Lists Scala List contains() method with example Scala String substring() method with example Lambda Expression in Scala Scala String replace() method with example
[ { "code": null, "e": 23439, "s": 23411, "text": "\n17 Jan, 2019" }, { "code": null, "e": 23704, "s": 23439, "text": "Pattern matching is a way of checking the given sequence of tokens for the presence of the specific pattern. It is the most widely used feature in Scala. It is a technique for checking a value against a pattern. It is similar to the switch statement of Java and C." }, { "code": null, "e": 24145, "s": 23704, "text": "Here, “match” keyword is used instead of switch statement. “match” is always defined in Scala’s root class to make its availability to the all objects. This can contain a sequence of alternatives. Each alternative will start from case keyword. Each case statement includes a pattern and one or more expression which get evaluated if the specified pattern gets matched. To separate the pattern from the expressions, arrow symbol(=>) is used." }, { "code": null, "e": 24156, "s": 24145, "text": "Example 1:" }, { "code": "// Scala program to illustrate // the pattern matching object GeeksforGeeks { // main method def main(args: Array[String]) { // calling test method println(test(1)); } // method containing match keyword def test(x:Int): String = x match { // if value of x is 0, // this case will be executed case 0 => \"Hello, Geeks!!\" // if value of x is 1, // this case will be executed case 1 => \"Are you learning Scala?\" // if x doesnt match any sequence, // then this case will be executed case _ => \"Good Luck!!\" }}", "e": 24793, "s": 24156, "text": null }, { "code": null, "e": 24801, "s": 24793, "text": "Output:" }, { "code": null, "e": 24826, "s": 24801, "text": "Are you learning Scala?\n" }, { "code": null, "e": 25120, "s": 24826, "text": "Explanation: In the above program, if the value of x which is passed in test method call matches any of the cases, the expression within that case is evaluated. Here we are passing 1 so case 1 will be evaluated. case_ => is the default case which will get executed if value of x is not 0 or 1." }, { "code": null, "e": 25131, "s": 25120, "text": "Example 2:" }, { "code": "// Scala program to illustrate // the pattern matching object GeeksforGeeks { // main method def main(args: Array[String]) { // calling test method println(test(\"Geeks\")); } // method containing match keyword def test(x:String): String = x match { // if value of x is \"G1\", // this case will be executed case \"G1\" => \"GFG\" // if value of x is \"G2\", // this case will be executed case \"G2\" => \"Scala Tutorials\" // if x doesnt match any sequence, // then this case will be executed case _ => \"Default Case Executed\" }}", "e": 25788, "s": 25131, "text": null }, { "code": null, "e": 25796, "s": 25788, "text": "Output:" }, { "code": null, "e": 25819, "s": 25796, "text": "Default Case Executed\n" }, { "code": null, "e": 25837, "s": 25819, "text": "Important Points:" }, { "code": null, "e": 25892, "s": 25837, "text": "Each match keyword must have at least one case clause." }, { "code": null, "e": 26012, "s": 25892, "text": "The last “_“, is a “catch-all” case, will be executed if none of the cases matches. Cases are also called alternatives." }, { "code": null, "e": 26064, "s": 26012, "text": "Pattern matching does not have any break statement." }, { "code": null, "e": 26108, "s": 26064, "text": "Pattern matching always returns some value." }, { "code": null, "e": 26280, "s": 26108, "text": "Match blocks are expressions, not statements. This means that they evaluate the body of whichever case matches. This is a very important feature of functional programming." }, { "code": null, "e": 26383, "s": 26280, "text": "Pattern matching can also be used for value assignment and for comprehension, not only in match block." }, { "code": null, "e": 26462, "s": 26383, "text": "Pattern matching allows matching any sort of data with the first match policy." }, { "code": null, "e": 26583, "s": 26462, "text": "Each case statement returns a value, and the whole match statement is virtually a function that returns a matched value." }, { "code": null, "e": 26644, "s": 26583, "text": "Multiple values can be tested in a single line by using “|“." }, { "code": null, "e": 26650, "s": 26644, "text": "Scala" }, { "code": null, "e": 26656, "s": 26650, "text": "Scala" }, { "code": null, "e": 26754, "s": 26656, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26763, "s": 26754, "text": "Comments" }, { "code": null, "e": 26776, "s": 26763, "text": "Old Comments" }, { "code": null, "e": 26829, "s": 26776, "text": "Scala Tutorial – Learn Scala with Step By Step Guide" }, { "code": null, "e": 26869, "s": 26829, "text": "Scala List filter() method with example" }, { "code": null, "e": 26879, "s": 26869, "text": "Scala Map" }, { "code": null, "e": 26901, "s": 26879, "text": "Type Casting in Scala" }, { "code": null, "e": 26913, "s": 26901, "text": "Scala Lists" }, { "code": null, "e": 26955, "s": 26913, "text": "Scala List contains() method with example" }, { "code": null, "e": 27000, "s": 26955, "text": "Scala String substring() method with example" }, { "code": null, "e": 27027, "s": 27000, "text": "Lambda Expression in Scala" } ]
HTML5 Canvas - Animations
HTML5 canvas provides necessary methods to draw an image and erase it completely. We can take Javascript help to simulate good animation over a HTML5 canvas. Following are the two important Javascript methods which would be used to animate an image on a canvas − setInterval(callback, time); This method repeatedly executes the supplied code after a given timemilliseconds. setTimeout(callback, time); This method executes the supplied code only once after a given time milliseconds. Following is a simple example which would rotate a small image repeatedly − <!DOCTYPE HTML> <html> <head> <script type = "text/javascript"> var pattern = new Image(); function animate() { pattern.src = '/html5/images/pattern.jpg'; setInterval(drawShape, 100); } function drawShape() { // get the canvas element using the DOM var canvas = document.getElementById('mycanvas'); // Make sure we don't execute when canvas isn't supported if (canvas.getContext) { // use getContext to use the canvas for drawing var ctx = canvas.getContext('2d'); ctx.fillStyle = 'rgba(0,0,0,0.4)'; ctx.strokeStyle = 'rgba(0,153,255,0.4)'; ctx.save(); ctx.translate(150,150); var time = new Date(); ctx.rotate( ((2*Math.PI)/6)*time.getSeconds() + ( (2*Math.PI)/6000)*time.getMilliseconds() ); ctx.translate(0,28.5); ctx.drawImage(pattern,-3.5,-3.5); ctx.restore(); } else { alert('You need Safari or Firefox 1.5+ to see this demo.'); } } </script> </head> <body onload = "animate();"> <canvas id = "mycanvas" width = "400" height = "400"></canvas> </body> </html> The above example would produce the following result − 19 Lectures 2 hours Anadi Sharma 16 Lectures 1.5 hours Anadi Sharma 18 Lectures 1.5 hours Frahaan Hussain 57 Lectures 5.5 hours DigiFisk (Programming Is Fun) 54 Lectures 6 hours DigiFisk (Programming Is Fun) 45 Lectures 5.5 hours DigiFisk (Programming Is Fun) Print Add Notes Bookmark this page
[ { "code": null, "e": 2766, "s": 2608, "text": "HTML5 canvas provides necessary methods to draw an image and erase it completely. We can take Javascript help to simulate good animation over a HTML5 canvas." }, { "code": null, "e": 2871, "s": 2766, "text": "Following are the two important Javascript methods which would be used to animate an image on a canvas −" }, { "code": null, "e": 2900, "s": 2871, "text": "setInterval(callback, time);" }, { "code": null, "e": 2982, "s": 2900, "text": "This method repeatedly executes the supplied code after a given timemilliseconds." }, { "code": null, "e": 3010, "s": 2982, "text": "setTimeout(callback, time);" }, { "code": null, "e": 3092, "s": 3010, "text": "This method executes the supplied code only once after a given time milliseconds." }, { "code": null, "e": 3168, "s": 3092, "text": "Following is a simple example which would rotate a small image repeatedly −" }, { "code": null, "e": 4593, "s": 3168, "text": "<!DOCTYPE HTML>\n\n<html>\n <head>\n \n <script type = \"text/javascript\">\n var pattern = new Image();\n \n function animate() {\n pattern.src = '/html5/images/pattern.jpg';\n setInterval(drawShape, 100);\n }\n \n function drawShape() {\n \n // get the canvas element using the DOM\n var canvas = document.getElementById('mycanvas');\n \n // Make sure we don't execute when canvas isn't supported\n if (canvas.getContext) {\n \n // use getContext to use the canvas for drawing\n var ctx = canvas.getContext('2d');\n \n ctx.fillStyle = 'rgba(0,0,0,0.4)';\n ctx.strokeStyle = 'rgba(0,153,255,0.4)';\n ctx.save();\n ctx.translate(150,150); \n \n var time = new Date(); \n ctx.rotate( ((2*Math.PI)/6)*time.getSeconds() + ( (2*Math.PI)/6000)*time.getMilliseconds() );\n ctx.translate(0,28.5);\n ctx.drawImage(pattern,-3.5,-3.5);\n ctx.restore();\n } else {\n alert('You need Safari or Firefox 1.5+ to see this demo.');\n }\n }\n </script>\n </head>\n \n <body onload = \"animate();\">\n <canvas id = \"mycanvas\" width = \"400\" height = \"400\"></canvas>\n </body>\n \n</html>" }, { "code": null, "e": 4648, "s": 4593, "text": "The above example would produce the following result −" }, { "code": null, "e": 4681, "s": 4648, "text": "\n 19 Lectures \n 2 hours \n" }, { "code": null, "e": 4695, "s": 4681, "text": " Anadi Sharma" }, { "code": null, "e": 4730, "s": 4695, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4744, "s": 4730, "text": " Anadi Sharma" }, { "code": null, "e": 4779, "s": 4744, "text": "\n 18 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4796, "s": 4779, "text": " Frahaan Hussain" }, { "code": null, "e": 4831, "s": 4796, "text": "\n 57 Lectures \n 5.5 hours \n" }, { "code": null, "e": 4862, "s": 4831, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 4895, "s": 4862, "text": "\n 54 Lectures \n 6 hours \n" }, { "code": null, "e": 4926, "s": 4895, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 4961, "s": 4926, "text": "\n 45 Lectures \n 5.5 hours \n" }, { "code": null, "e": 4992, "s": 4961, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 4999, "s": 4992, "text": " Print" }, { "code": null, "e": 5010, "s": 4999, "text": " Add Notes" } ]