title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Custom Keras Generators. A short intro to writing Keras... | by Nilesh | Towards Data Science
The idea behind using a Keras generator is to get batches of input and corresponding output on the fly during training process, e.g. reading in 100 images, getting corresponding 100 label vectors and then feeding this set to the gpu for training step. The problem I faced was memory requirement for the standard Keras generator. The in-memory generator creates copies of the original data as well as has to convert the dtype from uint8 to float64. On the other hand, the Keras generator to read from directory expects images in each class to be in an independent directory (Not possible in multi-label problems, segmentation problems etc.) So, I like to split the batch generator into 4 steps: 1. Get input : input_path -> image2. Get output : input_path -> label3. Pre-process input : image -> pre-processing step -> image4. Get generator output : ( batch_input, batch_labels ) Step 1 : Define a function to get input (can be subsetting a numpy array, pandas dataframe, reading in from disk etc.) : from skimage.io import imreaddef get_input(path): img = imread( path ) return( img ) Step 2 : Define a function to get output : import numpy as npimport pandas as pddef get_output( path, label_file = None ): img_id = path.split('/')[-1].split('.')[0] labels = label_file.loc[img_id].values return(labels) Step 3 : Define a function to preprocess input : def preprocess_input( image ): --- Rescale Image --- Rotate Image --- Resize Image --- Flip Image --- PCA etc. return( image ) Step 4 : Bring everything together to define your generator : def image_generator(files, label_file, batch_size = 64): while True: # Select files (paths/indices) for the batch batch_paths = np.random.choice(a = files, size = batch_size) batch_input = [] batch_output = [] # Read in each input, perform preprocessing and get labels for input_path in batch_paths: input = get_input(input_path ) output = get_output(input_path,label_file=label_file ) input = preprocess_input(image=input) batch_input += [ input ] batch_output += [ output ] # Return a tuple of (input, output) to feed the network batch_x = np.array( batch_input ) batch_y = np.array( batch_output ) yield( batch_x, batch_y ) And there you have it, you can add to pre-processing function as defined by your specific data-set , have the output as an image mask ( segmentation problems, localization problems etc. ). After this, using this custom generator is the same as using a predefined Keras ImageDataGenerator and simply pass the generator object to model.fit_generator().
[ { "code": null, "e": 423, "s": 171, "text": "The idea behind using a Keras generator is to get batches of input and corresponding output on the fly during training process, e.g. reading in 100 images, getting corresponding 100 label vectors and then feeding this set to the gpu for training step." }, { "code": null, "e": 811, "s": 423, "text": "The problem I faced was memory requirement for the standard Keras generator. The in-memory generator creates copies of the original data as well as has to convert the dtype from uint8 to float64. On the other hand, the Keras generator to read from directory expects images in each class to be in an independent directory (Not possible in multi-label problems, segmentation problems etc.)" }, { "code": null, "e": 865, "s": 811, "text": "So, I like to split the batch generator into 4 steps:" }, { "code": null, "e": 1074, "s": 865, "text": "1. Get input : input_path -> image2. Get output : input_path -> label3. Pre-process input : image -> pre-processing step -> image4. Get generator output : ( batch_input, batch_labels )" }, { "code": null, "e": 1195, "s": 1074, "text": "Step 1 : Define a function to get input (can be subsetting a numpy array, pandas dataframe, reading in from disk etc.) :" }, { "code": null, "e": 1294, "s": 1195, "text": "from skimage.io import imreaddef get_input(path): img = imread( path ) return( img )" }, { "code": null, "e": 1337, "s": 1294, "text": "Step 2 : Define a function to get output :" }, { "code": null, "e": 1531, "s": 1337, "text": "import numpy as npimport pandas as pddef get_output( path, label_file = None ): img_id = path.split('/')[-1].split('.')[0] labels = label_file.loc[img_id].values return(labels)" }, { "code": null, "e": 1580, "s": 1531, "text": "Step 3 : Define a function to preprocess input :" }, { "code": null, "e": 1733, "s": 1580, "text": "def preprocess_input( image ): --- Rescale Image --- Rotate Image --- Resize Image --- Flip Image --- PCA etc. return( image )" }, { "code": null, "e": 1795, "s": 1733, "text": "Step 4 : Bring everything together to define your generator :" }, { "code": null, "e": 2662, "s": 1795, "text": "def image_generator(files, label_file, batch_size = 64): while True: # Select files (paths/indices) for the batch batch_paths = np.random.choice(a = files, size = batch_size) batch_input = [] batch_output = [] # Read in each input, perform preprocessing and get labels for input_path in batch_paths: input = get_input(input_path ) output = get_output(input_path,label_file=label_file ) input = preprocess_input(image=input) batch_input += [ input ] batch_output += [ output ] # Return a tuple of (input, output) to feed the network batch_x = np.array( batch_input ) batch_y = np.array( batch_output ) yield( batch_x, batch_y )" }, { "code": null, "e": 2851, "s": 2662, "text": "And there you have it, you can add to pre-processing function as defined by your specific data-set , have the output as an image mask ( segmentation problems, localization problems etc. )." } ]
How to dynamically update a listView in Android?
This example demonstrates how do I dynamically update a ListView 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" android:layout_width="fill_parent" android:layout_height="fill_parent" android:padding="4dp" android:orientation="vertical" > <EditText android:id="@+id/editText" android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="text" android:hint="Enter an item here" /> <Button android:id="@+id/btnAdd" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Add item" android:layout_below="@id/editText" /> <ListView android:id="@+id/listView" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@id/btnAdd" /> </RelativeLayout> Step 3 βˆ’ Add the following code to src/MainActivity.java import android.os.Bundle; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import java.util.ArrayList; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { EditText editText; Button button; ListView listView; ArrayList<String> list = new ArrayList<>(); ArrayAdapter<String> adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = findViewById(R.id.btnAdd); listView = findViewById(R.id.listView); editText = findViewById(R.id.editText); adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, list); View.OnClickListener onClickListener = new View.OnClickListener() { @Override public void onClick(View v) { list.add(editText.getText().toString()); editText.setText(""); adapter.notifyDataSetChanged(); } }; button.setOnClickListener(onClickListener); listView.setAdapter(adapter); } } Step 4 βˆ’ Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample"> <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 the 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": 1139, "s": 1062, "text": "This example demonstrates how do I dynamically update a ListView in android." }, { "code": null, "e": 1268, "s": 1139, "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": 1333, "s": 1268, "text": "Step 2 βˆ’ Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2183, "s": 1333, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:layout_width=\"fill_parent\"\n android:layout_height=\"fill_parent\"\n android:padding=\"4dp\"\n android:orientation=\"vertical\" >\n <EditText\n android:id=\"@+id/editText\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:inputType=\"text\"\n android:hint=\"Enter an item here\" />\n <Button\n android:id=\"@+id/btnAdd\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Add item\"\n android:layout_below=\"@id/editText\" />\n <ListView\n android:id=\"@+id/listView\"\n android:layout_width=\"fill_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_below=\"@id/btnAdd\" />\n</RelativeLayout>" }, { "code": null, "e": 2240, "s": 2183, "text": "Step 3 βˆ’ Add the following code to src/MainActivity.java" }, { "code": null, "e": 3447, "s": 2240, "text": "import android.os.Bundle;\nimport android.view.View;\nimport android.widget.ArrayAdapter;\nimport android.widget.Button;\nimport android.widget.EditText;\nimport android.widget.ListView;\nimport java.util.ArrayList;\nimport androidx.appcompat.app.AppCompatActivity;\npublic class MainActivity extends AppCompatActivity {\n EditText editText;\n Button button;\n ListView listView;\n ArrayList<String> list = new ArrayList<>();\n ArrayAdapter<String> adapter;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n button = findViewById(R.id.btnAdd);\n listView = findViewById(R.id.listView);\n editText = findViewById(R.id.editText);\n adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, list);\n View.OnClickListener onClickListener = new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n list.add(editText.getText().toString());\n editText.setText(\"\");\n adapter.notifyDataSetChanged();\n }\n };\n button.setOnClickListener(onClickListener);\n listView.setAdapter(adapter);\n }\n}" }, { "code": null, "e": 3502, "s": 3447, "text": "Step 4 βˆ’ Add the following code to androidManifest.xml" }, { "code": null, "e": 4175, "s": 3502, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"app.com.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": 4529, "s": 4175, "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 the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen βˆ’" } ]
H2O - Installation
H2O can be configured and used with five different options as listed below βˆ’ Install in Python Install in Python Install in R Install in R Web-based Flow GUI Web-based Flow GUI Hadoop Hadoop Anaconda Cloud Anaconda Cloud In our subsequent sections, you will see the instructions for installation of H2O based on the options available. You are likely to use one of the options. To run H2O with Python, the installation requires several dependencies. So let us start installing the minimum set of dependencies to run H2O. To install a dependency, execute the following pip command βˆ’ $ pip install requests Open your console window and type the above command to install the requests package. The following screenshot shows the execution of the above command on our Mac machine βˆ’ After installing requests, you need to install three more packages as shown below βˆ’ $ pip install tabulate $ pip install "colorama >= 0.3.8" $ pip install future The most updated list of dependencies is available on H2O GitHub page. At the time of this writing, the following dependencies are listed on the page. python 2. H2O β€” Installation pip >= 9.0.1 setuptools colorama >= 0.3.7 future >= 0.15.2 After installing the above dependencies, you need to remove any existing H2O installation. To do so, run the following command βˆ’ $ pip uninstall h2o Now, let us install the latest version of H2O using the following command βˆ’ $ pip install -f http://h2o-release.s3.amazonaws.com/h2o/latest_stable_Py.html h2o After successful installation, you should see the following message display on the screen βˆ’ Installing collected packages: h2o Successfully installed h2o-3.26.0.1 To test the installation, we will run one of the sample applications provided in the H2O installation. First start the Python prompt by typing the following command βˆ’ $ Python3 Once the Python interpreter starts, type the following Python statement on the Python command prompt βˆ’ >>>import h2o The above command imports the H2O package in your program. Next, initialize the H2O system using the following command βˆ’ >>>h2o.init() Your screen would show the cluster information and should look the following at this stage βˆ’ Now, you are ready to run the sample code. Type the following command on the Python prompt and execute it. >>>h2o.demo("glm") The demo consists of a Python notebook with a series of commands. After executing each command, its output is shown immediately on the screen and you will be asked to hit the key to continue with the next step. The partial screenshot on executing the last statement in the notebook is shown here βˆ’ At this stage your Python installation is complete and you are ready for your own experimentation. Installing H2O for R development is very much similar to installing it for Python, except that you would be using R prompt for the installation. Start R console by clicking on the R application icon on your machine. The console screen would appear as shown in the following screenshot βˆ’ Your H2O installation would be done on the above R prompt. If you prefer using RStudio, type the commands in the R console subwindow. To begin with, remove older versions using the following command on the R prompt βˆ’ > if ("package:h2o" %in% search()) { detach("package:h2o", unload=TRUE) } > if ("h2o" %in% rownames(installed.packages())) { remove.packages("h2o") } Download the dependencies for H2O using the following code βˆ’ > pkgs <- c("RCurl","jsonlite") for (pkg in pkgs) { if (! (pkg %in% rownames(installed.packages()))) { install.packages(pkg) } } Install H2O by typing the following command on the R prompt βˆ’ > install.packages("h2o", type = "source", repos = (c("http://h2o-release.s3.amazonaws.com/h2o/latest_stable_R"))) The following screenshot shows the expected output βˆ’ There is another way of installing H2O in R. To install R from CRAN, use the following command on R prompt βˆ’ > install.packages("h2o") You will be asked to select the mirror βˆ’ --- Please select a CRAN mirror for use in this session --- A dialog box displaying the list of mirror sites is shown on your screen. Select the nearest location or the mirror of your choice. On the R prompt, type and run the following code βˆ’ > library(h2o) > localH2O = h2o.init() > demo(h2o.kmeans) The output generated will be as shown in the following screenshot βˆ’ Your H2O installation in R is complete now. To install GUI Flow download the installation file from the H20 site. Unzip the downloaded file in your preferred folder. Note the presence of h2o.jar file in the installation. Run this file in a command window using the following command βˆ’ $ java -jar h2o.jar After a while, the following will appear in your console window. 07-24 16:06:37.304 192.168.1.18:54321 3294 main INFO: H2O started in 7725ms 07-24 16:06:37.304 192.168.1.18:54321 3294 main INFO: 07-24 16:06:37.305 192.168.1.18:54321 3294 main INFO: Open H2O Flow in your web browser: http://192.168.1.18:54321 07-24 16:06:37.305 192.168.1.18:54321 3294 main INFO: To start the Flow, open the given URL http://localhost:54321 in your browser. The following screen will appear βˆ’ At this stage, your Flow installation is complete. Unless you are a seasoned developer, you would not think of using H2O on Big Data. It is sufficient to say here that H2O models run efficiently on huge databases of several terabytes. If your data is on your Hadoop installation or in the Cloud, follow the steps given on H2O site to install it for your respective database. Now that you have successfully installed and tested H2O on your machine, you are ready for real development. First, we will see the development from a Command prompt. In our subsequent lessons, we will learn how to do model testing in H2O Flow. Let us now consider using H2O to classify plants of the well-known iris dataset that is freely available for developing Machine Learning applications. Start the Python interpreter by typing the following command in your shell window βˆ’ $ Python3 This starts the Python interpreter. Import h2o platform using the following command βˆ’ >>> import h2o We will use Random Forest algorithm for classification. This is provided in the H2ORandomForestEstimator package. We import this package using the import statement as follows βˆ’ >>> from h2o.estimators import H2ORandomForestEstimator We initialize the H2o environment by calling its init method. >>> h2o.init() On successful initialization, you should see the following message on the console along with the cluster information. Checking whether there is an H2O instance running at http://localhost:54321 . connected. Now, we will import the iris data using the import_file method in H2O. >>> data = h2o.import_file('iris.csv') The progress will display as shown in the following screenshot βˆ’ After the file is loaded in the memory, you can verify this by displaying the first 10 rows of the loaded table. You use the head method to do so βˆ’ >>> data.head() You will see the following output in tabular format. The table also displays the column names. We will use the first four columns as the features for our ML algorithm and the last column class as the predicted output. We specify this in the call to our ML algorithm by first creating the following two variables. >>> features = ['sepal_length', 'sepal_width', 'petal_length', 'petal_width'] >>> output = 'class' Next, we split the data into training and testing by calling the split_frame method. >>> train, test = data.split_frame(ratios = [0.8]) The data is split in the 80:20 ratio. We use 80% data for training and 20% for testing. Now, we load the built-in Random Forest model into the system. >>> model = H2ORandomForestEstimator(ntrees = 50, max_depth = 20, nfolds = 10) In the above call, we set the number of trees to 50, the maximum depth for the tree to 20 and number of folds for cross validation to 10. We now need to train the model. We do so by calling the train method as follows βˆ’ >>> model.train(x = features, y = output, training_frame = train) The train method receives the features and the output that we created earlier as first two parameters. The training dataset is set to train, which is the 80% of our full dataset. During training, you will see the progress as shown here βˆ’ Now, as the model building process is over, it is time to test the model. We do this by calling the model_performance method on the trained model object. >>> performance = model.model_performance(test_data=test) In the above method call, we sent test data as our parameter. It is time now to see the output, which is the performance of our model. You do this by simply printing the performance. >>> print (performance) This will give you the following output βˆ’ The output shows the Mean Square Error (MSE), Root Mean Square Error (RMSE), LogLoss and even the Confusion Matrix. We have seen the execution from the command and also understood the purpose of each line of code. You may run the entire code in a Jupyter environment, either line by line or the whole program at a time. The complete listing is given here βˆ’ import h2o from h2o.estimators import H2ORandomForestEstimator h2o.init() data = h2o.import_file('iris.csv') features = ['sepal_length', 'sepal_width', 'petal_length', 'petal_width'] output = 'class' train, test = data.split_frame(ratios=[0.8]) model = H2ORandomForestEstimator(ntrees = 50, max_depth = 20, nfolds = 10) model.train(x = features, y = output, training_frame = train) performance = model.model_performance(test_data=test) print (performance) Run the code and observe the output. You can now appreciate how easy it is to apply and test a Random Forest algorithm on your dataset. The power of H20 goes far beyond this capability. What if you want to try another model on the same dataset to see if you can get better performance. This is explained in our subsequent section. Now, we will learn how to apply a Gradient Boosting algorithm to our earlier dataset to see how it performs. In the above full listing, you will need to make only two minor changes as highlighted in the code below βˆ’ import h2o from h2o.estimators import H2OGradientBoostingEstimator h2o.init() data = h2o.import_file('iris.csv') features = ['sepal_length', 'sepal_width', 'petal_length', 'petal_width'] output = 'class' train, test = data.split_frame(ratios = [0.8]) model = H2OGradientBoostingEstimator (ntrees = 50, max_depth = 20, nfolds = 10) model.train(x = features, y = output, training_frame = train) performance = model.model_performance(test_data = test) print (performance) Run the code and you will get the following output βˆ’ Just compare the results like MSE, RMSE, Confusion Matrix, etc. with the previous output and decide on which one to use for production deployment. As a matter of fact, you can apply several different algorithms to decide on the best one that meets your purpose. 14 Lectures 1 hours Mahesh Kumar 31 Lectures 1.5 hours Shweta 187 Lectures 17.5 hours Malhar Lathkar 55 Lectures 8 hours Arnab Chakraborty 77 Lectures 5.5 hours Ayushi Nangru 12 Lectures 1.5 hours Richa Maheshwari Print Add Notes Bookmark this page
[ { "code": null, "e": 1729, "s": 1652, "text": "H2O can be configured and used with five different options as listed below βˆ’" }, { "code": null, "e": 1747, "s": 1729, "text": "Install in Python" }, { "code": null, "e": 1765, "s": 1747, "text": "Install in Python" }, { "code": null, "e": 1778, "s": 1765, "text": "Install in R" }, { "code": null, "e": 1791, "s": 1778, "text": "Install in R" }, { "code": null, "e": 1810, "s": 1791, "text": "Web-based Flow GUI" }, { "code": null, "e": 1829, "s": 1810, "text": "Web-based Flow GUI" }, { "code": null, "e": 1836, "s": 1829, "text": "Hadoop" }, { "code": null, "e": 1843, "s": 1836, "text": "Hadoop" }, { "code": null, "e": 1858, "s": 1843, "text": "Anaconda Cloud" }, { "code": null, "e": 1873, "s": 1858, "text": "Anaconda Cloud" }, { "code": null, "e": 2029, "s": 1873, "text": "In our subsequent sections, you will see the instructions for installation of H2O based on the options available. You are likely to use one of the options." }, { "code": null, "e": 2172, "s": 2029, "text": "To run H2O with Python, the installation requires several dependencies. So let us start installing the minimum set of dependencies to run H2O." }, { "code": null, "e": 2233, "s": 2172, "text": "To install a dependency, execute the following pip command βˆ’" }, { "code": null, "e": 2257, "s": 2233, "text": "$ pip install requests\n" }, { "code": null, "e": 2429, "s": 2257, "text": "Open your console window and type the above command to install the requests package. The following screenshot shows the execution of the above command on our Mac machine βˆ’" }, { "code": null, "e": 2513, "s": 2429, "text": "After installing requests, you need to install three more packages as shown below βˆ’" }, { "code": null, "e": 2592, "s": 2513, "text": "$ pip install tabulate\n$ pip install \"colorama >= 0.3.8\"\n$ pip install future\n" }, { "code": null, "e": 2743, "s": 2592, "text": "The most updated list of dependencies is available on H2O GitHub page. At the time of this writing, the following dependencies are listed on the page." }, { "code": null, "e": 2832, "s": 2743, "text": "python 2. H2O β€” Installation\npip >= 9.0.1\nsetuptools\ncolorama >= 0.3.7\nfuture >= 0.15.2\n" }, { "code": null, "e": 2961, "s": 2832, "text": "After installing the above dependencies, you need to remove any existing H2O installation. To do so, run the following command βˆ’" }, { "code": null, "e": 2982, "s": 2961, "text": "$ pip uninstall h2o\n" }, { "code": null, "e": 3058, "s": 2982, "text": "Now, let us install the latest version of H2O using the following command βˆ’" }, { "code": null, "e": 3142, "s": 3058, "text": "$ pip install -f http://h2o-release.s3.amazonaws.com/h2o/latest_stable_Py.html h2o\n" }, { "code": null, "e": 3234, "s": 3142, "text": "After successful installation, you should see the following message display on the screen βˆ’" }, { "code": null, "e": 3306, "s": 3234, "text": "Installing collected packages: h2o\nSuccessfully installed h2o-3.26.0.1\n" }, { "code": null, "e": 3473, "s": 3306, "text": "To test the installation, we will run one of the sample applications provided in the H2O installation. First start the Python prompt by typing the following command βˆ’" }, { "code": null, "e": 3484, "s": 3473, "text": "$ Python3\n" }, { "code": null, "e": 3587, "s": 3484, "text": "Once the Python interpreter starts, type the following Python statement on the Python command prompt βˆ’" }, { "code": null, "e": 3602, "s": 3587, "text": ">>>import h2o\n" }, { "code": null, "e": 3723, "s": 3602, "text": "The above command imports the H2O package in your program. Next, initialize the H2O system using the following command βˆ’" }, { "code": null, "e": 3738, "s": 3723, "text": ">>>h2o.init()\n" }, { "code": null, "e": 3831, "s": 3738, "text": "Your screen would show the cluster information and should look the following at this stage βˆ’" }, { "code": null, "e": 3938, "s": 3831, "text": "Now, you are ready to run the sample code. Type the following command on the Python prompt and execute it." }, { "code": null, "e": 3958, "s": 3938, "text": ">>>h2o.demo(\"glm\")\n" }, { "code": null, "e": 4256, "s": 3958, "text": "The demo consists of a Python notebook with a series of commands. After executing each command, its output is shown immediately on the screen and you will be asked to hit the key to continue with the next step. The partial screenshot on executing the last statement in the notebook is shown here βˆ’" }, { "code": null, "e": 4355, "s": 4256, "text": "At this stage your Python installation is complete and you are ready for your own experimentation." }, { "code": null, "e": 4500, "s": 4355, "text": "Installing H2O for R development is very much similar to installing it for Python, except that you would be using R prompt for the installation." }, { "code": null, "e": 4642, "s": 4500, "text": "Start R console by clicking on the R application icon on your machine. The console screen would appear as shown in the following screenshot βˆ’" }, { "code": null, "e": 4776, "s": 4642, "text": "Your H2O installation would be done on the above R prompt. If you prefer using RStudio, type the commands in the R console subwindow." }, { "code": null, "e": 4859, "s": 4776, "text": "To begin with, remove older versions using the following command on the R prompt βˆ’" }, { "code": null, "e": 5010, "s": 4859, "text": "> if (\"package:h2o\" %in% search()) { detach(\"package:h2o\", unload=TRUE) }\n> if (\"h2o\" %in% rownames(installed.packages())) { remove.packages(\"h2o\") }\n" }, { "code": null, "e": 5071, "s": 5010, "text": "Download the dependencies for H2O using the following code βˆ’" }, { "code": null, "e": 5204, "s": 5071, "text": "> pkgs <- c(\"RCurl\",\"jsonlite\")\nfor (pkg in pkgs) {\n if (! (pkg %in% rownames(installed.packages()))) { install.packages(pkg) }\n}\n" }, { "code": null, "e": 5266, "s": 5204, "text": "Install H2O by typing the following command on the R prompt βˆ’" }, { "code": null, "e": 5382, "s": 5266, "text": "> install.packages(\"h2o\", type = \"source\", repos = (c(\"http://h2o-release.s3.amazonaws.com/h2o/latest_stable_R\")))\n" }, { "code": null, "e": 5435, "s": 5382, "text": "The following screenshot shows the expected output βˆ’" }, { "code": null, "e": 5480, "s": 5435, "text": "There is another way of installing H2O in R." }, { "code": null, "e": 5544, "s": 5480, "text": "To install R from CRAN, use the following command on R prompt βˆ’" }, { "code": null, "e": 5571, "s": 5544, "text": "> install.packages(\"h2o\")\n" }, { "code": null, "e": 5612, "s": 5571, "text": "You will be asked to select the mirror βˆ’" }, { "code": null, "e": 5673, "s": 5612, "text": "--- Please select a CRAN mirror for use in this session ---\n" }, { "code": null, "e": 5805, "s": 5673, "text": "A dialog box displaying the list of mirror sites is shown on your screen. Select the nearest location or the mirror of your choice." }, { "code": null, "e": 5856, "s": 5805, "text": "On the R prompt, type and run the following code βˆ’" }, { "code": null, "e": 5915, "s": 5856, "text": "> library(h2o)\n> localH2O = h2o.init()\n> demo(h2o.kmeans)\n" }, { "code": null, "e": 5983, "s": 5915, "text": "The output generated will be as shown in the following screenshot βˆ’" }, { "code": null, "e": 6027, "s": 5983, "text": "Your H2O installation in R is complete now." }, { "code": null, "e": 6268, "s": 6027, "text": "To install GUI Flow download the installation file from the H20 site. Unzip the downloaded file in your preferred folder. Note the presence of h2o.jar file in the installation. Run this file in a command window using the following command βˆ’" }, { "code": null, "e": 6289, "s": 6268, "text": "$ java -jar h2o.jar\n" }, { "code": null, "e": 6354, "s": 6289, "text": "After a while, the following will appear in your console window." }, { "code": null, "e": 6654, "s": 6354, "text": "07-24 16:06:37.304 192.168.1.18:54321 3294 main INFO: H2O started in 7725ms\n07-24 16:06:37.304 192.168.1.18:54321 3294 main INFO:\n07-24 16:06:37.305 192.168.1.18:54321 3294 main INFO: Open H2O Flow in your web browser: http://192.168.1.18:54321\n07-24 16:06:37.305 192.168.1.18:54321 3294 main INFO:\n" }, { "code": null, "e": 6767, "s": 6654, "text": "To start the Flow, open the given URL http://localhost:54321 in your browser. The following screen will appear βˆ’" }, { "code": null, "e": 6818, "s": 6767, "text": "At this stage, your Flow installation is complete." }, { "code": null, "e": 7142, "s": 6818, "text": "Unless you are a seasoned developer, you would not think of using H2O on Big Data. It is sufficient to say here that H2O models run efficiently on huge databases of several terabytes. If your data is on your Hadoop installation or in the Cloud, follow the steps given on H2O site to install it for your respective database." }, { "code": null, "e": 7387, "s": 7142, "text": "Now that you have successfully installed and tested H2O on your machine, you are ready for real development. First, we will see the development from a Command prompt. In our subsequent lessons, we will learn how to do model testing in H2O Flow." }, { "code": null, "e": 7538, "s": 7387, "text": "Let us now consider using H2O to classify plants of the well-known iris dataset that is freely available for developing Machine Learning applications." }, { "code": null, "e": 7622, "s": 7538, "text": "Start the Python interpreter by typing the following command in your shell window βˆ’" }, { "code": null, "e": 7633, "s": 7622, "text": "$ Python3\n" }, { "code": null, "e": 7719, "s": 7633, "text": "This starts the Python interpreter. Import h2o platform using the following command βˆ’" }, { "code": null, "e": 7735, "s": 7719, "text": ">>> import h2o\n" }, { "code": null, "e": 7912, "s": 7735, "text": "We will use Random Forest algorithm for classification. This is provided in the H2ORandomForestEstimator package. We import this package using the import statement as follows βˆ’" }, { "code": null, "e": 7969, "s": 7912, "text": ">>> from h2o.estimators import H2ORandomForestEstimator\n" }, { "code": null, "e": 8031, "s": 7969, "text": "We initialize the H2o environment by calling its init method." }, { "code": null, "e": 8047, "s": 8031, "text": ">>> h2o.init()\n" }, { "code": null, "e": 8165, "s": 8047, "text": "On successful initialization, you should see the following message on the console along with the cluster information." }, { "code": null, "e": 8255, "s": 8165, "text": "Checking whether there is an H2O instance running at http://localhost:54321 . connected.\n" }, { "code": null, "e": 8326, "s": 8255, "text": "Now, we will import the iris data using the import_file method in H2O." }, { "code": null, "e": 8366, "s": 8326, "text": ">>> data = h2o.import_file('iris.csv')\n" }, { "code": null, "e": 8431, "s": 8366, "text": "The progress will display as shown in the following screenshot βˆ’" }, { "code": null, "e": 8579, "s": 8431, "text": "After the file is loaded in the memory, you can verify this by displaying the first 10 rows of the loaded table. You use the head method to do so βˆ’" }, { "code": null, "e": 8596, "s": 8579, "text": ">>> data.head()\n" }, { "code": null, "e": 8649, "s": 8596, "text": "You will see the following output in tabular format." }, { "code": null, "e": 8909, "s": 8649, "text": "The table also displays the column names. We will use the first four columns as the features for our ML algorithm and the last column class as the predicted output. We specify this in the call to our ML algorithm by first creating the following two variables." }, { "code": null, "e": 9009, "s": 8909, "text": ">>> features = ['sepal_length', 'sepal_width', 'petal_length', 'petal_width']\n>>> output = 'class'\n" }, { "code": null, "e": 9094, "s": 9009, "text": "Next, we split the data into training and testing by calling the split_frame method." }, { "code": null, "e": 9146, "s": 9094, "text": ">>> train, test = data.split_frame(ratios = [0.8])\n" }, { "code": null, "e": 9234, "s": 9146, "text": "The data is split in the 80:20 ratio. We use 80% data for training and 20% for testing." }, { "code": null, "e": 9297, "s": 9234, "text": "Now, we load the built-in Random Forest model into the system." }, { "code": null, "e": 9377, "s": 9297, "text": ">>> model = H2ORandomForestEstimator(ntrees = 50, max_depth = 20, nfolds = 10)\n" }, { "code": null, "e": 9597, "s": 9377, "text": "In the above call, we set the number of trees to 50, the maximum depth for the tree to 20 and number of folds for cross validation to 10. We now need to train the model. We do so by calling the train method as follows βˆ’" }, { "code": null, "e": 9664, "s": 9597, "text": ">>> model.train(x = features, y = output, training_frame = train)\n" }, { "code": null, "e": 9902, "s": 9664, "text": "The train method receives the features and the output that we created earlier as first two parameters. The training dataset is set to train, which is the 80% of our full dataset. During training, you will see the progress as shown here βˆ’" }, { "code": null, "e": 10056, "s": 9902, "text": "Now, as the model building process is over, it is time to test the model. We do this by calling the model_performance method on the trained model object." }, { "code": null, "e": 10115, "s": 10056, "text": ">>> performance = model.model_performance(test_data=test)\n" }, { "code": null, "e": 10177, "s": 10115, "text": "In the above method call, we sent test data as our parameter." }, { "code": null, "e": 10298, "s": 10177, "text": "It is time now to see the output, which is the performance of our model. You do this by simply printing the performance." }, { "code": null, "e": 10323, "s": 10298, "text": ">>> print (performance)\n" }, { "code": null, "e": 10365, "s": 10323, "text": "This will give you the following output βˆ’" }, { "code": null, "e": 10481, "s": 10365, "text": "The output shows the Mean Square Error (MSE), Root Mean Square Error (RMSE), LogLoss and even the Confusion Matrix." }, { "code": null, "e": 10722, "s": 10481, "text": "We have seen the execution from the command and also understood the purpose of each line of code. You may run the entire code in a Jupyter environment, either line by line or the whole program at a time. The complete listing is given here βˆ’" }, { "code": null, "e": 11178, "s": 10722, "text": "import h2o\nfrom h2o.estimators import H2ORandomForestEstimator\nh2o.init()\ndata = h2o.import_file('iris.csv')\nfeatures = ['sepal_length', 'sepal_width', 'petal_length', 'petal_width']\noutput = 'class'\ntrain, test = data.split_frame(ratios=[0.8])\nmodel = H2ORandomForestEstimator(ntrees = 50, max_depth = 20, nfolds = 10)\nmodel.train(x = features, y = output, training_frame = train)\nperformance = model.model_performance(test_data=test)\nprint (performance)" }, { "code": null, "e": 11509, "s": 11178, "text": "Run the code and observe the output. You can now appreciate how easy it is to apply and test a Random Forest algorithm on your dataset. The power of H20 goes far beyond this capability. What if you want to try another model on the same dataset to see if you can get better performance. This is explained in our subsequent section." }, { "code": null, "e": 11725, "s": 11509, "text": "Now, we will learn how to apply a Gradient Boosting algorithm to our earlier dataset to see how it performs. In the above full listing, you will need to make only two minor changes as highlighted in the code below βˆ’" }, { "code": null, "e": 12196, "s": 11725, "text": "import h2o \nfrom h2o.estimators import H2OGradientBoostingEstimator\nh2o.init()\ndata = h2o.import_file('iris.csv')\nfeatures = ['sepal_length', 'sepal_width', 'petal_length', 'petal_width']\noutput = 'class'\ntrain, test = data.split_frame(ratios = [0.8]) \nmodel = H2OGradientBoostingEstimator\n(ntrees = 50, max_depth = 20, nfolds = 10)\nmodel.train(x = features, y = output, training_frame = train)\nperformance = model.model_performance(test_data = test)\nprint (performance)" }, { "code": null, "e": 12249, "s": 12196, "text": "Run the code and you will get the following output βˆ’" }, { "code": null, "e": 12511, "s": 12249, "text": "Just compare the results like MSE, RMSE, Confusion Matrix, etc. with the previous output and decide on which one to use for production deployment. As a matter of fact, you can apply several different algorithms to decide on the best one that meets your purpose." }, { "code": null, "e": 12544, "s": 12511, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 12558, "s": 12544, "text": " Mahesh Kumar" }, { "code": null, "e": 12593, "s": 12558, "text": "\n 31 Lectures \n 1.5 hours \n" }, { "code": null, "e": 12601, "s": 12593, "text": " Shweta" }, { "code": null, "e": 12638, "s": 12601, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 12654, "s": 12638, "text": " Malhar Lathkar" }, { "code": null, "e": 12687, "s": 12654, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 12706, "s": 12687, "text": " Arnab Chakraborty" }, { "code": null, "e": 12741, "s": 12706, "text": "\n 77 Lectures \n 5.5 hours \n" }, { "code": null, "e": 12756, "s": 12741, "text": " Ayushi Nangru" }, { "code": null, "e": 12791, "s": 12756, "text": "\n 12 Lectures \n 1.5 hours \n" }, { "code": null, "e": 12809, "s": 12791, "text": " Richa Maheshwari" }, { "code": null, "e": 12816, "s": 12809, "text": " Print" }, { "code": null, "e": 12827, "s": 12816, "text": " Add Notes" } ]
How to set X-axis values in Matplotlib Python?
To set X-axis values in matplotlib in Python, we can take the following steps βˆ’ Create two lists for x and y data points. Create two lists for x and y data points. Get the xticks range value. Get the xticks range value. Plot a line using plot() method with xtick range value and y data points. Plot a line using plot() method with xtick range value and y data points. Replace xticks with X-axis value using xticks() method. Replace xticks with X-axis value using xticks() method. To display the figure, use show() method. To display the figure, use show() method. from matplotlib import pyplot as plt plt.rcParams["figure.figsize"] = [7.00, 3.50] plt.rcParams["figure.autolayout"] = True x = [45, 1, 34, 78, 100] y = [8, 10, 23, 78, 2] default_x_ticks = range(len(x)) plt.plot(default_x_ticks, y) plt.xticks(default_x_ticks, x) plt.show()
[ { "code": null, "e": 1142, "s": 1062, "text": "To set X-axis values in matplotlib in Python, we can take the following steps βˆ’" }, { "code": null, "e": 1184, "s": 1142, "text": "Create two lists for x and y data points." }, { "code": null, "e": 1226, "s": 1184, "text": "Create two lists for x and y data points." }, { "code": null, "e": 1254, "s": 1226, "text": "Get the xticks range value." }, { "code": null, "e": 1282, "s": 1254, "text": "Get the xticks range value." }, { "code": null, "e": 1356, "s": 1282, "text": "Plot a line using plot() method with xtick range value and y data points." }, { "code": null, "e": 1430, "s": 1356, "text": "Plot a line using plot() method with xtick range value and y data points." }, { "code": null, "e": 1486, "s": 1430, "text": "Replace xticks with X-axis value using xticks() method." }, { "code": null, "e": 1542, "s": 1486, "text": "Replace xticks with X-axis value using xticks() method." }, { "code": null, "e": 1584, "s": 1542, "text": "To display the figure, use show() method." }, { "code": null, "e": 1626, "s": 1584, "text": "To display the figure, use show() method." }, { "code": null, "e": 1901, "s": 1626, "text": "from matplotlib import pyplot as plt\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\nx = [45, 1, 34, 78, 100]\ny = [8, 10, 23, 78, 2]\ndefault_x_ticks = range(len(x))\nplt.plot(default_x_ticks, y)\nplt.xticks(default_x_ticks, x)\nplt.show()" } ]
Controlling a DC Motor with Arduino
A DC Motor is the simplest kind of motor. It has two terminals or leads. When connected with a battery the motor will rotate, and if the connections are reversed, the motor will rotate in the opposite direction. If the voltage across the terminals is reduced, the motor speed will reduce accordingly. In this article, we will see how to interface a DC Motor with Arduino and control its speed. We won’t be looking at reversing the direction of the motor, as that will require an additional IC (an H-bridge). At the end of this article, I’ll provide links to some tutorials which explain the direction reversing of DC motors. Alright, so let’s begin with the circuit diagram. A simplified version of the circuit diagram is shown below βˆ’ As you can see, one terminal of the motor is directly connected to +5V, while the other is connected to the Collector of the PN2222 transistor. The base of this transistor is connected to pin 11 of Arduino via a resistor, while the emitter is connected to GND. We have used a transistor because the motor may demand much higher current than what a digital pin of the Arduino can handle. Using the Arduino pin to control the base of the transistor ensures that a small current from the digital pin of the Arduino can control a much larger current of the motor. Please note that you may have to power the Arduino using a wall adapter rather than the USB if your motor draws a much larger current than what a USB can provide. The transistor acts as a switch. When pin 11 goes to max voltage, the switch will be fully closed and the motor will experience maximum voltage difference across its terminals (Vcc and GND) and it will rotate at full speed. When the PWM duty cycle of pin 11 is reduced, the switch will be closed partially (i.e. open from some time and closed for the remaining time, depending on the duty cycle), creating lesser apparent voltage difference across the motor terminals, thereby reducing its speed. Higher the PWM duty cycle, higher will be the speed of the motor. There is a reverse protection diode between the two terminals of the motor, with the silver (negative) end connected to the +5V line. This diode protects the Arduino and the transistor against any negative spike voltage and corresponding current from the motor that may arise when the motor is powered off. Another variant of this circuit diagram has been taken from another TutorialsPoint tutorial and reproduced below βˆ’ The only difference is that instead of pin 11, in the above circuit, the base of the transistor is connected to PIN 9 of Arduino. Make sure that whatever pin you connect the base to, you mention properly in your code. The code is given below βˆ’ #define basePin 11 void setup() { pinMode(basePin, OUTPUT); Serial.begin(9600); } void loop() { if (Serial.available()) { int user_input_speed = Serial.parseInt(); if (user_input_speed >= 0 && user_input_speed <= 255) { analogWrite(basePin, user_input_speed); } } } As you can see, we have defined the pin connected to the base of the transistor as pin 11. In the setup, we have defined the pin as OUTPUT and initialized Serial. Within the loop, we take in an integer from the user, and if it is between 0 and 255, we set the PWM duty cycle of the base pin accordingly. Thus, the speed of the motor’s rotation will be proportional to the user input. If you are interested in changing the direction of the motor’s spinning using an H-bridge, here are tutorials for the same βˆ’ https://www.tutorialspoint.com/arduino/arduino_dc_motor.htm https://www.tutorialspoint.com/arduino/arduino_dc_motor.htm https://www.allaboutcircuits.com/projects/control-a-motor-with-an-arduino/ https://www.allaboutcircuits.com/projects/control-a-motor-with-an-arduino/ https://bc-robotics.com/tutorials/controlling-dc-motor-arduino/ https://bc-robotics.com/tutorials/controlling-dc-motor-arduino/
[ { "code": null, "e": 1363, "s": 1062, "text": "A DC Motor is the simplest kind of motor. It has two terminals or leads. When connected with a battery the motor will rotate, and if the connections are reversed, the motor will rotate in the opposite direction. If the voltage across the terminals is reduced, the motor speed will reduce accordingly." }, { "code": null, "e": 1687, "s": 1363, "text": "In this article, we will see how to interface a DC Motor with Arduino and control its speed. We won’t be looking at reversing the direction of the motor, as that will require an additional IC (an H-bridge). At the end of this article, I’ll provide links to some tutorials which explain the direction reversing of DC motors." }, { "code": null, "e": 1737, "s": 1687, "text": "Alright, so let’s begin with the circuit diagram." }, { "code": null, "e": 1798, "s": 1737, "text": "A simplified version of the circuit diagram is shown below βˆ’" }, { "code": null, "e": 2521, "s": 1798, "text": "As you can see, one terminal of the motor is directly connected to +5V, while the other is connected to the Collector of the PN2222 transistor. The base of this transistor is connected to pin 11 of Arduino via a resistor, while the emitter is connected to GND. We have used a transistor because the motor may demand much higher current than what a digital pin of the Arduino can handle. Using the Arduino pin to control the base of the transistor ensures that a small current from the digital pin of the Arduino can control a much larger current of the motor. Please note that you may have to power the Arduino using a wall adapter rather than the USB if your motor draws a much larger current than what a USB can provide." }, { "code": null, "e": 3084, "s": 2521, "text": "The transistor acts as a switch. When pin 11 goes to max voltage, the switch will be fully closed and the motor will experience maximum voltage difference across its terminals (Vcc and GND) and it will rotate at full speed. When the PWM duty cycle of pin 11 is reduced, the switch will be closed partially (i.e. open from some time and closed for the remaining time, depending on the duty cycle), creating lesser apparent voltage difference across the motor terminals, thereby reducing its speed. Higher the PWM duty cycle, higher will be the speed of the motor." }, { "code": null, "e": 3391, "s": 3084, "text": "There is a reverse protection diode between the two terminals of the motor, with the silver (negative) end connected to the +5V line. This diode protects the Arduino and the transistor against any negative spike voltage and corresponding current from the motor that may arise when the motor is powered off." }, { "code": null, "e": 3506, "s": 3391, "text": "Another variant of this circuit diagram has been taken from another TutorialsPoint tutorial and reproduced below βˆ’" }, { "code": null, "e": 3724, "s": 3506, "text": "The only difference is that instead of pin 11, in the above circuit, the base of the transistor is connected to PIN 9 of Arduino. Make sure that whatever pin you connect the base to, you mention properly in your code." }, { "code": null, "e": 3750, "s": 3724, "text": "The code is given below βˆ’" }, { "code": null, "e": 4057, "s": 3750, "text": "#define basePin 11\n\nvoid setup() {\n pinMode(basePin, OUTPUT);\n Serial.begin(9600);\n}\n\nvoid loop() {\n if (Serial.available()) {\n int user_input_speed = Serial.parseInt();\n if (user_input_speed >= 0 && user_input_speed <= 255) {\n analogWrite(basePin, user_input_speed);\n }\n }\n}" }, { "code": null, "e": 4148, "s": 4057, "text": "As you can see, we have defined the pin connected to the base of the transistor as pin 11." }, { "code": null, "e": 4220, "s": 4148, "text": "In the setup, we have defined the pin as OUTPUT and initialized Serial." }, { "code": null, "e": 4441, "s": 4220, "text": "Within the loop, we take in an integer from the user, and if it is between 0 and 255, we set the PWM duty cycle of the base pin accordingly. Thus, the speed of the motor’s rotation will be proportional to the user input." }, { "code": null, "e": 4566, "s": 4441, "text": "If you are interested in changing the direction of the motor’s spinning using an H-bridge, here are tutorials for the same βˆ’" }, { "code": null, "e": 4627, "s": 4566, "text": " https://www.tutorialspoint.com/arduino/arduino_dc_motor.htm" }, { "code": null, "e": 4688, "s": 4627, "text": " https://www.tutorialspoint.com/arduino/arduino_dc_motor.htm" }, { "code": null, "e": 4763, "s": 4688, "text": "https://www.allaboutcircuits.com/projects/control-a-motor-with-an-arduino/" }, { "code": null, "e": 4838, "s": 4763, "text": "https://www.allaboutcircuits.com/projects/control-a-motor-with-an-arduino/" }, { "code": null, "e": 4902, "s": 4838, "text": "https://bc-robotics.com/tutorials/controlling-dc-motor-arduino/" }, { "code": null, "e": 4966, "s": 4902, "text": "https://bc-robotics.com/tutorials/controlling-dc-motor-arduino/" } ]
Golang program to create an integer array that takes inputs from users.
Approach Ask the user to enter the size of array. Ask the user to enter the size of array. Make an integer array of given size. Make an integer array of given size. Ask the user to enter elements. Ask the user to enter elements. At the end, print the array. At the end, print the array. Live Demo package main import ( "fmt" ) func main(){ fmt.Printf("Enter size of your array: ") var size int fmt.Scanln(&size) var arr = make([]int, size) for i:=0; i<size; i++ { fmt.Printf("Enter %dth element: ", i) fmt.Scanf("%d", &arr[i]) } fmt.Println("Your array is: ", arr) } Enter size of your array: 6 Enter 0th element: 10 Enter 1th element: 20 Enter 2th element: 30 Enter 3th element: 40 Enter 4th element: 50 Enter 5th element: 60 Your array is: [10 20 30 40 50 60]
[ { "code": null, "e": 1071, "s": 1062, "text": "Approach" }, { "code": null, "e": 1112, "s": 1071, "text": "Ask the user to enter the size of array." }, { "code": null, "e": 1153, "s": 1112, "text": "Ask the user to enter the size of array." }, { "code": null, "e": 1190, "s": 1153, "text": "Make an integer array of given size." }, { "code": null, "e": 1227, "s": 1190, "text": "Make an integer array of given size." }, { "code": null, "e": 1259, "s": 1227, "text": "Ask the user to enter elements." }, { "code": null, "e": 1291, "s": 1259, "text": "Ask the user to enter elements." }, { "code": null, "e": 1320, "s": 1291, "text": "At the end, print the array." }, { "code": null, "e": 1349, "s": 1320, "text": "At the end, print the array." }, { "code": null, "e": 1360, "s": 1349, "text": " Live Demo" }, { "code": null, "e": 1666, "s": 1360, "text": "package main\nimport (\n \"fmt\"\n)\nfunc main(){\n fmt.Printf(\"Enter size of your array: \")\n var size int\n fmt.Scanln(&size)\n var arr = make([]int, size)\n for i:=0; i<size; i++ {\n fmt.Printf(\"Enter %dth element: \", i)\n fmt.Scanf(\"%d\", &arr[i])\n }\n fmt.Println(\"Your array is: \", arr)\n}" }, { "code": null, "e": 1861, "s": 1666, "text": "Enter size of your array: 6\nEnter 0th element: 10\nEnter 1th element: 20\nEnter 2th element: 30\nEnter 3th element: 40\nEnter 4th element: 50\nEnter 5th element: 60\nYour array is: [10 20 30 40 50 60]" } ]
Generating your own Images with NVIDIA StyleGAN2-ADA for PyTorch on the Ampere Architecture | by Jeff Heaton | Towards Data Science
StyleGAN2 ADA allows you to train a neural network to generate high-resolution images based on a training set of images. The most classic example of this is the made-up faces that StyleGAN2 is often used to generate. Until the latest release, in February 2021, you had to install an old 1.x version of TensorFlow and utilize CUDA 10. This requirement made it difficult to leverage StyleGAN2 ADA on the latest Ampere-based GPUs from NVIDIA. In this article I will show you how to use this new version of StyleGAN from Windows, no Docker or Windows Subsystem for Linux (WSL2) needed! I’ve trained GANs to produce a variety of different image types, you can see samples from some of my GANs above. I provide pretrained models to produce these images on GitHub: Minecraft GAN 70s Scifi Art GAN Fish GAN Christmas GAN You can make use of the above networks, using only Google Colab online, to generate these sorts of images for yourself. GANs are compute-intensive, there is really no way around it. The researchers at NVIDIA threw 8 V100s on a DGX system at the task of training faces. StyleGAN also scales nearly linearly across multiple GPUs, as a result, StyleGAN will take whatever hardware you are willing to throw at it on a single machine. The images that I present here were trained on a dual Quadro RTX 8000. For this article, I am assuming that we will use the latest CUDA 11, with PyTorch 1.7.1. NVIDIA recommends 12GB of RAM on the GPU; however, it is possible to work with less, if you use lower resolutions, such as 256x256. Higher-resolution GANs are generally trained at 1024x1024. A single strong GPU, such as an NVIDIA RTX A6000 also does very well. We will install StyleGAN2 outside of WSL2 or Docker. This gives the highest performance. Believe me, with GANs, you want every bit of compute that your machine can provide! First, make sure you have the latest NVIDIA driver for your graphics card: NVIDIA GPU Drivers Second, install the latest version of CUDA 11. If CUDA 12 has been released, and I have not updated this article, then proceed with caution. Check the StyleGAN2 ADA PyTorch instructions for the latest updates on versions. CUDA Toolkit Downloads It is also necessary that you install Visual C++ so that custom CUDA kernels can be compiled by StyleGAN. Visual Studio Community edition can be found at the following URL. Make sure that you install C++, which is not enabled by default in Microsoft’s installer. https://visualstudio.microsoft.com/vs/ Once Visual Studio is installed, you must add several items to the system PATH and environmental variables. You can accomplish this by running the following batch program: C:\Program Files (x86)\Microsoft Visual Studio\<VERSION>\Community\VC\Auxiliary\Build\vcvars64.bat I suggest opening a power shell window and moving into that directory and running the command β€œvcvars64.” To install PyTorch you will need Python installed on your system. I suggest either installing Miniconda or Anaconda. Miniconda is small and you will have to install needed packages. Anaconda is gigantic but contains mostly everything you will ever need. https://docs.anaconda.com/anaconda/install/ https://docs.conda.io/en/latest/miniconda.html If you are even debating which to install, or you’ve never heard of the difference between Anaconda and Miniconda, then almost certainly, Anaconda is the right answer for you. The StyleGAN team recommends PyTorch 1.7.1 for StyleGAN. Later versions may likely work, depending on the amount of β€œbreaking changes” introduced to PyTorch. The install process for PyTorch is amazing, navigate to the following URL and choose your options: https://pytorch.org/ I choose: Stable 1.7.1 Windows PIP Python CUDA 11 This resulted in the following command: pip install torch===1.7.1+cu110 torchvision===0.8.2+cu110 torchaudio===0.7.2 -f https://download.pytorch.org/whl/torch_stable.html The actual NVIDIA StyleGAN2 ADA package is distributed through GitHub at the following repository: https://github.com/NVlabs/stylegan2-ada-pytorch You can choose to download a ZIP file, which should be extracted to a directory. You can also obtain StyleGAN with the command line git command. git clone https://github.com/NVlabs/stylegan2-ada-pytorch.git At the time of this writing, there was not a requirements.txt file provided by StyleGAN to specify required packages. As you run the Python scripts, you will see errors about missing packages, just pip install them. To get you started, these are the ones I found: pip install clickpip install tqdmpip install requestspip installimageiopip installpsutilpip installscipy To train the GAN you must convert all of the images to PNG of the same size and dimension, with a very specific directory structure. This can be accomplished with the dataset_tool script provided by StyleGAN. Here I am converting all of the JPEG images that I obtained to train a GAN to generate images of fish. python dataset_tool.py --source c:\jth\fish_img --dest c:\jth\fish_train Next, you will actually train the GAN. This is done with the following command: python train.py --data c:\jth\fish_train --outdir c:\jth\results Training can take a long time, as it trains, you will see images created during training that indicate how good the images currently look. The following image shows my Minecraft GAN at 2,800 kimg, meaning it had trained on over 2,800 images (both real and augmented), at this point. As training progresses pickle snapshots will be made of your generator and discriminator to correspond with each image set checkpoint generated. For example, network-snapshot-002800.pkl generated the image checkpoint above. To generate images from this network, the following command is used. python generate.py --outdir=out --trunc=1 --seeds=85,265,297,849 \ --network=network-snapshot-002800.pkl The seeds specify the individual images to be generated, each seed is a separate image. If you would like to see each of these steps performed, I also have a YouTube video of this same material. NVIDIA StyleGAN2 ADA is a great way to generate your own images if you have the hardware for training. The new PyTorch version makes it easy to run under a Windows environment. Following the steps in this article allows you to quickly setup an environment for training your own GANs.
[ { "code": null, "e": 753, "s": 171, "text": "StyleGAN2 ADA allows you to train a neural network to generate high-resolution images based on a training set of images. The most classic example of this is the made-up faces that StyleGAN2 is often used to generate. Until the latest release, in February 2021, you had to install an old 1.x version of TensorFlow and utilize CUDA 10. This requirement made it difficult to leverage StyleGAN2 ADA on the latest Ampere-based GPUs from NVIDIA. In this article I will show you how to use this new version of StyleGAN from Windows, no Docker or Windows Subsystem for Linux (WSL2) needed!" }, { "code": null, "e": 929, "s": 753, "text": "I’ve trained GANs to produce a variety of different image types, you can see samples from some of my GANs above. I provide pretrained models to produce these images on GitHub:" }, { "code": null, "e": 943, "s": 929, "text": "Minecraft GAN" }, { "code": null, "e": 961, "s": 943, "text": "70s Scifi Art GAN" }, { "code": null, "e": 970, "s": 961, "text": "Fish GAN" }, { "code": null, "e": 984, "s": 970, "text": "Christmas GAN" }, { "code": null, "e": 1104, "s": 984, "text": "You can make use of the above networks, using only Google Colab online, to generate these sorts of images for yourself." }, { "code": null, "e": 1485, "s": 1104, "text": "GANs are compute-intensive, there is really no way around it. The researchers at NVIDIA threw 8 V100s on a DGX system at the task of training faces. StyleGAN also scales nearly linearly across multiple GPUs, as a result, StyleGAN will take whatever hardware you are willing to throw at it on a single machine. The images that I present here were trained on a dual Quadro RTX 8000." }, { "code": null, "e": 1835, "s": 1485, "text": "For this article, I am assuming that we will use the latest CUDA 11, with PyTorch 1.7.1. NVIDIA recommends 12GB of RAM on the GPU; however, it is possible to work with less, if you use lower resolutions, such as 256x256. Higher-resolution GANs are generally trained at 1024x1024. A single strong GPU, such as an NVIDIA RTX A6000 also does very well." }, { "code": null, "e": 2008, "s": 1835, "text": "We will install StyleGAN2 outside of WSL2 or Docker. This gives the highest performance. Believe me, with GANs, you want every bit of compute that your machine can provide!" }, { "code": null, "e": 2083, "s": 2008, "text": "First, make sure you have the latest NVIDIA driver for your graphics card:" }, { "code": null, "e": 2102, "s": 2083, "text": "NVIDIA GPU Drivers" }, { "code": null, "e": 2324, "s": 2102, "text": "Second, install the latest version of CUDA 11. If CUDA 12 has been released, and I have not updated this article, then proceed with caution. Check the StyleGAN2 ADA PyTorch instructions for the latest updates on versions." }, { "code": null, "e": 2347, "s": 2324, "text": "CUDA Toolkit Downloads" }, { "code": null, "e": 2610, "s": 2347, "text": "It is also necessary that you install Visual C++ so that custom CUDA kernels can be compiled by StyleGAN. Visual Studio Community edition can be found at the following URL. Make sure that you install C++, which is not enabled by default in Microsoft’s installer." }, { "code": null, "e": 2649, "s": 2610, "text": "https://visualstudio.microsoft.com/vs/" }, { "code": null, "e": 2821, "s": 2649, "text": "Once Visual Studio is installed, you must add several items to the system PATH and environmental variables. You can accomplish this by running the following batch program:" }, { "code": null, "e": 2920, "s": 2821, "text": "C:\\Program Files (x86)\\Microsoft Visual Studio\\<VERSION>\\Community\\VC\\Auxiliary\\Build\\vcvars64.bat" }, { "code": null, "e": 3026, "s": 2920, "text": "I suggest opening a power shell window and moving into that directory and running the command β€œvcvars64.”" }, { "code": null, "e": 3280, "s": 3026, "text": "To install PyTorch you will need Python installed on your system. I suggest either installing Miniconda or Anaconda. Miniconda is small and you will have to install needed packages. Anaconda is gigantic but contains mostly everything you will ever need." }, { "code": null, "e": 3324, "s": 3280, "text": "https://docs.anaconda.com/anaconda/install/" }, { "code": null, "e": 3371, "s": 3324, "text": "https://docs.conda.io/en/latest/miniconda.html" }, { "code": null, "e": 3547, "s": 3371, "text": "If you are even debating which to install, or you’ve never heard of the difference between Anaconda and Miniconda, then almost certainly, Anaconda is the right answer for you." }, { "code": null, "e": 3804, "s": 3547, "text": "The StyleGAN team recommends PyTorch 1.7.1 for StyleGAN. Later versions may likely work, depending on the amount of β€œbreaking changes” introduced to PyTorch. The install process for PyTorch is amazing, navigate to the following URL and choose your options:" }, { "code": null, "e": 3825, "s": 3804, "text": "https://pytorch.org/" }, { "code": null, "e": 3835, "s": 3825, "text": "I choose:" }, { "code": null, "e": 3848, "s": 3835, "text": "Stable 1.7.1" }, { "code": null, "e": 3856, "s": 3848, "text": "Windows" }, { "code": null, "e": 3860, "s": 3856, "text": "PIP" }, { "code": null, "e": 3867, "s": 3860, "text": "Python" }, { "code": null, "e": 3875, "s": 3867, "text": "CUDA 11" }, { "code": null, "e": 3915, "s": 3875, "text": "This resulted in the following command:" }, { "code": null, "e": 4046, "s": 3915, "text": "pip install torch===1.7.1+cu110 torchvision===0.8.2+cu110 torchaudio===0.7.2 -f https://download.pytorch.org/whl/torch_stable.html" }, { "code": null, "e": 4145, "s": 4046, "text": "The actual NVIDIA StyleGAN2 ADA package is distributed through GitHub at the following repository:" }, { "code": null, "e": 4193, "s": 4145, "text": "https://github.com/NVlabs/stylegan2-ada-pytorch" }, { "code": null, "e": 4338, "s": 4193, "text": "You can choose to download a ZIP file, which should be extracted to a directory. You can also obtain StyleGAN with the command line git command." }, { "code": null, "e": 4400, "s": 4338, "text": "git clone https://github.com/NVlabs/stylegan2-ada-pytorch.git" }, { "code": null, "e": 4664, "s": 4400, "text": "At the time of this writing, there was not a requirements.txt file provided by StyleGAN to specify required packages. As you run the Python scripts, you will see errors about missing packages, just pip install them. To get you started, these are the ones I found:" }, { "code": null, "e": 4769, "s": 4664, "text": "pip install clickpip install tqdmpip install requestspip installimageiopip installpsutilpip installscipy" }, { "code": null, "e": 5081, "s": 4769, "text": "To train the GAN you must convert all of the images to PNG of the same size and dimension, with a very specific directory structure. This can be accomplished with the dataset_tool script provided by StyleGAN. Here I am converting all of the JPEG images that I obtained to train a GAN to generate images of fish." }, { "code": null, "e": 5154, "s": 5081, "text": "python dataset_tool.py --source c:\\jth\\fish_img --dest c:\\jth\\fish_train" }, { "code": null, "e": 5234, "s": 5154, "text": "Next, you will actually train the GAN. This is done with the following command:" }, { "code": null, "e": 5299, "s": 5234, "text": "python train.py --data c:\\jth\\fish_train --outdir c:\\jth\\results" }, { "code": null, "e": 5582, "s": 5299, "text": "Training can take a long time, as it trains, you will see images created during training that indicate how good the images currently look. The following image shows my Minecraft GAN at 2,800 kimg, meaning it had trained on over 2,800 images (both real and augmented), at this point." }, { "code": null, "e": 5875, "s": 5582, "text": "As training progresses pickle snapshots will be made of your generator and discriminator to correspond with each image set checkpoint generated. For example, network-snapshot-002800.pkl generated the image checkpoint above. To generate images from this network, the following command is used." }, { "code": null, "e": 5983, "s": 5875, "text": "python generate.py --outdir=out --trunc=1 --seeds=85,265,297,849 \\ --network=network-snapshot-002800.pkl" }, { "code": null, "e": 6071, "s": 5983, "text": "The seeds specify the individual images to be generated, each seed is a separate image." }, { "code": null, "e": 6178, "s": 6071, "text": "If you would like to see each of these steps performed, I also have a YouTube video of this same material." } ]
Banker's Algorithm in Operating System - GeeksforGeeks
15 Jun, 2021 Prerequisite – Resource Allocation Graph (RAG), Banker’s Algorithm, Program for Banker’s Algorithm Banker’s Algorithm is a resource allocation and deadlock avoidance algorithm. This algorithm test for safety simulating the allocation for predetermined maximum possible amounts of all resources, then makes an β€œs-state” check to test for possible activities, before deciding whether allocation should be allowed to continue. In simple terms, it checks if allocation of any resource will lead to deadlock or not, OR is it safe to allocate a resource to a process and if not then resource is not allocated to that process. Determining a safe sequence(even if there is only 1) will assure that system will not go into deadlock. Banker’s algorithm is generally used to find if a safe sequence exist or not. But here we will determine the total number of safe sequences and print all safe sequences. The data structure used are: Available vector Max Matrix Allocation Matrix Need Matrix Example:Input: Output: Safe sequences are: P2--> P4--> P1--> P3 P2--> P4--> P3--> P1 P4--> P2--> P1--> P3 P4--> P2--> P3--> P1 There are total 4 safe-sequences Explanation: Total resources are R1 = 10, R2 = 5, R3 = 7 and allocated resources are R1 = (0+2+3+2 =) 7, R2 = (1+0+0+1 =) 2, R3 = (0+0+2+1 =) 3. Therefore, remaining resources are R1 = (10 – 7 =) 3, R2 = (5 – 2 =) 3, R3 = (7 – 3 =) 4. Remaining available = Total resources – allocated resources and Remaining need = max – allocated So, we can start from either P2 or P4. We can not satisfy remaining need from available resources of either P1 or P3 in first or second attempt step of Banker’s algorithm. There are only four possible safe sequences. These are : P2–> P4–> P1–> P3 P2–> P4–> P3–> P1 P4–> P2–> P1–> P3 P4–> P2–> P3–> P1 Implementation: . Output: Safe sequences are: P2--> P4--> P1--> P3 P2--> P4--> P3--> P1 P4--> P2--> P1--> P3 P4--> P2--> P3--> P1 There are total 4 safe-sequences princiraj1992 Rajput-Ji rutvik_56 dharanendralv23 Algorithms GATE CS Matrix Operating Systems Operating Systems Matrix Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments SDE SHEET - A Complete Guide for SDE Preparation DSA Sheet by Love Babbar Introduction to Algorithms Difference between Informed and Uninformed Search in AI Cyclomatic Complexity Layers of OSI Model ACID Properties in DBMS Types of Operating Systems TCP/IP Model Page Replacement Algorithms in Operating Systems
[ { "code": null, "e": 23745, "s": 23717, "text": "\n15 Jun, 2021" }, { "code": null, "e": 24169, "s": 23745, "text": "Prerequisite – Resource Allocation Graph (RAG), Banker’s Algorithm, Program for Banker’s Algorithm Banker’s Algorithm is a resource allocation and deadlock avoidance algorithm. This algorithm test for safety simulating the allocation for predetermined maximum possible amounts of all resources, then makes an β€œs-state” check to test for possible activities, before deciding whether allocation should be allowed to continue." }, { "code": null, "e": 24469, "s": 24169, "text": "In simple terms, it checks if allocation of any resource will lead to deadlock or not, OR is it safe to allocate a resource to a process and if not then resource is not allocated to that process. Determining a safe sequence(even if there is only 1) will assure that system will not go into deadlock." }, { "code": null, "e": 24639, "s": 24469, "text": "Banker’s algorithm is generally used to find if a safe sequence exist or not. But here we will determine the total number of safe sequences and print all safe sequences." }, { "code": null, "e": 24669, "s": 24639, "text": "The data structure used are: " }, { "code": null, "e": 24686, "s": 24669, "text": "Available vector" }, { "code": null, "e": 24697, "s": 24686, "text": "Max Matrix" }, { "code": null, "e": 24715, "s": 24697, "text": "Allocation Matrix" }, { "code": null, "e": 24727, "s": 24715, "text": "Need Matrix" }, { "code": null, "e": 24743, "s": 24727, "text": "Example:Input: " }, { "code": null, "e": 24894, "s": 24747, "text": "Output: Safe sequences are:\nP2--> P4--> P1--> P3\nP2--> P4--> P3--> P1\nP4--> P2--> P1--> P3\nP4--> P2--> P3--> P1\n\nThere are total 4 safe-sequences " }, { "code": null, "e": 25227, "s": 24894, "text": "Explanation: Total resources are R1 = 10, R2 = 5, R3 = 7 and allocated resources are R1 = (0+2+3+2 =) 7, R2 = (1+0+0+1 =) 2, R3 = (0+0+2+1 =) 3. Therefore, remaining resources are R1 = (10 – 7 =) 3, R2 = (5 – 2 =) 3, R3 = (7 – 3 =) 4. Remaining available = Total resources – allocated resources and Remaining need = max – allocated " }, { "code": null, "e": 25528, "s": 25227, "text": "So, we can start from either P2 or P4. We can not satisfy remaining need from available resources of either P1 or P3 in first or second attempt step of Banker’s algorithm. There are only four possible safe sequences. These are : P2–> P4–> P1–> P3 P2–> P4–> P3–> P1 P4–> P2–> P1–> P3 P4–> P2–> P3–> P1" }, { "code": null, "e": 25544, "s": 25528, "text": "Implementation:" }, { "code": null, "e": 25546, "s": 25544, "text": "." }, { "code": null, "e": 25555, "s": 25546, "text": "Output: " }, { "code": null, "e": 25693, "s": 25555, "text": "Safe sequences are:\nP2--> P4--> P1--> P3\nP2--> P4--> P3--> P1\nP4--> P2--> P1--> P3\nP4--> P2--> P3--> P1\n\nThere are total 4 safe-sequences" }, { "code": null, "e": 25709, "s": 25695, "text": "princiraj1992" }, { "code": null, "e": 25719, "s": 25709, "text": "Rajput-Ji" }, { "code": null, "e": 25729, "s": 25719, "text": "rutvik_56" }, { "code": null, "e": 25745, "s": 25729, "text": "dharanendralv23" }, { "code": null, "e": 25756, "s": 25745, "text": "Algorithms" }, { "code": null, "e": 25764, "s": 25756, "text": "GATE CS" }, { "code": null, "e": 25771, "s": 25764, "text": "Matrix" }, { "code": null, "e": 25789, "s": 25771, "text": "Operating Systems" }, { "code": null, "e": 25807, "s": 25789, "text": "Operating Systems" }, { "code": null, "e": 25814, "s": 25807, "text": "Matrix" }, { "code": null, "e": 25825, "s": 25814, "text": "Algorithms" }, { "code": null, "e": 25923, "s": 25825, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25932, "s": 25923, "text": "Comments" }, { "code": null, "e": 25945, "s": 25932, "text": "Old Comments" }, { "code": null, "e": 25994, "s": 25945, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 26019, "s": 25994, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 26046, "s": 26019, "text": "Introduction to Algorithms" }, { "code": null, "e": 26102, "s": 26046, "text": "Difference between Informed and Uninformed Search in AI" }, { "code": null, "e": 26124, "s": 26102, "text": "Cyclomatic Complexity" }, { "code": null, "e": 26144, "s": 26124, "text": "Layers of OSI Model" }, { "code": null, "e": 26168, "s": 26144, "text": "ACID Properties in DBMS" }, { "code": null, "e": 26195, "s": 26168, "text": "Types of Operating Systems" }, { "code": null, "e": 26208, "s": 26195, "text": "TCP/IP Model" } ]
Volume Calculation - Solved Examples
Q 1 - The diagonal of a cube is 12√6m .Find its surface area. A - 1624 m2 B - 1728 m2 C - 2564 m2 D - 1254√2m2 Answer - B Explanation Let the edge of the cube be X. √(3 )X=12√(6) β‡’ X=12√(2) Surface area = 6X2 = (6 x 12√(2) x12√(2)) m2 ≑ 1728 m2. Q 2 - The surface area of a cube is 1728 cm2. Find its volume. A - 3456√2 cm3 B - 256√2 cm3 C - 125√2 cm3 D - 144√2 cm3 Answer - A Explanation Let the edge of the cube be X. Then, 6X2 = 1728 β‡’ X2 = 288 β‡’ X = 12√2 cm. Volume = X3 = (12√2)3 cm3 = 3456√2 cm3. Q 3 - Find the number of bricks, each measuring 24 cm x 12 cm x 8 cm, required to construct a wall 24 m long, 8m high and 60 cm thick. A - 12500 B - 11500 C - 12000 D - 10000 Answer - A Explanation Volume of the wall = (1800 x 600 x 90) cm3. Volume of 1 brick = (36 x 18 x 12) cm3. Number of bricks=((1800 x 600 x 90)/( 36 x 18 x 12)=12500 Q 4 - A right triangle with sides 6 cm, 8 cm and 10 cm is rotated the side of 6 cm to form a cone. The volume of the cone so formed is: A - 96 cm3 B - 96Ο€ cm3 C - 96/Ο€ cm3 D - 96Ο€3 Answer - B Explanation We have R = 6 cm and H = 8 cm. Volume = (1/3)Ο€R2H= (1/3)Ο€x62x8=96Ο€ cm3 Q 5 - A room is 30 m long and 24 m broad. If the sum of the areas of the floor and the ceiling is equal to the sum of the areas of four walls, the volume of the hall is: A - 96 m3 B - 960 m3 C - 9600 m3 D - 96000 m3 Answer - C Explanation Let the height be H 2(30 + 24) x H = 2(30 x 24) β‡’ H=(2(30 x 24))/(2(30 + 24))=(30 x 24)/54=40/3 m β‡’ Volume = 30 x 24 x 40/3 = 9600 m3 Q 6 - A hollow steel pipe is 42 cm long and its external diameter is 16 cm. If the thickness of the pipe is 2 cm and steel density weighs 12 g/cm3, then the weight of the pipe is: A - 51.744 kg B - 45.834 kg C - 48.225 kg D - 55.565 kg Answer - A Explanation External radius = 8 cm, Internal radius = 6 cm. Volume of steel = ( Ο€ x (82-62) x42) =1176 Ο€ cm3 Weight of steel = (1176 Ο€ x 12) gm = 51744 gm = 51.744 kg. Q 7 - Find the area of right circular cone curved surface if slant height is 20 m and height is 16 m. A - 100Ο€ m2 B - 200Ο€ m2 C - 320Ο€ m2 D - 240Ο€ m2 Answer - D Explanation L = 20 m, H = 16 m. So, R = √(L2-H2) = √(202-162) = 12 m. β‡’ Curved surface area = Ο€RL = (Ο€ x 12 x 20) m2 = 240Ο€ m2. Q 8 - Find the volume & curved surface area of a cylinder with diameter of base 14 cm and height 60 cm. A - 4640cm3 & 1340 cm2 B - 9240cm3 & 1340 cm2 C - 4640cm3 & 2640 cm2 D - 9240cm3 & 2640 cm2 Answer - D Explanation Volume = Ο€R2H= Ο€ x 72 x 60 = 9240 cm3 Curved surface area = 2Ο€RH = (2 Ο€ x 7 x 60) cm2 =2640 cm2 Q 9 - If the volume of a cylindrical tank is 3696 m3 and the diameter of its base is 28 m, then find the depth of the tank. A - 5 m B - 6 m C - 8 m D - 14 m Answer - B Explanation Let the depth of the tank be H meters. Then, Volume = Ο€R2H= Ο€ x 142 x H = 3696 m3 β‡’ H=6 m Q 10 - How many steel rods, each of length 14 m and diameter 4 cm can be made out of 1.76 cm3 of steel? A - 80 B - 100 C - 110 D - 120 Answer - B Explanation Volume of 1 rod = (( 22/7) x (2/100) x (2/100) x 14 ) m3= 11/625 m3 Volume of steel = 1.76 m3 Number of rods = (1.76 x 625/11) = 100. Q 11 - Find the volume and surface area of a Box 32 m long, 28 m broad and 14 m high. A - 12544 m3 & 3472 m2 B - 12500 m3 & 3472 m2 C - 12600 m3 & 3400 m2 D - 12000 m3 & 3000 m2 Answer - A Explanation Volume = (32 x 28 x 14) m3 = 12544 m3. Surface area = [2 (32 x 28 + 28 x 14 + 32 x 14)] m2 = (2 x 1736) m2 = 3472 m2. Q 12 - Find the length of the longest pole that can be placed in a room 24 m long 16 m broad and 18 m high. A - 34 m B - 24 m C - 14 m D - 4 m Answer - A Explanation Length of the longest pole=√(242+162+182)=34 m Q 13 - A wheel makes 2000 revolutions in covering a distance of 44 km. Find the radius of the wheel. A - 12 m B - 14 m C - 13 m D - 15 m Answer - B Explanation Distance covered in one revolution = ((44 X 2000)/1000) = 88m. 2Ο€R = 88 2 x (22/7) x R = 88 β‡’ R = 88 x (7/44) = 14 m. Q 14 - A rectangular block 35 cm x 42 cm x 70 cm is cut up into an exact number of equal cubes. Find the least possible number of cubes. A - 300 B - 200 C - 100 D - 50 Answer - A Explanation Volume of the block = (35 cm x 42 cm x 70 cm) cm3 = 300x73 cm3. Side of the largest cube = H.C.F. of 35 cm , 42 cm and 70 cm = 7 cm. Volume of this cube = (7 x 7 x 7) cm3 = 73 cm3. Number of cubes = 300x73/73 = 300. Q 15 - Two cubes have their volumes in the ratio 8: 125. Find the ratio of their surface areas. A - 4:25 B - 2:25 C - 1:25 D - 3:25 Answer - A Explanation Let their edges be X and Y. Then, X3/Y3 = 8/125 (or) (X/Y)3 = (2/5)3 (or) (X/Y) = (2/5). Ratio of their surface area = 6X2/6Y2 = X2/Y2 = (X/Y)2 = 4/25, i.e. 4:25. Q 16 - Find the volume and surface area of a sphere of radius 21 cm. A - 38008 cm3 & 5444 cm2 B - 38808 cm3 & 5544 cm2 C - 38888 cm3 & 4544 cm2 D - 30008 cm3 & 5544 cm2 Answer - B Explanation Volume = (4/3)Ο€r3 =(4/3)*(22/7)*(21)*(21)*(21) cm3 = 38808 cm3. Surface area = 4Ο€r2 =(4*(22/7)*(21)*(21)) cm2 = 5544 cm2 Q 17 - The volume of a wall, 10 times as high as it is broad and 16 times as long as it is high, is 25.6 m3. Find the breadth of the wall. A - βˆ›2/5 m B - βˆ›5/2 m C - βˆ›5/3 m D - βˆ›3/2 m Answer - A Explanation Let the breadth of the wall be X meters. Then, Height = 10X meters and Length = 160X meters. X x 10X x 160X = 25.6 β‡’ X3=25.6/1600 =2/125 β‡’X = βˆ›2/5 m Q 18 - Two metallic right circular cones having their heights 4.1 cm and 4.3 cm and the radii of their bases 2.1 cm each have been melted together and recast into a sphere. Find the diameter of the sphere. A - 2 cm B - 3 cm C - 4 cm D - 5 cm Answer - A Explanation Volume of sphere = Volume of 2 cones = (1/3 Ο€ x (12) x 2.2 + 1/3 Ο€ x (1)2 x 1.8) = 4/3 Ο€ Let the radius of sphere be R 4/3 Ο€ R3 = 4/3 Ο€ or R = 1cm Hence , diameter of the sphere = 2 cm Q 19 - The diameter of garden roller is 2.8 m and it is 3 m long. The area covered by the roller in 10 revolutions is? A - 132 m2 B - 264 m m2 C - 132/5 m2 D - 264/5 m2 Answer - B Explanation Curved surface area of roller = (2 Ο€ R H) = 2 x Ο€ x 1.4 x 3=132/5. Area covered by the roller = 10 x (132/5) =264 m2 Q 20 - The curved surface area of a cylindrical pillar is 440 m2 and its volume is 1540 m3. Find the ratio of its diameter to its height. A - 7:5 B - 6:5 C - 5:7 D - 6:7 Answer - A Explanation Curved surface area = (2 Ο€ R H) = 440 β‡’ R x H=70 ... (1) Volume = β‡’ R2H=1540 β‡’ R2 x H =490 ... (2) Solving 1 & 2 we get R=7 m H= 10 m Required ratio = 2R/H =14/10 =7/5 =7:5 87 Lectures 22.5 hours Programming Line Print Add Notes Bookmark this page
[ { "code": null, "e": 3955, "s": 3892, "text": "Q 1 - The diagonal of a cube is 12√6m .Find its surface area.\t" }, { "code": null, "e": 3967, "s": 3955, "text": "A - 1624 m2" }, { "code": null, "e": 3979, "s": 3967, "text": "B - 1728 m2" }, { "code": null, "e": 3991, "s": 3979, "text": "C - 2564 m2" }, { "code": null, "e": 4004, "s": 3991, "text": "D - 1254√2m2" }, { "code": null, "e": 4015, "s": 4004, "text": "Answer - B" }, { "code": null, "e": 4027, "s": 4015, "text": "Explanation" }, { "code": null, "e": 4141, "s": 4027, "text": "Let the edge of the cube be X.\n√(3 )X=12√(6)\nβ‡’ X=12√(2)\nSurface area = 6X2 = (6 x 12√(2) x12√(2)) m2 ≑ 1728 m2. \n" }, { "code": null, "e": 4205, "s": 4141, "text": "Q 2 - The surface area of a cube is 1728 cm2. Find its volume." }, { "code": null, "e": 4220, "s": 4205, "text": "A - 3456√2 cm3" }, { "code": null, "e": 4234, "s": 4220, "text": "B - 256√2 cm3" }, { "code": null, "e": 4248, "s": 4234, "text": "C - 125√2 cm3" }, { "code": null, "e": 4262, "s": 4248, "text": "D - 144√2 cm3" }, { "code": null, "e": 4273, "s": 4262, "text": "Answer - A" }, { "code": null, "e": 4285, "s": 4273, "text": "Explanation" }, { "code": null, "e": 4403, "s": 4285, "text": "Let the edge of the cube be X. Then,\n6X2 = 1728 \nβ‡’ X2 = 288 \nβ‡’ X = 12√2 cm.\nVolume = X3 = (12√2)3 cm3\n= 3456√2 cm3. \n" }, { "code": null, "e": 4538, "s": 4403, "text": "Q 3 - Find the number of bricks, each measuring 24 cm x 12 cm x 8 cm, required to construct a wall 24 m long, 8m high and 60 cm thick." }, { "code": null, "e": 4548, "s": 4538, "text": "A - 12500" }, { "code": null, "e": 4558, "s": 4548, "text": "B - 11500" }, { "code": null, "e": 4568, "s": 4558, "text": "C - 12000" }, { "code": null, "e": 4578, "s": 4568, "text": "D - 10000" }, { "code": null, "e": 4589, "s": 4578, "text": "Answer - A" }, { "code": null, "e": 4601, "s": 4589, "text": "Explanation" }, { "code": null, "e": 4744, "s": 4601, "text": "Volume of the wall = (1800 x 600 x 90) cm3.\nVolume of 1 brick = (36 x 18 x 12) cm3.\nNumber of bricks=((1800 x 600 x 90)/( 36 x 18 x 12)=12500\n" }, { "code": null, "e": 4880, "s": 4744, "text": "Q 4 - A right triangle with sides 6 cm, 8 cm and 10 cm is rotated the side of 6 cm to form a cone. The volume of the cone so formed is:" }, { "code": null, "e": 4891, "s": 4880, "text": "A - 96 cm3" }, { "code": null, "e": 4903, "s": 4891, "text": "B - 96Ο€ cm3" }, { "code": null, "e": 4916, "s": 4903, "text": "C - 96/Ο€ cm3" }, { "code": null, "e": 4925, "s": 4916, "text": "D - 96Ο€3" }, { "code": null, "e": 4936, "s": 4925, "text": "Answer - B" }, { "code": null, "e": 4948, "s": 4936, "text": "Explanation" }, { "code": null, "e": 5020, "s": 4948, "text": "We have R = 6 cm and H = 8 cm.\nVolume = (1/3)Ο€R2H= (1/3)Ο€x62x8=96Ο€ cm3\n" }, { "code": null, "e": 5190, "s": 5020, "text": "Q 5 - A room is 30 m long and 24 m broad. If the sum of the areas of the floor and the ceiling is equal to the sum of the areas of four walls, the volume of the hall is:" }, { "code": null, "e": 5200, "s": 5190, "text": "A - 96 m3" }, { "code": null, "e": 5211, "s": 5200, "text": "B - 960 m3" }, { "code": null, "e": 5223, "s": 5211, "text": "C - 9600 m3" }, { "code": null, "e": 5236, "s": 5223, "text": "D - 96000 m3" }, { "code": null, "e": 5247, "s": 5236, "text": "Answer - C" }, { "code": null, "e": 5259, "s": 5247, "text": "Explanation" }, { "code": null, "e": 5394, "s": 5259, "text": "Let the height be H\n2(30 + 24) x H = 2(30 x 24)\nβ‡’ H=(2(30 x 24))/(2(30 + 24))=(30 x 24)/54=40/3 m\nβ‡’ Volume = 30 x 24 x 40/3 = 9600 m3\n" }, { "code": null, "e": 5574, "s": 5394, "text": "Q 6 - A hollow steel pipe is 42 cm long and its external diameter is 16 cm. If the thickness of the pipe is 2 cm and steel density weighs 12 g/cm3, then the weight of the pipe is:" }, { "code": null, "e": 5588, "s": 5574, "text": "A - 51.744 kg" }, { "code": null, "e": 5602, "s": 5588, "text": "B - 45.834 kg" }, { "code": null, "e": 5616, "s": 5602, "text": "C - 48.225 kg" }, { "code": null, "e": 5630, "s": 5616, "text": "D - 55.565 kg" }, { "code": null, "e": 5641, "s": 5630, "text": "Answer - A" }, { "code": null, "e": 5653, "s": 5641, "text": "Explanation" }, { "code": null, "e": 5810, "s": 5653, "text": "External radius = 8 cm,\nInternal radius = 6 cm.\nVolume of steel = ( Ο€ x (82-62) x42) =1176 Ο€ cm3\nWeight of steel = (1176 Ο€ x 12) gm = 51744 gm = 51.744 kg.\n" }, { "code": null, "e": 5912, "s": 5810, "text": "Q 7 - Find the area of right circular cone curved surface if slant height is 20 m and height is 16 m." }, { "code": null, "e": 5924, "s": 5912, "text": "A - 100Ο€ m2" }, { "code": null, "e": 5936, "s": 5924, "text": "B - 200Ο€ m2" }, { "code": null, "e": 5948, "s": 5936, "text": "C - 320Ο€ m2" }, { "code": null, "e": 5960, "s": 5948, "text": "D - 240Ο€ m2" }, { "code": null, "e": 5971, "s": 5960, "text": "Answer - D" }, { "code": null, "e": 5983, "s": 5971, "text": "Explanation" }, { "code": null, "e": 6100, "s": 5983, "text": "L = 20 m, H = 16 m.\nSo, R = √(L2-H2) = √(202-162) = 12 m.\nβ‡’ Curved surface area = Ο€RL = (Ο€ x 12 x 20) m2 = 240Ο€ m2.\n" }, { "code": null, "e": 6204, "s": 6100, "text": "Q 8 - Find the volume & curved surface area of a cylinder with diameter of base 14 cm and height 60 cm." }, { "code": null, "e": 6227, "s": 6204, "text": "A - 4640cm3 & 1340 cm2" }, { "code": null, "e": 6250, "s": 6227, "text": "B - 9240cm3 & 1340 cm2" }, { "code": null, "e": 6273, "s": 6250, "text": "C - 4640cm3 & 2640 cm2" }, { "code": null, "e": 6296, "s": 6273, "text": "D - 9240cm3 & 2640 cm2" }, { "code": null, "e": 6307, "s": 6296, "text": "Answer - D" }, { "code": null, "e": 6319, "s": 6307, "text": "Explanation" }, { "code": null, "e": 6417, "s": 6319, "text": "Volume = Ο€R2H= Ο€ x 72 x 60 = 9240\tcm3\nCurved surface area = 2Ο€RH = (2 Ο€ x 7 x 60) cm2 =2640 cm2\n" }, { "code": null, "e": 6541, "s": 6417, "text": "Q 9 - If the volume of a cylindrical tank is 3696 m3 and the diameter of its base is 28 m, then find the depth of the tank." }, { "code": null, "e": 6549, "s": 6541, "text": "A - 5 m" }, { "code": null, "e": 6557, "s": 6549, "text": "B - 6 m" }, { "code": null, "e": 6565, "s": 6557, "text": "C - 8 m" }, { "code": null, "e": 6574, "s": 6565, "text": "D - 14 m" }, { "code": null, "e": 6585, "s": 6574, "text": "Answer - B" }, { "code": null, "e": 6597, "s": 6585, "text": "Explanation" }, { "code": null, "e": 6689, "s": 6597, "text": "Let the depth of the tank be H meters. Then,\nVolume = Ο€R2H= Ο€ x 142 x H = 3696 m3\nβ‡’ H=6 m\n" }, { "code": null, "e": 6793, "s": 6689, "text": "Q 10 - How many steel rods, each of length 14 m and diameter 4 cm can be made out of 1.76 cm3 of steel?" }, { "code": null, "e": 6801, "s": 6793, "text": "A - 80 " }, { "code": null, "e": 6810, "s": 6801, "text": "B - 100 " }, { "code": null, "e": 6818, "s": 6810, "text": "C - 110" }, { "code": null, "e": 6826, "s": 6818, "text": "D - 120" }, { "code": null, "e": 6837, "s": 6826, "text": "Answer - B" }, { "code": null, "e": 6849, "s": 6837, "text": "Explanation" }, { "code": null, "e": 6984, "s": 6849, "text": "Volume of 1 rod = (( 22/7) x (2/100) x (2/100) x 14 ) m3= 11/625 m3\nVolume of steel = 1.76 m3\nNumber of rods = (1.76 x 625/11) = 100.\n" }, { "code": null, "e": 7070, "s": 6984, "text": "Q 11 - Find the volume and surface area of a Box 32 m long, 28 m broad and 14 m high." }, { "code": null, "e": 7093, "s": 7070, "text": "A - 12544 m3 & 3472 m2" }, { "code": null, "e": 7116, "s": 7093, "text": "B - 12500 m3 & 3472 m2" }, { "code": null, "e": 7139, "s": 7116, "text": "C - 12600 m3 & 3400 m2" }, { "code": null, "e": 7162, "s": 7139, "text": "D - 12000 m3 & 3000 m2" }, { "code": null, "e": 7173, "s": 7162, "text": "Answer - A" }, { "code": null, "e": 7185, "s": 7173, "text": "Explanation" }, { "code": null, "e": 7304, "s": 7185, "text": "Volume = (32 x 28 x 14) m3 = 12544 m3.\nSurface area = [2 (32 x 28 + 28 x 14 + 32 x 14)] m2 = (2 x 1736) m2 = 3472 m2.\n" }, { "code": null, "e": 7412, "s": 7304, "text": "Q 12 - Find the length of the longest pole that can be placed in a room 24 m long 16 m broad and 18 m high." }, { "code": null, "e": 7421, "s": 7412, "text": "A - 34 m" }, { "code": null, "e": 7430, "s": 7421, "text": "B - 24 m" }, { "code": null, "e": 7439, "s": 7430, "text": "C - 14 m" }, { "code": null, "e": 7447, "s": 7439, "text": "D - 4 m" }, { "code": null, "e": 7458, "s": 7447, "text": "Answer - A" }, { "code": null, "e": 7470, "s": 7458, "text": "Explanation" }, { "code": null, "e": 7518, "s": 7470, "text": "Length of the longest pole=√(242+162+182)=34 m\n" }, { "code": null, "e": 7619, "s": 7518, "text": "Q 13 - A wheel makes 2000 revolutions in covering a distance of 44 km. Find the radius of the wheel." }, { "code": null, "e": 7628, "s": 7619, "text": "A - 12 m" }, { "code": null, "e": 7638, "s": 7628, "text": "B - 14 m " }, { "code": null, "e": 7647, "s": 7638, "text": "C - 13 m" }, { "code": null, "e": 7657, "s": 7647, "text": "D - 15 m " }, { "code": null, "e": 7668, "s": 7657, "text": "Answer - B" }, { "code": null, "e": 7680, "s": 7668, "text": "Explanation" }, { "code": null, "e": 7799, "s": 7680, "text": "Distance covered in one revolution = ((44 X 2000)/1000) = 88m.\n2Ο€R = 88\n2 x (22/7) x R = 88\nβ‡’ R = 88 x (7/44) = 14 m.\n" }, { "code": null, "e": 7936, "s": 7799, "text": "Q 14 - A rectangular block 35 cm x 42 cm x 70 cm is cut up into an exact number of equal cubes. Find the least possible number of cubes." }, { "code": null, "e": 7944, "s": 7936, "text": "A - 300" }, { "code": null, "e": 7952, "s": 7944, "text": "B - 200" }, { "code": null, "e": 7960, "s": 7952, "text": "C - 100" }, { "code": null, "e": 7967, "s": 7960, "text": "D - 50" }, { "code": null, "e": 7978, "s": 7967, "text": "Answer - A" }, { "code": null, "e": 7990, "s": 7978, "text": "Explanation" }, { "code": null, "e": 8207, "s": 7990, "text": "Volume of the block = (35 cm x 42 cm x 70 cm) cm3 = 300x73 cm3.\nSide of the largest cube = H.C.F. of 35 cm , 42 cm and 70 cm = 7 cm.\nVolume of this cube = (7 x 7 x 7) cm3 = 73 cm3.\nNumber of cubes = 300x73/73 = 300.\n" }, { "code": null, "e": 8303, "s": 8207, "text": "Q 15 - Two cubes have their volumes in the ratio 8: 125. Find the ratio of their surface areas." }, { "code": null, "e": 8312, "s": 8303, "text": "A - 4:25" }, { "code": null, "e": 8321, "s": 8312, "text": "B - 2:25" }, { "code": null, "e": 8330, "s": 8321, "text": "C - 1:25" }, { "code": null, "e": 8339, "s": 8330, "text": "D - 3:25" }, { "code": null, "e": 8350, "s": 8339, "text": "Answer - A" }, { "code": null, "e": 8362, "s": 8350, "text": "Explanation" }, { "code": null, "e": 8526, "s": 8362, "text": "Let their edges be X and Y. Then,\nX3/Y3 = 8/125 (or) (X/Y)3 = (2/5)3 (or) (X/Y) = (2/5).\nRatio of their surface area = 6X2/6Y2 = X2/Y2 = (X/Y)2 = 4/25, i.e. 4:25.\n" }, { "code": null, "e": 8595, "s": 8526, "text": "Q 16 - Find the volume and surface area of a sphere of radius 21 cm." }, { "code": null, "e": 8620, "s": 8595, "text": "A - 38008 cm3 & 5444 cm2" }, { "code": null, "e": 8646, "s": 8620, "text": "B - 38808 cm3 & 5544 cm2 " }, { "code": null, "e": 8671, "s": 8646, "text": "C - 38888 cm3 & 4544 cm2" }, { "code": null, "e": 8696, "s": 8671, "text": "D - 30008 cm3 & 5544 cm2" }, { "code": null, "e": 8707, "s": 8696, "text": "Answer - B" }, { "code": null, "e": 8719, "s": 8707, "text": "Explanation" }, { "code": null, "e": 8841, "s": 8719, "text": "Volume = (4/3)Ο€r3 =(4/3)*(22/7)*(21)*(21)*(21) cm3 = 38808 cm3.\nSurface area = 4Ο€r2 =(4*(22/7)*(21)*(21)) cm2 = 5544 cm2\n" }, { "code": null, "e": 8980, "s": 8841, "text": "Q 17 - The volume of a wall, 10 times as high as it is broad and 16 times as long as it is high, is 25.6 m3. Find the breadth of the wall." }, { "code": null, "e": 8991, "s": 8980, "text": "A - βˆ›2/5 m" }, { "code": null, "e": 9002, "s": 8991, "text": "B - βˆ›5/2 m" }, { "code": null, "e": 9013, "s": 9002, "text": "C - βˆ›5/3 m" }, { "code": null, "e": 9024, "s": 9013, "text": "D - βˆ›3/2 m" }, { "code": null, "e": 9035, "s": 9024, "text": "Answer - A" }, { "code": null, "e": 9047, "s": 9035, "text": "Explanation" }, { "code": null, "e": 9197, "s": 9047, "text": "Let the breadth of the wall be X meters.\nThen, Height = 10X meters and Length = 160X meters.\nX x 10X x 160X = 25.6\nβ‡’ X3=25.6/1600\n=2/125\nβ‡’X = βˆ›2/5 m\n" }, { "code": null, "e": 9403, "s": 9197, "text": "Q 18 - Two metallic right circular cones having their heights 4.1 cm and 4.3 cm and the radii of their bases 2.1 cm each have been melted together and recast into a sphere. Find the diameter of the sphere." }, { "code": null, "e": 9412, "s": 9403, "text": "A - 2 cm" }, { "code": null, "e": 9421, "s": 9412, "text": "B - 3 cm" }, { "code": null, "e": 9430, "s": 9421, "text": "C - 4 cm" }, { "code": null, "e": 9439, "s": 9430, "text": "D - 5 cm" }, { "code": null, "e": 9450, "s": 9439, "text": "Answer - A" }, { "code": null, "e": 9462, "s": 9450, "text": "Explanation" }, { "code": null, "e": 9649, "s": 9462, "text": "Volume of sphere = Volume of 2 cones \n= (1/3 Ο€ x (12) x 2.2 + 1/3 Ο€ x (1)2 x 1.8) =\t4/3 Ο€\nLet the radius of sphere be R\n4/3 Ο€ R3 = 4/3 Ο€ or R = 1cm\nHence , diameter of the sphere = 2 cm\n" }, { "code": null, "e": 9768, "s": 9649, "text": "Q 19 - The diameter of garden roller is 2.8 m and it is 3 m long. The area covered by the roller in 10 revolutions is?" }, { "code": null, "e": 9780, "s": 9768, "text": "A - 132 m2 " }, { "code": null, "e": 9794, "s": 9780, "text": "B - 264 m m2 " }, { "code": null, "e": 9807, "s": 9794, "text": "C - 132/5 m2" }, { "code": null, "e": 9820, "s": 9807, "text": "D - 264/5 m2" }, { "code": null, "e": 9831, "s": 9820, "text": "Answer - B" }, { "code": null, "e": 9843, "s": 9831, "text": "Explanation" }, { "code": null, "e": 9961, "s": 9843, "text": "Curved surface area of roller = (2 Ο€ R H) = 2 x Ο€ x 1.4 x 3=132/5.\nArea covered by the roller = 10 x (132/5) =264 m2\n" }, { "code": null, "e": 10099, "s": 9961, "text": "Q 20 - The curved surface area of a cylindrical pillar is 440 m2 and its volume is 1540 m3. Find the ratio of its diameter to its height." }, { "code": null, "e": 10107, "s": 10099, "text": "A - 7:5" }, { "code": null, "e": 10115, "s": 10107, "text": "B - 6:5" }, { "code": null, "e": 10123, "s": 10115, "text": "C - 5:7" }, { "code": null, "e": 10131, "s": 10123, "text": "D - 6:7" }, { "code": null, "e": 10142, "s": 10131, "text": "Answer - A" }, { "code": null, "e": 10154, "s": 10142, "text": "Explanation" }, { "code": null, "e": 10329, "s": 10154, "text": "Curved surface area = (2 Ο€ R H) = 440\nβ‡’ R x H=70\t... (1)\nVolume = β‡’ R2H=1540 \nβ‡’ R2 x H =490 ... (2)\nSolving 1 & 2 we get R=7 m H= 10 m\nRequired ratio = 2R/H =14/10 =7/5 =7:5\n" }, { "code": null, "e": 10365, "s": 10329, "text": "\n 87 Lectures \n 22.5 hours \n" }, { "code": null, "e": 10383, "s": 10365, "text": " Programming Line" }, { "code": null, "e": 10390, "s": 10383, "text": " Print" }, { "code": null, "e": 10401, "s": 10390, "text": " Add Notes" } ]
C++ Program to Find Factorial of Large Numbers
The following is an example to find the factorial. #include <iostream> using namespace std; int fact(unsigned long long int n) { if (n == 0 || n == 1) return 1; else return n * fact(n - 1); } int main() { unsigned long long int n; cout<<"Enter number : "; cin>>n; cout<< β€œ\nThe factorial : β€œ << fact(n); return 0; } Enter number : 19 The factorial : 109641728 In the above program, we have declared a variabe with the following data type for large numbers. unsigned long long int n; The actual code is in fact() function as follows βˆ’ int fact(unsigned long long int n) { if (n == 0 || n == 1) return 1; else return n * fact(n - 1); } In the main() function, a number is entered by the user and fact() is called. The factorial of entered number is printed. cout<<"Enter number : "; cin>>n; cout<<fact(n);
[ { "code": null, "e": 1113, "s": 1062, "text": "The following is an example to find the factorial." }, { "code": null, "e": 1405, "s": 1113, "text": "#include <iostream>\nusing namespace std;\nint fact(unsigned long long int n) {\n if (n == 0 || n == 1)\n return 1;\n else\n return n * fact(n - 1);\n}\nint main() {\n unsigned long long int n;\n cout<<\"Enter number : \";\n cin>>n;\n cout<< β€œ\\nThe factorial : β€œ << fact(n);\n return 0;\n}" }, { "code": null, "e": 1449, "s": 1405, "text": "Enter number : 19\nThe factorial : 109641728" }, { "code": null, "e": 1546, "s": 1449, "text": "In the above program, we have declared a variabe with the following data type for large numbers." }, { "code": null, "e": 1572, "s": 1546, "text": "unsigned long long int n;" }, { "code": null, "e": 1623, "s": 1572, "text": "The actual code is in fact() function as follows βˆ’" }, { "code": null, "e": 1735, "s": 1623, "text": "int fact(unsigned long long int n) {\n if (n == 0 || n == 1)\n return 1;\n else\n return n * fact(n - 1);\n}" }, { "code": null, "e": 1857, "s": 1735, "text": "In the main() function, a number is entered by the user and fact() is called. The factorial of entered number is printed." }, { "code": null, "e": 1905, "s": 1857, "text": "cout<<\"Enter number : \";\ncin>>n;\ncout<<fact(n);" } ]
How to decrease the density of x-ticks in Seaborn?
To decrease the density of x-ticks in Seaborn, we can use set_visible=False for odd positions. Set the figure size and adjust the padding between and around the subplots. Set the figure size and adjust the padding between and around the subplots. Create a dataframe with X-axis and Y-axis keys. Create a dataframe with X-axis and Y-axis keys. Show the point estimates and confidence intervals with bars, using barplot() method. Show the point estimates and confidence intervals with bars, using barplot() method. Iterate bar_plot.get_xticklabels() method. If index is even, then make them visible; else, not visible. Iterate bar_plot.get_xticklabels() method. If index is even, then make them visible; else, not visible. To display the figure, use show() method. To display the figure, use show() method. import pandas import matplotlib.pylab as plt import seaborn as sns plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True df = pandas.DataFrame({"X-Axis": [i for i in range(10)], "Y-Axis": [i for i in range(10)]}) bar_plot = sns.barplot(x='X-Axis', y='Y-Axis', data=df) for index, label in enumerate(bar_plot.get_xticklabels()): if index % 2 == 0: label.set_visible(True) else: label.set_visible(False) plt.show()
[ { "code": null, "e": 1157, "s": 1062, "text": "To decrease the density of x-ticks in Seaborn, we can use set_visible=False for odd positions." }, { "code": null, "e": 1233, "s": 1157, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1309, "s": 1233, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1357, "s": 1309, "text": "Create a dataframe with X-axis and Y-axis keys." }, { "code": null, "e": 1405, "s": 1357, "text": "Create a dataframe with X-axis and Y-axis keys." }, { "code": null, "e": 1490, "s": 1405, "text": "Show the point estimates and confidence intervals with bars, using barplot() method." }, { "code": null, "e": 1575, "s": 1490, "text": "Show the point estimates and confidence intervals with bars, using barplot() method." }, { "code": null, "e": 1679, "s": 1575, "text": "Iterate bar_plot.get_xticklabels() method. If index is even, then make them visible; else, not visible." }, { "code": null, "e": 1783, "s": 1679, "text": "Iterate bar_plot.get_xticklabels() method. If index is even, then make them visible; else, not visible." }, { "code": null, "e": 1825, "s": 1783, "text": "To display the figure, use show() method." }, { "code": null, "e": 1867, "s": 1825, "text": "To display the figure, use show() method." }, { "code": null, "e": 2331, "s": 1867, "text": "import pandas\nimport matplotlib.pylab as plt\nimport seaborn as sns\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\ndf = pandas.DataFrame({\"X-Axis\": [i for i in range(10)], \"Y-Axis\": [i for i in range(10)]})\nbar_plot = sns.barplot(x='X-Axis', y='Y-Axis', data=df)\nfor index, label in enumerate(bar_plot.get_xticklabels()):\n if index % 2 == 0:\n label.set_visible(True)\n else:\n label.set_visible(False)\nplt.show()" } ]
How to test if a letter in a string is uppercase or lowercase using javascript?
To test if a letter in a string is uppercase or lowercase using javascript, you can simply convert the char to its respective case and see the result. function checkCase(ch) { if (!isNaN(ch * 1)){ return 'ch is numeric'; } else { if (ch == ch.toUpperCase()) { return 'upper case'; } if (ch == ch.toLowerCase()){ return 'lower case'; } } } console.log(checkCase('a')) console.log(checkCase('A')) console.log(checkCase('1')) This will give the output βˆ’ lower case upper case ch is numeric
[ { "code": null, "e": 1213, "s": 1062, "text": "To test if a letter in a string is uppercase or lowercase using javascript, you can simply convert the char to its respective case and see the result." }, { "code": null, "e": 1546, "s": 1213, "text": "function checkCase(ch) {\n if (!isNaN(ch * 1)){\n return 'ch is numeric';\n }\n else {\n if (ch == ch.toUpperCase()) {\n return 'upper case';\n }\n if (ch == ch.toLowerCase()){\n return 'lower case';\n }\n }\n}\nconsole.log(checkCase('a'))\nconsole.log(checkCase('A'))\nconsole.log(checkCase('1'))" }, { "code": null, "e": 1574, "s": 1546, "text": "This will give the output βˆ’" }, { "code": null, "e": 1610, "s": 1574, "text": "lower case\nupper case\nch is numeric" } ]
Fundamental Techniques of Feature Engineering for Machine Learning | by Emre Rençberoğlu | Towards Data Science
What is a feature and why we need the engineering of it? Basically, all machine learning algorithms use some input data to create outputs. This input data comprise features, which are usually in the form of structured columns. Algorithms require features with some specific characteristic to work properly. Here, the need for feature engineering arises. I think feature engineering efforts mainly have two goals: Preparing the proper input dataset, compatible with the machine learning algorithm requirements. Improving the performance of machine learning models. The features you use influence more than everything else the result. No algorithm alone, to my knowledge, can supplement the information gain given by correct feature engineering. β€” Luca Massaron According to a survey in Forbes, data scientists spend 80% of their time on data preparation: This metric is very impressive to show the importance of feature engineering in data science. Thus, I decided to write this article, which summarizes the main techniques of feature engineering with their short descriptions. I also added some basic python scripts for every technique. You need to import Pandas and Numpy library to run them. import pandas as pdimport numpy as np Some techniques above might work better with some algorithms or datasets, while some of them might be beneficial in all cases. This article does not aim to go so much deep in this aspect. Tough, it is possible to write an article for every method above, I tried to keep the explanations brief and informative. I think the best way to achieve expertise in feature engineering is practicing different techniques on various datasets and observing their effect on model performances. 1.Imputation 2.Handling Outliers 3.Binning 4.Log Transform 5.One-Hot Encoding 6.Grouping Operations 7.Feature Split 8.Scaling 9.Extracting Date Missing values are one of the most common problems you can encounter when you try to prepare your data for machine learning. The reason for the missing values might be human errors, interruptions in the data flow, privacy concerns, and so on. Whatever is the reason, missing values affect the performance of the machine learning models. Some machine learning platforms automatically drop the rows which include missing values in the model training phase and it decreases the model performance because of the reduced training size. On the other hand, most of the algorithms do not accept datasets with missing values and gives an error. The most simple solution to the missing values is to drop the rows or the entire column. There is not an optimum threshold for dropping but you can use 70% as an example value and try to drop the rows and columns which have missing values with higher than this threshold. threshold = 0.7#Dropping columns with missing value rate higher than thresholddata = data[data.columns[data.isnull().mean() < threshold]]#Dropping rows with missing value rate higher than thresholddata = data.loc[data.isnull().mean(axis=1) < threshold] Imputation is a more preferable option rather than dropping because it preserves the data size. However, there is an important selection of what you impute to the missing values. I suggest beginning with considering a possible default value of missing values in the column. For example, if you have a column that only has 1 and NA, then it is likely that the NA rows correspond to 0. For another example, if you have a column that shows the β€œcustomer visit count in last month”, the missing values might be replaced with 0 as long as you think it is a sensible solution. Another reason for the missing values is joining tables with different sizes and in this case, imputing 0 might be reasonable as well. Except for the case of having a default value for missing values, I think the best imputation way is to use the medians of the columns. As the averages of the columns are sensitive to the outlier values, while medians are more solid in this respect. #Filling all missing values with 0data = data.fillna(0)#Filling missing values with medians of the columnsdata = data.fillna(data.median()) Replacing the missing values with the maximum occurred value in a column is a good option for handling categorical columns. But if you think the values in the column are distributed uniformly and there is not a dominant value, imputing a category like β€œOther” might be more sensible, because in such a case, your imputation is likely to converge a random selection. #Max fill function for categorical columnsdata['column_name'].fillna(data['column_name'].value_counts().idxmax(), inplace=True) Before mentioning how outliers can be handled, I want to state that the best way to detect the outliers is to demonstrate the data visually. All other statistical methodologies are open to making mistakes, whereas visualizing the outliers gives a chance to take a decision with high precision. Anyway, I am planning to focus visualization deeply in another article and let’s continue with statistical methodologies. Statistical methodologies are less precise as I mentioned, but on the other hand, they have a superiority, they are fast. Here I will list two different ways of handling outliers. These will detect them using standard deviation, and percentiles. If a value has a distance to the average higher than x * standard deviation, it can be assumed as an outlier. Then what x should be? There is no trivial solution for x, but usually, a value between 2 and 4 seems practical. #Dropping the outlier rows with standard deviationfactor = 3upper_lim = data['column'].mean () + data['column'].std () * factorlower_lim = data['column'].mean () - data['column'].std () * factordata = data[(data['column'] < upper_lim) & (data['column'] > lower_lim)] In addition, z-score can be used instead of the formula above. Z-score (or standard score) standardizes the distance between a value and the mean using the standard deviation. Another mathematical method to detect outliers is to use percentiles. You can assume a certain percent of the value from the top or the bottom as an outlier. The key point is here to set the percentage value once again, and this depends on the distribution of your data as mentioned earlier. Additionally, a common mistake is using the percentiles according to the range of the data. In other words, if your data ranges from 0 to 100, your top 5% is not the values between 96 and 100. Top 5% means here the values that are out of the 95th percentile of data. #Dropping the outlier rows with Percentilesupper_lim = data['column'].quantile(.95)lower_lim = data['column'].quantile(.05)data = data[(data['column'] < upper_lim) & (data['column'] > lower_lim)] Another option for handling outliers is to cap them instead of dropping. So you can keep your data size and at the end of the day, it might be better for the final model performance. On the other hand, capping can affect the distribution of the data, thus it better not to exaggerate it. #Capping the outlier rows with Percentilesupper_lim = data['column'].quantile(.95)lower_lim = data['column'].quantile(.05)data.loc[(df[column] > upper_lim),column] = upper_limdata.loc[(df[column] < lower_lim),column] = lower_lim Binning can be applied on both categorical and numerical data: #Numerical Binning ExampleValue Bin 0-30 -> Low 31-70 -> Mid 71-100 -> High#Categorical Binning ExampleValue Bin Spain -> Europe Italy -> Europe Chile -> South AmericaBrazil -> South America The main motivation of binning is to make the model more robust and prevent overfitting, however, it has a cost to the performance. Every time you bin something, you sacrifice information and make your data more regularized. (Please see regularization in machine learning) The trade-off between performance and overfitting is the key point of the binning process. In my opinion, for numerical columns, except for some obvious overfitting cases, binning might be redundant for some kind of algorithms, due to its effect on model performance. However, for categorical columns, the labels with low frequencies probably affect the robustness of statistical models negatively. Thus, assigning a general category to these less frequent values helps to keep the robustness of the model. For example, if your data size is 100,000 rows, it might be a good option to unite the labels with a count less than 100 to a new category like β€œOther”. #Numerical Binning Exampledata['bin'] = pd.cut(data['value'], bins=[0,30,70,100], labels=["Low", "Mid", "High"]) value bin0 2 Low1 45 Mid2 7 Low3 85 High4 28 Low#Categorical Binning Example Country0 Spain1 Chile2 Australia3 Italy4 Brazilconditions = [ data['Country'].str.contains('Spain'), data['Country'].str.contains('Italy'), data['Country'].str.contains('Chile'), data['Country'].str.contains('Brazil')]choices = ['Europe', 'Europe', 'South America', 'South America']data['Continent'] = np.select(conditions, choices, default='Other') Country Continent0 Spain Europe1 Chile South America2 Australia Other3 Italy Europe4 Brazil South America Logarithm transformation (or log transform) is one of the most commonly used mathematical transformations in feature engineering. What are the benefits of log transform: It helps to handle skewed data and after transformation, the distribution becomes more approximate to normal. In most of the cases the magnitude order of the data changes within the range of the data. For instance, the difference between ages 15 and 20 is not equal to the ages 65 and 70. In terms of years, yes, they are identical, but for all other aspects, 5 years of difference in young ages mean a higher magnitude difference. This type of data comes from a multiplicative process and log transform normalizes the magnitude differences like that. It also decreases the effect of the outliers, due to the normalization of magnitude differences and the model become more robust. A critical note: The data you apply log transform must have only positive values, otherwise you receive an error. Also, you can add 1 to your data before transform it. Thus, you ensure the output of the transformation to be positive. Log(x+1) #Log Transform Exampledata = pd.DataFrame({'value':[2,45, -23, 85, 28, 2, 35, -12]})data['log+1'] = (data['value']+1).transform(np.log)#Negative Values Handling#Note that the values are differentdata['log'] = (data['value']-data['value'].min()+1) .transform(np.log) value log(x+1) log(x-min(x)+1)0 2 1.09861 3.258101 45 3.82864 4.234112 -23 nan 0.000003 85 4.45435 4.691354 28 3.36730 3.951245 2 1.09861 3.258106 35 3.58352 4.077547 -12 nan 2.48491 One-hot encoding is one of the most common encoding methods in machine learning. This method spreads the values in a column to multiple flag columns and assigns 0 or 1 to them. These binary values express the relationship between grouped and encoded column. This method changes your categorical data, which is challenging to understand for algorithms, to a numerical format and enables you to group your categorical data without losing any information. (For details please see the last part of Categorical Column Grouping) Why One-Hot?: If you have N distinct values in the column, it is enough to map them to N-1 binary columns, because the missing value can be deducted from other columns. If all the columns in our hand are equal to 0, the missing value must be equal to 1. This is the reason why it is called as one-hot encoding. However, I will give an example using the get_dummies function of Pandas. This function maps all values in a column to multiple columns. encoded_columns = pd.get_dummies(data['column'])data = data.join(encoded_columns).drop('column', axis=1) In most machine learning algorithms, every instance is represented by a row in the training dataset, where every column show a different feature of the instance. This kind of data called β€œTidy”. Tidy datasets are easy to manipulate, model and visualise, and have a specific structure: each variable is a column, each observation is a row, and each type of observational unit is a table. β€” Hadley Wickham Datasets such as transactions rarely fit the definition of tidy data above, because of the multiple rows of an instance. In such a case, we group the data by the instances and then every instance is represented by only one row. The key point of group by operations is to decide the aggregation functions of the features. For numerical features, average and sum functions are usually convenient options, whereas for categorical features it more complicated. I suggest three different ways for aggregating categorical columns: The first option is to select the label with the highest frequency. In other words, this is the max operation for categorical columns, but ordinary max functions generally do not return this value, you need to use a lambda function for this purpose. data.groupby('id').agg(lambda x: x.value_counts().index[0]) Second option is to make a pivot table. This approach resembles the encoding method in the preceding step with a difference. Instead of binary notation, it can be defined as aggregated functions for the values between grouped and encoded columns. This would be a good option if you aim to go beyond binary flag columns and merge multiple features into aggregated features, which are more informative. #Pivot table Pandas Exampledata.pivot_table(index='column_to_group', columns='column_to_encode', values='aggregation_column', aggfunc=np.sum, fill_value = 0) Last categorical grouping option is to apply a group by function after applying one-hot encoding. This method preserves all the data -in the first option you lose some-, and in addition, you transform the encoded column from categorical to numerical in the meantime. You can check the next section for the explanation of numerical column grouping. Numerical columns are grouped using sum and mean functions in most of the cases. Both can be preferable according to the meaning of the feature. For example, if you want to obtain ratio columns, you can use the average of binary columns. In the same example, sum function can be used to obtain the total count either. #sum_cols: List of columns to sum#mean_cols: List of columns to averagegrouped = data.groupby('column_to_group')sums = grouped[sum_cols].sum().add_suffix('_sum')avgs = grouped[mean_cols].mean().add_suffix('_avg')new_df = pd.concat([sums, avgs], axis=1) Splitting features is a good way to make them useful in terms of machine learning. Most of the time the dataset contains string columns that violates tidy data principles. By extracting the utilizable parts of a column into new features: We enable machine learning algorithms to comprehend them. Make possible to bin and group them. Improve model performance by uncovering potential information. Split function is a good option, however, there is no one way of splitting features. It depends on the characteristics of the column, how to split it. Let’s introduce it with two examples. First, a simple split function for an ordinary name column: data.name0 Luther N. Gonzalez1 Charles M. Young2 Terry Lawson3 Kristen White4 Thomas Logsdon#Extracting first namesdata.name.str.split(" ").map(lambda x: x[0])0 Luther1 Charles2 Terry3 Kristen4 Thomas#Extracting last namesdata.name.str.split(" ").map(lambda x: x[-1])0 Gonzalez1 Young2 Lawson3 White4 Logsdon The example above handles the names longer than two words by taking only the first and last elements and it makes the function robust for corner cases, which should be regarded when manipulating strings like that. Another case for split function is to extract a string part between two chars. The following example shows an implementation of this case by using two split functions in a row. #String extraction exampledata.title.head()0 Toy Story (1995)1 Jumanji (1995)2 Grumpier Old Men (1995)3 Waiting to Exhale (1995)4 Father of the Bride Part II (1995)data.title.str.split("(", n=1, expand=True)[1].str.split(")", n=1, expand=True)[0]0 19951 19952 19953 19954 1995 In most cases, the numerical features of the dataset do not have a certain range and they differ from each other. In real life, it is nonsense to expect age and income columns to have the same range. But from the machine learning point of view, how these two columns can be compared? Scaling solves this problem. The continuous features become identical in terms of the range, after a scaling process. This process is not mandatory for many algorithms, but it might be still nice to apply. However, the algorithms based on distance calculations such as k-NN or k-Means need to have scaled continuous features as model input. Basically, there are two common ways of scaling: Normalization (or min-max normalization) scale all values in a fixed range between 0 and 1. This transformation does not change the distribution of the feature and due to the decreased standard deviations, the effects of the outliers increases. Therefore, before normalization, it is recommended to handle the outliers. data = pd.DataFrame({'value':[2,45, -23, 85, 28, 2, 35, -12]})data['normalized'] = (data['value'] - data['value'].min()) / (data['value'].max() - data['value'].min()) value normalized0 2 0.231 45 0.632 -23 0.003 85 1.004 28 0.475 2 0.236 35 0.547 -12 0.10 Standardization (or z-score normalization) scales the values while taking into account standard deviation. If the standard deviation of features is different, their range also would differ from each other. This reduces the effect of the outliers in the features. In the following formula of standardization, the mean is shown as ΞΌ and the standard deviation is shown as Οƒ. data = pd.DataFrame({'value':[2,45, -23, 85, 28, 2, 35, -12]})data['standardized'] = (data['value'] - data['value'].mean()) / data['value'].std() value standardized0 2 -0.521 45 0.702 -23 -1.233 85 1.844 28 0.225 2 -0.526 35 0.427 -12 -0.92 Though date columns usually provide valuable information about the model target, they are neglected as an input or used nonsensically for the machine learning algorithms. It might be the reason for this, that dates can be present in numerous formats, which make it hard to understand by algorithms, even they are simplified to a format like "01–01–2017". Building an ordinal relationship between the values is very challenging for a machine learning algorithm if you leave the date columns without manipulation. Here, I suggest three types of preprocessing for dates: Extracting the parts of the date into different columns: Year, month, day, etc. Extracting the time period between the current date and columns in terms of years, months, days, etc. Extracting some specific features from the date: Name of the weekday, Weekend or not, holiday or not, etc. If you transform the date column into the extracted columns like above, the information of them become disclosed and machine learning algorithms can easily understand them. from datetime import datedata = pd.DataFrame({'date':['01-01-2017','04-12-2008','23-06-1988','25-08-1999','20-02-1993',]})#Transform string to datedata['date'] = pd.to_datetime(data.date, format="%d-%m-%Y")#Extracting Yeardata['year'] = data['date'].dt.year#Extracting Monthdata['month'] = data['date'].dt.month#Extracting passed years since the datedata['passed_years'] = date.today().year - data['date'].dt.year#Extracting passed months since the datedata['passed_months'] = (date.today().year - data['date'].dt.year) * 12 + date.today().month - data['date'].dt.month#Extracting the weekday name of the datedata['day_name'] = data['date'].dt.day_name() date year month passed_years passed_months day_name0 2017-01-01 2017 1 2 26 Sunday1 2008-12-04 2008 12 11 123 Thursday2 1988-06-23 1988 6 31 369 Thursday3 1999-08-25 1999 8 20 235 Wednesday4 1993-02-20 1993 2 26 313 Saturday I tried to explain fundamental methods that can be beneficial in the feature engineering process. After this article, proceeding with other topics of data preparation such as feature selection, train/test splitting, and sampling might be a good option. You can check my other article about Oversampling. Lastly, I want to conclude the article with a reminder. These techniques are not magical tools. If your data tiny, dirty and useless, feature engineering may remain incapable. Do not forget β€œgarbage in, garbage out!” Stack Overflow questions are very beneficial for every kind of feature engineering script. I highly recommend Kaggle competitions and their discussion boards. Ways to Detect and Remove the Outliers Understanding Feature Engineering (Part 1) β€” Continuous Numeric Data Understanding Feature Engineering (Part 2) β€” Categorical Data Log Transformations for Skewed and Wide Distributions Tidy data About Feature Scaling and Normalization
[ { "code": null, "e": 584, "s": 171, "text": "What is a feature and why we need the engineering of it? Basically, all machine learning algorithms use some input data to create outputs. This input data comprise features, which are usually in the form of structured columns. Algorithms require features with some specific characteristic to work properly. Here, the need for feature engineering arises. I think feature engineering efforts mainly have two goals:" }, { "code": null, "e": 681, "s": 584, "text": "Preparing the proper input dataset, compatible with the machine learning algorithm requirements." }, { "code": null, "e": 735, "s": 681, "text": "Improving the performance of machine learning models." }, { "code": null, "e": 915, "s": 735, "text": "The features you use influence more than everything else the result. No algorithm alone, to my knowledge, can supplement the information gain given by correct feature engineering." }, { "code": null, "e": 931, "s": 915, "text": "β€” Luca Massaron" }, { "code": null, "e": 1025, "s": 931, "text": "According to a survey in Forbes, data scientists spend 80% of their time on data preparation:" }, { "code": null, "e": 1366, "s": 1025, "text": "This metric is very impressive to show the importance of feature engineering in data science. Thus, I decided to write this article, which summarizes the main techniques of feature engineering with their short descriptions. I also added some basic python scripts for every technique. You need to import Pandas and Numpy library to run them." }, { "code": null, "e": 1404, "s": 1366, "text": "import pandas as pdimport numpy as np" }, { "code": null, "e": 1884, "s": 1404, "text": "Some techniques above might work better with some algorithms or datasets, while some of them might be beneficial in all cases. This article does not aim to go so much deep in this aspect. Tough, it is possible to write an article for every method above, I tried to keep the explanations brief and informative. I think the best way to achieve expertise in feature engineering is practicing different techniques on various datasets and observing their effect on model performances." }, { "code": null, "e": 1897, "s": 1884, "text": "1.Imputation" }, { "code": null, "e": 1917, "s": 1897, "text": "2.Handling Outliers" }, { "code": null, "e": 1927, "s": 1917, "text": "3.Binning" }, { "code": null, "e": 1943, "s": 1927, "text": "4.Log Transform" }, { "code": null, "e": 1962, "s": 1943, "text": "5.One-Hot Encoding" }, { "code": null, "e": 1984, "s": 1962, "text": "6.Grouping Operations" }, { "code": null, "e": 2000, "s": 1984, "text": "7.Feature Split" }, { "code": null, "e": 2010, "s": 2000, "text": "8.Scaling" }, { "code": null, "e": 2028, "s": 2010, "text": "9.Extracting Date" }, { "code": null, "e": 2365, "s": 2028, "text": "Missing values are one of the most common problems you can encounter when you try to prepare your data for machine learning. The reason for the missing values might be human errors, interruptions in the data flow, privacy concerns, and so on. Whatever is the reason, missing values affect the performance of the machine learning models." }, { "code": null, "e": 2664, "s": 2365, "text": "Some machine learning platforms automatically drop the rows which include missing values in the model training phase and it decreases the model performance because of the reduced training size. On the other hand, most of the algorithms do not accept datasets with missing values and gives an error." }, { "code": null, "e": 2936, "s": 2664, "text": "The most simple solution to the missing values is to drop the rows or the entire column. There is not an optimum threshold for dropping but you can use 70% as an example value and try to drop the rows and columns which have missing values with higher than this threshold." }, { "code": null, "e": 3189, "s": 2936, "text": "threshold = 0.7#Dropping columns with missing value rate higher than thresholddata = data[data.columns[data.isnull().mean() < threshold]]#Dropping rows with missing value rate higher than thresholddata = data.loc[data.isnull().mean(axis=1) < threshold]" }, { "code": null, "e": 3760, "s": 3189, "text": "Imputation is a more preferable option rather than dropping because it preserves the data size. However, there is an important selection of what you impute to the missing values. I suggest beginning with considering a possible default value of missing values in the column. For example, if you have a column that only has 1 and NA, then it is likely that the NA rows correspond to 0. For another example, if you have a column that shows the β€œcustomer visit count in last month”, the missing values might be replaced with 0 as long as you think it is a sensible solution." }, { "code": null, "e": 3895, "s": 3760, "text": "Another reason for the missing values is joining tables with different sizes and in this case, imputing 0 might be reasonable as well." }, { "code": null, "e": 4145, "s": 3895, "text": "Except for the case of having a default value for missing values, I think the best imputation way is to use the medians of the columns. As the averages of the columns are sensitive to the outlier values, while medians are more solid in this respect." }, { "code": null, "e": 4285, "s": 4145, "text": "#Filling all missing values with 0data = data.fillna(0)#Filling missing values with medians of the columnsdata = data.fillna(data.median())" }, { "code": null, "e": 4651, "s": 4285, "text": "Replacing the missing values with the maximum occurred value in a column is a good option for handling categorical columns. But if you think the values in the column are distributed uniformly and there is not a dominant value, imputing a category like β€œOther” might be more sensible, because in such a case, your imputation is likely to converge a random selection." }, { "code": null, "e": 4779, "s": 4651, "text": "#Max fill function for categorical columnsdata['column_name'].fillna(data['column_name'].value_counts().idxmax(), inplace=True)" }, { "code": null, "e": 5195, "s": 4779, "text": "Before mentioning how outliers can be handled, I want to state that the best way to detect the outliers is to demonstrate the data visually. All other statistical methodologies are open to making mistakes, whereas visualizing the outliers gives a chance to take a decision with high precision. Anyway, I am planning to focus visualization deeply in another article and let’s continue with statistical methodologies." }, { "code": null, "e": 5441, "s": 5195, "text": "Statistical methodologies are less precise as I mentioned, but on the other hand, they have a superiority, they are fast. Here I will list two different ways of handling outliers. These will detect them using standard deviation, and percentiles." }, { "code": null, "e": 5574, "s": 5441, "text": "If a value has a distance to the average higher than x * standard deviation, it can be assumed as an outlier. Then what x should be?" }, { "code": null, "e": 5664, "s": 5574, "text": "There is no trivial solution for x, but usually, a value between 2 and 4 seems practical." }, { "code": null, "e": 5931, "s": 5664, "text": "#Dropping the outlier rows with standard deviationfactor = 3upper_lim = data['column'].mean () + data['column'].std () * factorlower_lim = data['column'].mean () - data['column'].std () * factordata = data[(data['column'] < upper_lim) & (data['column'] > lower_lim)]" }, { "code": null, "e": 6107, "s": 5931, "text": "In addition, z-score can be used instead of the formula above. Z-score (or standard score) standardizes the distance between a value and the mean using the standard deviation." }, { "code": null, "e": 6399, "s": 6107, "text": "Another mathematical method to detect outliers is to use percentiles. You can assume a certain percent of the value from the top or the bottom as an outlier. The key point is here to set the percentage value once again, and this depends on the distribution of your data as mentioned earlier." }, { "code": null, "e": 6666, "s": 6399, "text": "Additionally, a common mistake is using the percentiles according to the range of the data. In other words, if your data ranges from 0 to 100, your top 5% is not the values between 96 and 100. Top 5% means here the values that are out of the 95th percentile of data." }, { "code": null, "e": 6862, "s": 6666, "text": "#Dropping the outlier rows with Percentilesupper_lim = data['column'].quantile(.95)lower_lim = data['column'].quantile(.05)data = data[(data['column'] < upper_lim) & (data['column'] > lower_lim)]" }, { "code": null, "e": 7045, "s": 6862, "text": "Another option for handling outliers is to cap them instead of dropping. So you can keep your data size and at the end of the day, it might be better for the final model performance." }, { "code": null, "e": 7150, "s": 7045, "text": "On the other hand, capping can affect the distribution of the data, thus it better not to exaggerate it." }, { "code": null, "e": 7379, "s": 7150, "text": "#Capping the outlier rows with Percentilesupper_lim = data['column'].quantile(.95)lower_lim = data['column'].quantile(.05)data.loc[(df[column] > upper_lim),column] = upper_limdata.loc[(df[column] < lower_lim),column] = lower_lim" }, { "code": null, "e": 7442, "s": 7379, "text": "Binning can be applied on both categorical and numerical data:" }, { "code": null, "e": 7691, "s": 7442, "text": "#Numerical Binning ExampleValue Bin 0-30 -> Low 31-70 -> Mid 71-100 -> High#Categorical Binning ExampleValue Bin Spain -> Europe Italy -> Europe Chile -> South AmericaBrazil -> South America" }, { "code": null, "e": 7964, "s": 7691, "text": "The main motivation of binning is to make the model more robust and prevent overfitting, however, it has a cost to the performance. Every time you bin something, you sacrifice information and make your data more regularized. (Please see regularization in machine learning)" }, { "code": null, "e": 8232, "s": 7964, "text": "The trade-off between performance and overfitting is the key point of the binning process. In my opinion, for numerical columns, except for some obvious overfitting cases, binning might be redundant for some kind of algorithms, due to its effect on model performance." }, { "code": null, "e": 8624, "s": 8232, "text": "However, for categorical columns, the labels with low frequencies probably affect the robustness of statistical models negatively. Thus, assigning a general category to these less frequent values helps to keep the robustness of the model. For example, if your data size is 100,000 rows, it might be a good option to unite the labels with a count less than 100 to a new category like β€œOther”." }, { "code": null, "e": 9397, "s": 8624, "text": "#Numerical Binning Exampledata['bin'] = pd.cut(data['value'], bins=[0,30,70,100], labels=[\"Low\", \"Mid\", \"High\"]) value bin0 2 Low1 45 Mid2 7 Low3 85 High4 28 Low#Categorical Binning Example Country0 Spain1 Chile2 Australia3 Italy4 Brazilconditions = [ data['Country'].str.contains('Spain'), data['Country'].str.contains('Italy'), data['Country'].str.contains('Chile'), data['Country'].str.contains('Brazil')]choices = ['Europe', 'Europe', 'South America', 'South America']data['Continent'] = np.select(conditions, choices, default='Other') Country Continent0 Spain Europe1 Chile South America2 Australia Other3 Italy Europe4 Brazil South America" }, { "code": null, "e": 9567, "s": 9397, "text": "Logarithm transformation (or log transform) is one of the most commonly used mathematical transformations in feature engineering. What are the benefits of log transform:" }, { "code": null, "e": 9677, "s": 9567, "text": "It helps to handle skewed data and after transformation, the distribution becomes more approximate to normal." }, { "code": null, "e": 10119, "s": 9677, "text": "In most of the cases the magnitude order of the data changes within the range of the data. For instance, the difference between ages 15 and 20 is not equal to the ages 65 and 70. In terms of years, yes, they are identical, but for all other aspects, 5 years of difference in young ages mean a higher magnitude difference. This type of data comes from a multiplicative process and log transform normalizes the magnitude differences like that." }, { "code": null, "e": 10249, "s": 10119, "text": "It also decreases the effect of the outliers, due to the normalization of magnitude differences and the model become more robust." }, { "code": null, "e": 10483, "s": 10249, "text": "A critical note: The data you apply log transform must have only positive values, otherwise you receive an error. Also, you can add 1 to your data before transform it. Thus, you ensure the output of the transformation to be positive." }, { "code": null, "e": 10492, "s": 10483, "text": "Log(x+1)" }, { "code": null, "e": 11073, "s": 10492, "text": "#Log Transform Exampledata = pd.DataFrame({'value':[2,45, -23, 85, 28, 2, 35, -12]})data['log+1'] = (data['value']+1).transform(np.log)#Negative Values Handling#Note that the values are differentdata['log'] = (data['value']-data['value'].min()+1) .transform(np.log) value log(x+1) log(x-min(x)+1)0 2 1.09861 3.258101 45 3.82864 4.234112 -23 nan 0.000003 85 4.45435 4.691354 28 3.36730 3.951245 2 1.09861 3.258106 35 3.58352 4.077547 -12 nan 2.48491" }, { "code": null, "e": 11331, "s": 11073, "text": "One-hot encoding is one of the most common encoding methods in machine learning. This method spreads the values in a column to multiple flag columns and assigns 0 or 1 to them. These binary values express the relationship between grouped and encoded column." }, { "code": null, "e": 11596, "s": 11331, "text": "This method changes your categorical data, which is challenging to understand for algorithms, to a numerical format and enables you to group your categorical data without losing any information. (For details please see the last part of Categorical Column Grouping)" }, { "code": null, "e": 12044, "s": 11596, "text": "Why One-Hot?: If you have N distinct values in the column, it is enough to map them to N-1 binary columns, because the missing value can be deducted from other columns. If all the columns in our hand are equal to 0, the missing value must be equal to 1. This is the reason why it is called as one-hot encoding. However, I will give an example using the get_dummies function of Pandas. This function maps all values in a column to multiple columns." }, { "code": null, "e": 12149, "s": 12044, "text": "encoded_columns = pd.get_dummies(data['column'])data = data.join(encoded_columns).drop('column', axis=1)" }, { "code": null, "e": 12344, "s": 12149, "text": "In most machine learning algorithms, every instance is represented by a row in the training dataset, where every column show a different feature of the instance. This kind of data called β€œTidy”." }, { "code": null, "e": 12536, "s": 12344, "text": "Tidy datasets are easy to manipulate, model and visualise, and have a specific structure: each variable is a column, each observation is a row, and each type of observational unit is a table." }, { "code": null, "e": 12553, "s": 12536, "text": "β€” Hadley Wickham" }, { "code": null, "e": 12781, "s": 12553, "text": "Datasets such as transactions rarely fit the definition of tidy data above, because of the multiple rows of an instance. In such a case, we group the data by the instances and then every instance is represented by only one row." }, { "code": null, "e": 13010, "s": 12781, "text": "The key point of group by operations is to decide the aggregation functions of the features. For numerical features, average and sum functions are usually convenient options, whereas for categorical features it more complicated." }, { "code": null, "e": 13078, "s": 13010, "text": "I suggest three different ways for aggregating categorical columns:" }, { "code": null, "e": 13328, "s": 13078, "text": "The first option is to select the label with the highest frequency. In other words, this is the max operation for categorical columns, but ordinary max functions generally do not return this value, you need to use a lambda function for this purpose." }, { "code": null, "e": 13388, "s": 13328, "text": "data.groupby('id').agg(lambda x: x.value_counts().index[0])" }, { "code": null, "e": 13789, "s": 13388, "text": "Second option is to make a pivot table. This approach resembles the encoding method in the preceding step with a difference. Instead of binary notation, it can be defined as aggregated functions for the values between grouped and encoded columns. This would be a good option if you aim to go beyond binary flag columns and merge multiple features into aggregated features, which are more informative." }, { "code": null, "e": 13947, "s": 13789, "text": "#Pivot table Pandas Exampledata.pivot_table(index='column_to_group', columns='column_to_encode', values='aggregation_column', aggfunc=np.sum, fill_value = 0)" }, { "code": null, "e": 14295, "s": 13947, "text": "Last categorical grouping option is to apply a group by function after applying one-hot encoding. This method preserves all the data -in the first option you lose some-, and in addition, you transform the encoded column from categorical to numerical in the meantime. You can check the next section for the explanation of numerical column grouping." }, { "code": null, "e": 14613, "s": 14295, "text": "Numerical columns are grouped using sum and mean functions in most of the cases. Both can be preferable according to the meaning of the feature. For example, if you want to obtain ratio columns, you can use the average of binary columns. In the same example, sum function can be used to obtain the total count either." }, { "code": null, "e": 14866, "s": 14613, "text": "#sum_cols: List of columns to sum#mean_cols: List of columns to averagegrouped = data.groupby('column_to_group')sums = grouped[sum_cols].sum().add_suffix('_sum')avgs = grouped[mean_cols].mean().add_suffix('_avg')new_df = pd.concat([sums, avgs], axis=1)" }, { "code": null, "e": 15104, "s": 14866, "text": "Splitting features is a good way to make them useful in terms of machine learning. Most of the time the dataset contains string columns that violates tidy data principles. By extracting the utilizable parts of a column into new features:" }, { "code": null, "e": 15162, "s": 15104, "text": "We enable machine learning algorithms to comprehend them." }, { "code": null, "e": 15199, "s": 15162, "text": "Make possible to bin and group them." }, { "code": null, "e": 15262, "s": 15199, "text": "Improve model performance by uncovering potential information." }, { "code": null, "e": 15511, "s": 15262, "text": "Split function is a good option, however, there is no one way of splitting features. It depends on the characteristics of the column, how to split it. Let’s introduce it with two examples. First, a simple split function for an ordinary name column:" }, { "code": null, "e": 15885, "s": 15511, "text": "data.name0 Luther N. Gonzalez1 Charles M. Young2 Terry Lawson3 Kristen White4 Thomas Logsdon#Extracting first namesdata.name.str.split(\" \").map(lambda x: x[0])0 Luther1 Charles2 Terry3 Kristen4 Thomas#Extracting last namesdata.name.str.split(\" \").map(lambda x: x[-1])0 Gonzalez1 Young2 Lawson3 White4 Logsdon" }, { "code": null, "e": 16099, "s": 15885, "text": "The example above handles the names longer than two words by taking only the first and last elements and it makes the function robust for corner cases, which should be regarded when manipulating strings like that." }, { "code": null, "e": 16276, "s": 16099, "text": "Another case for split function is to extract a string part between two chars. The following example shows an implementation of this case by using two split functions in a row." }, { "code": null, "e": 16642, "s": 16276, "text": "#String extraction exampledata.title.head()0 Toy Story (1995)1 Jumanji (1995)2 Grumpier Old Men (1995)3 Waiting to Exhale (1995)4 Father of the Bride Part II (1995)data.title.str.split(\"(\", n=1, expand=True)[1].str.split(\")\", n=1, expand=True)[0]0 19951 19952 19953 19954 1995" }, { "code": null, "e": 16926, "s": 16642, "text": "In most cases, the numerical features of the dataset do not have a certain range and they differ from each other. In real life, it is nonsense to expect age and income columns to have the same range. But from the machine learning point of view, how these two columns can be compared?" }, { "code": null, "e": 17267, "s": 16926, "text": "Scaling solves this problem. The continuous features become identical in terms of the range, after a scaling process. This process is not mandatory for many algorithms, but it might be still nice to apply. However, the algorithms based on distance calculations such as k-NN or k-Means need to have scaled continuous features as model input." }, { "code": null, "e": 17316, "s": 17267, "text": "Basically, there are two common ways of scaling:" }, { "code": null, "e": 17636, "s": 17316, "text": "Normalization (or min-max normalization) scale all values in a fixed range between 0 and 1. This transformation does not change the distribution of the feature and due to the decreased standard deviations, the effects of the outliers increases. Therefore, before normalization, it is recommended to handle the outliers." }, { "code": null, "e": 17983, "s": 17636, "text": "data = pd.DataFrame({'value':[2,45, -23, 85, 28, 2, 35, -12]})data['normalized'] = (data['value'] - data['value'].min()) / (data['value'].max() - data['value'].min()) value normalized0 2 0.231 45 0.632 -23 0.003 85 1.004 28 0.475 2 0.236 35 0.547 -12 0.10" }, { "code": null, "e": 18246, "s": 17983, "text": "Standardization (or z-score normalization) scales the values while taking into account standard deviation. If the standard deviation of features is different, their range also would differ from each other. This reduces the effect of the outliers in the features." }, { "code": null, "e": 18356, "s": 18246, "text": "In the following formula of standardization, the mean is shown as ΞΌ and the standard deviation is shown as Οƒ." }, { "code": null, "e": 18700, "s": 18356, "text": "data = pd.DataFrame({'value':[2,45, -23, 85, 28, 2, 35, -12]})data['standardized'] = (data['value'] - data['value'].mean()) / data['value'].std() value standardized0 2 -0.521 45 0.702 -23 -1.233 85 1.844 28 0.225 2 -0.526 35 0.427 -12 -0.92" }, { "code": null, "e": 19055, "s": 18700, "text": "Though date columns usually provide valuable information about the model target, they are neglected as an input or used nonsensically for the machine learning algorithms. It might be the reason for this, that dates can be present in numerous formats, which make it hard to understand by algorithms, even they are simplified to a format like \"01–01–2017\"." }, { "code": null, "e": 19268, "s": 19055, "text": "Building an ordinal relationship between the values is very challenging for a machine learning algorithm if you leave the date columns without manipulation. Here, I suggest three types of preprocessing for dates:" }, { "code": null, "e": 19348, "s": 19268, "text": "Extracting the parts of the date into different columns: Year, month, day, etc." }, { "code": null, "e": 19450, "s": 19348, "text": "Extracting the time period between the current date and columns in terms of years, months, days, etc." }, { "code": null, "e": 19557, "s": 19450, "text": "Extracting some specific features from the date: Name of the weekday, Weekend or not, holiday or not, etc." }, { "code": null, "e": 19730, "s": 19557, "text": "If you transform the date column into the extracted columns like above, the information of them become disclosed and machine learning algorithms can easily understand them." }, { "code": null, "e": 20775, "s": 19730, "text": "from datetime import datedata = pd.DataFrame({'date':['01-01-2017','04-12-2008','23-06-1988','25-08-1999','20-02-1993',]})#Transform string to datedata['date'] = pd.to_datetime(data.date, format=\"%d-%m-%Y\")#Extracting Yeardata['year'] = data['date'].dt.year#Extracting Monthdata['month'] = data['date'].dt.month#Extracting passed years since the datedata['passed_years'] = date.today().year - data['date'].dt.year#Extracting passed months since the datedata['passed_months'] = (date.today().year - data['date'].dt.year) * 12 + date.today().month - data['date'].dt.month#Extracting the weekday name of the datedata['day_name'] = data['date'].dt.day_name() date year month passed_years passed_months day_name0 2017-01-01 2017 1 2 26 Sunday1 2008-12-04 2008 12 11 123 Thursday2 1988-06-23 1988 6 31 369 Thursday3 1999-08-25 1999 8 20 235 Wednesday4 1993-02-20 1993 2 26 313 Saturday" }, { "code": null, "e": 21028, "s": 20775, "text": "I tried to explain fundamental methods that can be beneficial in the feature engineering process. After this article, proceeding with other topics of data preparation such as feature selection, train/test splitting, and sampling might be a good option." }, { "code": null, "e": 21079, "s": 21028, "text": "You can check my other article about Oversampling." }, { "code": null, "e": 21296, "s": 21079, "text": "Lastly, I want to conclude the article with a reminder. These techniques are not magical tools. If your data tiny, dirty and useless, feature engineering may remain incapable. Do not forget β€œgarbage in, garbage out!”" }, { "code": null, "e": 21387, "s": 21296, "text": "Stack Overflow questions are very beneficial for every kind of feature engineering script." }, { "code": null, "e": 21455, "s": 21387, "text": "I highly recommend Kaggle competitions and their discussion boards." }, { "code": null, "e": 21494, "s": 21455, "text": "Ways to Detect and Remove the Outliers" }, { "code": null, "e": 21563, "s": 21494, "text": "Understanding Feature Engineering (Part 1) β€” Continuous Numeric Data" }, { "code": null, "e": 21625, "s": 21563, "text": "Understanding Feature Engineering (Part 2) β€” Categorical Data" }, { "code": null, "e": 21679, "s": 21625, "text": "Log Transformations for Skewed and Wide Distributions" }, { "code": null, "e": 21689, "s": 21679, "text": "Tidy data" } ]
Left pad a string in Java
To left pad a string, use the String.format and set the spaces. String.format("|%20s|", "demotext") If you add 30 above, it will display the first string after 30 spaces from the beginning. String.format("|%30s|", "demotext") Live Demo public class Demo { public static void main(String []args) { System.out.print(String.format("|%20s|", "demotext")); System.out.println("Left padded!"); } } | demotext|Left padded
[ { "code": null, "e": 1126, "s": 1062, "text": "To left pad a string, use the String.format and set the spaces." }, { "code": null, "e": 1162, "s": 1126, "text": "String.format(\"|%20s|\", \"demotext\")" }, { "code": null, "e": 1252, "s": 1162, "text": "If you add 30 above, it will display the first string after 30 spaces from the beginning." }, { "code": null, "e": 1288, "s": 1252, "text": "String.format(\"|%30s|\", \"demotext\")" }, { "code": null, "e": 1299, "s": 1288, "text": " Live Demo" }, { "code": null, "e": 1473, "s": 1299, "text": "public class Demo {\n public static void main(String []args) {\n System.out.print(String.format(\"|%20s|\", \"demotext\"));\n System.out.println(\"Left padded!\");\n }\n}" }, { "code": null, "e": 1496, "s": 1473, "text": "| demotext|Left padded" } ]
How to add footer in Android ListView?
This example demonstrates how do I add footer in Android ListView. 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. <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" > <ListView android:id="@+id/listView" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" > </ListView> </RelativeLayout> Step 3 – Create a layout file.xml and name it as listView_footer.xml and add the following code βˆ’ <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/textView" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Footer: End of the ListView!" android:textAppearance="?android:attr/textAppearanceLarge" android:padding="16sp" /> </LinearLayout> Step 4 βˆ’ Add the following code to src/MainActivity.java import java.util.ArrayList; import java.util.Arrays; import java.util.List; import android.app.Activity; import android.os.Bundle; import android.view.LayoutInflater; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ListView; public class MainActivity extends Activity { ListView listView; String[] country = new String[] { "India", "Australia", "South Africa", "North America", "South America", "Iceland", "GreenLand" }; List<String> LISTSTRING; LayoutInflater layoutInflater; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); listView = findViewById(R.id.listView); LISTSTRING = new ArrayList<>(Arrays.asList(country)); ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, LISTSTRING); layoutInflater = getLayoutInflater(); ViewGroup footer = (ViewGroup) layoutInflater.inflate(R.layout.listview_footer, listView, false); listView.addFooterView(footer); listView.setAdapter(adapter); } } Step 5 - Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample"> <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 –
[ { "code": null, "e": 1129, "s": 1062, "text": "This example demonstrates how do I add footer in Android ListView." }, { "code": null, "e": 1258, "s": 1129, "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": 1323, "s": 1258, "text": "Step 2 βˆ’ Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 1818, "s": 1323, "text": "<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\n <ListView\n android:id=\"@+id/listView\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_alignParentTop=\"true\"\n android:layout_centerHorizontal=\"true\" >\n </ListView>\n\n</RelativeLayout>" }, { "code": null, "e": 1916, "s": 1818, "text": "Step 3 – Create a layout file.xml and name it as listView_footer.xml and add the following code βˆ’" }, { "code": null, "e": 2440, "s": 1916, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:orientation=\"vertical\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\">\n \n <TextView\n android:id=\"@+id/textView\"\n android:layout_width=\"fill_parent\"\n android:layout_height=\"wrap_content\"\n android:text=\"Footer: End of the ListView!\"\n android:textAppearance=\"?android:attr/textAppearanceLarge\"\n android:padding=\"16sp\" />\n\n</LinearLayout>" }, { "code": null, "e": 2497, "s": 2440, "text": "Step 4 βˆ’ Add the following code to src/MainActivity.java" }, { "code": null, "e": 3690, "s": 2497, "text": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\nimport android.app.Activity;\nimport android.os.Bundle;\nimport android.view.LayoutInflater;\nimport android.view.ViewGroup;\nimport android.widget.ArrayAdapter;\nimport android.widget.ListView;\n\npublic class MainActivity extends Activity {\n\n ListView listView;\n String[] country = new String[] {\n \"India\",\n \"Australia\",\n \"South Africa\",\n \"North America\",\n \"South America\",\n \"Iceland\",\n \"GreenLand\"\n };\n List<String> LISTSTRING;\n LayoutInflater layoutInflater;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n\n listView = findViewById(R.id.listView);\n LISTSTRING = new ArrayList<>(Arrays.asList(country));\n\n ArrayAdapter<String> adapter = new ArrayAdapter<>(this,\n android.R.layout.simple_list_item_1, LISTSTRING);\n\n layoutInflater = getLayoutInflater();\n ViewGroup footer = (ViewGroup) layoutInflater.inflate(R.layout.listview_footer, listView, false);\n listView.addFooterView(footer);\n listView.setAdapter(adapter);\n\n }\n}" }, { "code": null, "e": 3745, "s": 3690, "text": "Step 5 - Add the following code to androidManifest.xml" }, { "code": null, "e": 4419, "s": 3745, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"app.com.sample\">\n\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": 4766, "s": 4419, "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 –" } ]
Explain aggregate functions with the help of SQL queries
Aggregate functions perform Calculation on a set of values and return a single value. They ignore NULL values except COUNT and are used with GROUP BY clause of SELECT statement. The different types of aggregate functions are βˆ’ AVG MAX MIN SUM COUNT() COUNT(*) Let’s consider an employee table. We will perform the calculations on this table by using aggregate functions. The keyword used to calculate the average of given items is AVG. It returns the average of the data values. Syntax The syntax is as follows βˆ’ select <column name> from <table name>; Example An example of use of average function is as follows βˆ’ select AVG(salary) from employee; Output You will get the following output βˆ’ AVG(salary)= 16800 The keyword used to return maximum value for a column is MAX. Syntax The syntax is as follows βˆ’ select MAX <column name> from <table name>; Example An example of use of maximum function is as follows βˆ’ select MAX(salary) from employee; Output You will get the following output βˆ’ Max(salary)=30000 The keyword used to return the minimum value for a column is MIN. Syntax The syntax is as follows βˆ’ select MIN <column-name> from <table-name>; Example An example of use of minimum function is as follows βˆ’ select MIN (salary) from employee; Output You will get the following output βˆ’ MIN(salary)=4000 It returns the sum(addition) of the data values. The keyword used to perform addition on data items is SUM. Syntax The syntax is as follows βˆ’ select SUM <column-name> from <table-name>; Example An example of use of SUM function is as follows βˆ’ select SUM (salary) from employee where city=’Pune’; Output You will get the following output βˆ’ SUM (salary)= 50000 It returns the total number of values in a given column. Syntax The syntax is given below βˆ’ select COUNT <column-name> from <table-name>; Example An example of use of COUNT function is as follows βˆ’ select COUNT(Empid) from employee; Output You will get the following output βˆ’ COUNT(Empid)= 5 It returns the number of rows in a table. Syntax The syntax is as follows βˆ’ select COUNT(*) from <table-name>; Example An example of use of COUNT(*) function is as follows: select COUNT(*) from employee; Output You will get the following output βˆ’ COUNT(*) =5
[ { "code": null, "e": 1240, "s": 1062, "text": "Aggregate functions perform Calculation on a set of values and return a single value. They ignore NULL values except COUNT and are used with GROUP BY clause of SELECT statement." }, { "code": null, "e": 1289, "s": 1240, "text": "The different types of aggregate functions are βˆ’" }, { "code": null, "e": 1293, "s": 1289, "text": "AVG" }, { "code": null, "e": 1297, "s": 1293, "text": "MAX" }, { "code": null, "e": 1301, "s": 1297, "text": "MIN" }, { "code": null, "e": 1305, "s": 1301, "text": "SUM" }, { "code": null, "e": 1313, "s": 1305, "text": "COUNT()" }, { "code": null, "e": 1322, "s": 1313, "text": "COUNT(*)" }, { "code": null, "e": 1433, "s": 1322, "text": "Let’s consider an employee table. We will perform the calculations on this table by using aggregate functions." }, { "code": null, "e": 1541, "s": 1433, "text": "The keyword used to calculate the average of given items is AVG. It returns the average of the data values." }, { "code": null, "e": 1548, "s": 1541, "text": "Syntax" }, { "code": null, "e": 1575, "s": 1548, "text": "The syntax is as follows βˆ’" }, { "code": null, "e": 1615, "s": 1575, "text": "select <column name> from <table name>;" }, { "code": null, "e": 1623, "s": 1615, "text": "Example" }, { "code": null, "e": 1677, "s": 1623, "text": "An example of use of average function is as follows βˆ’" }, { "code": null, "e": 1711, "s": 1677, "text": "select AVG(salary) from employee;" }, { "code": null, "e": 1718, "s": 1711, "text": "Output" }, { "code": null, "e": 1754, "s": 1718, "text": "You will get the following output βˆ’" }, { "code": null, "e": 1773, "s": 1754, "text": "AVG(salary)= 16800" }, { "code": null, "e": 1835, "s": 1773, "text": "The keyword used to return maximum value for a column is MAX." }, { "code": null, "e": 1842, "s": 1835, "text": "Syntax" }, { "code": null, "e": 1869, "s": 1842, "text": "The syntax is as follows βˆ’" }, { "code": null, "e": 1913, "s": 1869, "text": "select MAX <column name> from <table name>;" }, { "code": null, "e": 1921, "s": 1913, "text": "Example" }, { "code": null, "e": 1975, "s": 1921, "text": "An example of use of maximum function is as follows βˆ’" }, { "code": null, "e": 2009, "s": 1975, "text": "select MAX(salary) from employee;" }, { "code": null, "e": 2016, "s": 2009, "text": "Output" }, { "code": null, "e": 2052, "s": 2016, "text": "You will get the following output βˆ’" }, { "code": null, "e": 2070, "s": 2052, "text": "Max(salary)=30000" }, { "code": null, "e": 2136, "s": 2070, "text": "The keyword used to return the minimum value for a column is MIN." }, { "code": null, "e": 2143, "s": 2136, "text": "Syntax" }, { "code": null, "e": 2170, "s": 2143, "text": "The syntax is as follows βˆ’" }, { "code": null, "e": 2214, "s": 2170, "text": "select MIN <column-name> from <table-name>;" }, { "code": null, "e": 2222, "s": 2214, "text": "Example" }, { "code": null, "e": 2276, "s": 2222, "text": "An example of use of minimum function is as follows βˆ’" }, { "code": null, "e": 2311, "s": 2276, "text": "select MIN (salary) from employee;" }, { "code": null, "e": 2318, "s": 2311, "text": "Output" }, { "code": null, "e": 2354, "s": 2318, "text": "You will get the following output βˆ’" }, { "code": null, "e": 2371, "s": 2354, "text": "MIN(salary)=4000" }, { "code": null, "e": 2479, "s": 2371, "text": "It returns the sum(addition) of the data values. The keyword used to perform addition on data items is SUM." }, { "code": null, "e": 2486, "s": 2479, "text": "Syntax" }, { "code": null, "e": 2513, "s": 2486, "text": "The syntax is as follows βˆ’" }, { "code": null, "e": 2557, "s": 2513, "text": "select SUM <column-name> from <table-name>;" }, { "code": null, "e": 2565, "s": 2557, "text": "Example" }, { "code": null, "e": 2615, "s": 2565, "text": "An example of use of SUM function is as follows βˆ’" }, { "code": null, "e": 2668, "s": 2615, "text": "select SUM (salary) from employee where city=’Pune’;" }, { "code": null, "e": 2675, "s": 2668, "text": "Output" }, { "code": null, "e": 2711, "s": 2675, "text": "You will get the following output βˆ’" }, { "code": null, "e": 2731, "s": 2711, "text": "SUM (salary)= 50000" }, { "code": null, "e": 2788, "s": 2731, "text": "It returns the total number of values in a given column." }, { "code": null, "e": 2795, "s": 2788, "text": "Syntax" }, { "code": null, "e": 2823, "s": 2795, "text": "The syntax is given below βˆ’" }, { "code": null, "e": 2869, "s": 2823, "text": "select COUNT <column-name> from <table-name>;" }, { "code": null, "e": 2877, "s": 2869, "text": "Example" }, { "code": null, "e": 2929, "s": 2877, "text": "An example of use of COUNT function is as follows βˆ’" }, { "code": null, "e": 2964, "s": 2929, "text": "select COUNT(Empid) from employee;" }, { "code": null, "e": 2971, "s": 2964, "text": "Output" }, { "code": null, "e": 3007, "s": 2971, "text": "You will get the following output βˆ’" }, { "code": null, "e": 3023, "s": 3007, "text": "COUNT(Empid)= 5" }, { "code": null, "e": 3065, "s": 3023, "text": "It returns the number of rows in a table." }, { "code": null, "e": 3072, "s": 3065, "text": "Syntax" }, { "code": null, "e": 3099, "s": 3072, "text": "The syntax is as follows βˆ’" }, { "code": null, "e": 3134, "s": 3099, "text": "select COUNT(*) from <table-name>;" }, { "code": null, "e": 3142, "s": 3134, "text": "Example" }, { "code": null, "e": 3196, "s": 3142, "text": "An example of use of COUNT(*) function is as follows:" }, { "code": null, "e": 3227, "s": 3196, "text": "select COUNT(*) from employee;" }, { "code": null, "e": 3234, "s": 3227, "text": "Output" }, { "code": null, "e": 3270, "s": 3234, "text": "You will get the following output βˆ’" }, { "code": null, "e": 3282, "s": 3270, "text": "COUNT(*) =5" } ]
Pima Indians Diabetes - Prediction & KNN Visualization | by Hardik Deshmukh | Towards Data Science
In India, diabetes is a major issue. Between 1971 and 2000, the incidence of diabetes rose ten times, from 1.2% to 12.1%. 61.3 million people 20–79 years of age in India are estimated living with diabetes (Expectations of 2011). It is expected that by 2030 this number will rise to 101,2 million. In India there are reportedly 77.2 million people with prediabetes. In 2012, nearly 1 million people in India died of diabetes. 1 out of 4 individuals living in Chennai’s urban slums suffer from diabetes, which is about 7 per cent by three times the national average. One third of the deaths in India involve people under non-communicable diseases Sixty years old. Indians get diabetes 10 years before their Western counterparts on average. Changes in lifestyle lead to physical decreases Increased fat, sugar and activities activity calories and higher insulin cortisol levels Obesity and vulnerability. In 2011, India cost around $38 billion annually as a result of diabetes. Reference: http://www.arogyaworld.org/wp-content/uploads/2010/10/ArogyaWorld_IndiaDiabetes_FactSheets_CGI2013_web.pdf Code by Hardik Link to Colab notebook: https://colab.research.google.com/drive/1n4FNgK0DwtK0QALoWcyWjBtkCLxjGs-S?usp=sharing Pima Indians Diabetes Database (Predict the onset of diabetes based on diagnostic measures) UCI Machine Learning β€” Repository:https://www.kaggle.com/uciml/pima-indians-diabetes-database This dataset comes from the Diabetes and Digestive and Kidney Disease National Institutes. The purpose of this dataset is to diagnose whether or not a patient is diabetic, on the basis of certain diagnostic measures in the dataset. The selection of these instances from a larger database was subject to several restrictions. All patients are women from the Indian heritage of Pima, at least 21 years old. The data sets comprise several variables of the medical predictor, and one objective variable, Outcome. The forecasting variables include the patient’s number of pregnancies, BMI levels, insulin levels, age, etc. Smith, J.W., Everhart, J.E., Dickson, W.C., Knowler, W.C., & Johannes, R.S. (1988). Using the ADAP learning algorithm to forecast the onset of diabetes mellitus. In Proceedings of the Symposium on Computer Applications and Medical Care (pp. 261–265). IEEE Computer Society Press. Can you build a machine learning model to accurately predict whether or not the patients in the dataset have diabetes or not? Imports import numpy as npimport pandas as pd# Visualization importsimport matplotlib.pyplot as pltimport seaborn as sns# plotly import for Colabdef configure_plotly_browser_state(): import IPython display(IPython.core.display.HTML(''' <script src="/static/components/requirejs/require.js"></script> <script> requirejs.config({ paths: { base: '/static/base', plotly: 'https://cdn.plot.ly/plotly-latest.min.js?noext', }, }); </script> ''')) # plotly importimport plotly.express as pxfrom plotly import __version__import cufflinks as cffrom plotly.offline import download_plotlyjs,init_notebook_mode,plot,iplotinit_notebook_mode(connected=True)cf.go_offline()import IPythonIPython.get_ipython().events.register('pre_run_cell', configure_plotly_browser_state) Dataset # Loading Datasetdf = pd.read_csv('/content/drive/My Drive/dataset/knn/datasets_228_482_diabetes.csv')df.head() β€˜0’ value in below columns makes no sense. Hence making them NaN. df[['Glucose','BloodPressure','SkinThickness','Insulin','BMI']] = df[['Glucose','BloodPressure','SkinThickness','Insulin','BMI']].replace(0,np.NaN)df.isnull().sum() import missingno as msnop = msno.bar(df) !pip install impyuteimport sysfrom impyute.imputation.cs import fast_knnsys.setrecursionlimit(100000) #Increase the recursion limit of the OS# start the KNN trainingimputed_training=fast_knn(df[['Glucose','BloodPressure','SkinThickness','Insulin','BMI']].values, k=30)df_t1 = pd.DataFrame(imputed_training,columns=['Glucose','BloodPressure','SkinThickness','Insulin','BMI'])df[['Glucose','BloodPressure','SkinThickness','Insulin','BMI']] = df_t1[['Glucose','BloodPressure','SkinThickness','Insulin','BMI']]df.isnull().sum() df.info() df.describe() sns.heatmap(df.corr(),annot=True) p = df[df['Outcome']==1].hist(figsize = (20,20))plt.title('Diabetes Patient') KNN Visualization all features with Outcome X = df[[β€˜Pregnancies’, β€˜Glucose’, β€˜BloodPressure’, β€˜SkinThickness’, β€˜Insulin’,’BMI’, β€˜DiabetesPedigreeFunction’, β€˜Age’]] y = df[β€˜Outcome’] Note: 0 β€” Non Diabetic Patient and 1 β€” Diabetic Patient from sklearn.decomposition import PCAfrom mlxtend.plotting import plot_decision_regionsfrom sklearn.svm import SVCclf = SVC(C=100,gamma=0.0001)pca = PCA(n_components = 2)X_train2 = pca.fit_transform(X)clf.fit(X_train2, df['Outcome'].astype(int).values)plot_decision_regions(X_train2, df['Outcome'].astype(int).values, clf=clf, legend=2) KNN features visualization with each other: from sklearn import datasets, neighborsfrom mlxtend.plotting import plot_decision_regionsdef ok(X,Y): x = df[[X,Y]].values y = df['Outcome'].astype(int).values clf = neighbors.KNeighborsClassifier(n_neighbors=9) clf.fit(x, y) # Plotting decision region plot_decision_regions(x, y, clf=clf, legend=2) # Adding axes annotations plt.xlabel(X) plt.ylabel(Y) plt.title('Knn with K='+ str(9)) plt.show()tt = ['Pregnancies', 'Glucose', 'BloodPressure', 'SkinThickness', 'Insulin','BMI', 'DiabetesPedigreeFunction', 'Age']ll = len(tt)for i in range(0,ll): for j in range(i+1,ll): ok(tt[i],tt[j]) Note: 0 β€” Non Diabetic and 1 β€” Diabetic Data Z is rescaled to ΞΌ = 0 and ρ = 1, and this form is applied: from sklearn.preprocessing import StandardScalerscaler = StandardScaler()scaler.fit(df.drop('Outcome', axis = 1))scaler_features = scaler.transform(df.drop('Outcome', axis = 1))df_feat = pd.DataFrame(scaler_features, columns = df.columns[:-1])# appending the outcome featuredf_feat['Outcome'] = df['Outcome'].astype(int)df = df_feat.copy()df.head() # to reverse scaler transformation#s = scaler.inverse_transform(df_feat)#df_feat = pd.DataFrame(s, columns = df.columns[:-1]) Split X = df.drop('Outcome', axis = 1)y = df['Outcome']from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.3, random_state=0) Check for the best K value by getting Receiver Operating Characteristic Accuracy for each K ranging from 1 to 100 import sklearntt = {}il = []ac=[]for i in range(1,100): from sklearn.neighbors import KNeighborsClassifierknn = KNeighborsClassifier(n_neighbors=i)knn.fit(X_train,y_train)y_pred = knn.predict(X_test)from sklearn.metrics import accuracy_score il.append(i) ac.append( sklearn.metrics.roc_auc_score(y_test,y_pred) )tt.update({'K':il}) tt.update({'ROC_ACC':ac})vv = pd.DataFrame(tt)vv.sort_values('ROC_ACC',ascending=False,inplace=True,ignore_index=True)vv.head(10) Selecting β€˜k = 9’ from sklearn.neighbors import KNeighborsClassifierknn = KNeighborsClassifier(n_neighbors=9)knn.fit(X_train,y_train)y_pred = knn.predict(X_test)from sklearn.metrics import classification_reportprint(classification_report(y_test,y_pred)) from sklearn.metrics import confusion_matrixprint(confusion_matrix(y_test,y_pred))sns.heatmap(confusion_matrix(y_test,y_pred),annot=True) from sklearn.metrics import roc_curveplt.figure(dpi=100)fpr, tpr, thresholds = roc_curve(y_test, y_pred)plt.plot(fpr,tpr,label = "%.2f" %sklearn.metrics.roc_auc_score(y_test,y_pred))plt.legend(loc = 'lower right')plt.xlim([0.0, 1.0])plt.ylim([0.0, 1.0])plt.title('ROC curve for Diabetes classifier')plt.xlabel('False positive rate (1-Specificity)')plt.ylabel('True positive rate (Sensitivity)')plt.grid(True) import sklearnsklearn.metrics.roc_auc_score(y_test,y_pred) 0.7399724565329662 data = {'test':y_test.values.ravel(),'pred':y_pred.ravel(),'number':np.arange(0,len(y_test))}pt = pd.DataFrame(data)pt.iplot( kind='scatter', x='number', y=['test','pred'], color=['white','yellow'], theme='solar', mode='lines+markers' )
[ { "code": null, "e": 1147, "s": 172, "text": "In India, diabetes is a major issue. Between 1971 and 2000, the incidence of diabetes rose ten times, from 1.2% to 12.1%. 61.3 million people 20–79 years of age in India are estimated living with diabetes (Expectations of 2011). It is expected that by 2030 this number will rise to 101,2 million. In India there are reportedly 77.2 million people with prediabetes. In 2012, nearly 1 million people in India died of diabetes. 1 out of 4 individuals living in Chennai’s urban slums suffer from diabetes, which is about 7 per cent by three times the national average. One third of the deaths in India involve people under non-communicable diseases Sixty years old. Indians get diabetes 10 years before their Western counterparts on average. Changes in lifestyle lead to physical decreases Increased fat, sugar and activities activity calories and higher insulin cortisol levels Obesity and vulnerability. In 2011, India cost around $38 billion annually as a result of diabetes." }, { "code": null, "e": 1265, "s": 1147, "text": "Reference: http://www.arogyaworld.org/wp-content/uploads/2010/10/ArogyaWorld_IndiaDiabetes_FactSheets_CGI2013_web.pdf" }, { "code": null, "e": 1280, "s": 1265, "text": "Code by Hardik" }, { "code": null, "e": 1390, "s": 1280, "text": "Link to Colab notebook: https://colab.research.google.com/drive/1n4FNgK0DwtK0QALoWcyWjBtkCLxjGs-S?usp=sharing" }, { "code": null, "e": 1482, "s": 1390, "text": "Pima Indians Diabetes Database (Predict the onset of diabetes based on diagnostic measures)" }, { "code": null, "e": 1576, "s": 1482, "text": "UCI Machine Learning β€” Repository:https://www.kaggle.com/uciml/pima-indians-diabetes-database" }, { "code": null, "e": 1981, "s": 1576, "text": "This dataset comes from the Diabetes and Digestive and Kidney Disease National Institutes. The purpose of this dataset is to diagnose whether or not a patient is diabetic, on the basis of certain diagnostic measures in the dataset. The selection of these instances from a larger database was subject to several restrictions. All patients are women from the Indian heritage of Pima, at least 21 years old." }, { "code": null, "e": 2194, "s": 1981, "text": "The data sets comprise several variables of the medical predictor, and one objective variable, Outcome. The forecasting variables include the patient’s number of pregnancies, BMI levels, insulin levels, age, etc." }, { "code": null, "e": 2474, "s": 2194, "text": "Smith, J.W., Everhart, J.E., Dickson, W.C., Knowler, W.C., & Johannes, R.S. (1988). Using the ADAP learning algorithm to forecast the onset of diabetes mellitus. In Proceedings of the Symposium on Computer Applications and Medical Care (pp. 261–265). IEEE Computer Society Press." }, { "code": null, "e": 2600, "s": 2474, "text": "Can you build a machine learning model to accurately predict whether or not the patients in the dataset have diabetes or not?" }, { "code": null, "e": 2608, "s": 2600, "text": "Imports" }, { "code": null, "e": 3454, "s": 2608, "text": "import numpy as npimport pandas as pd# Visualization importsimport matplotlib.pyplot as pltimport seaborn as sns# plotly import for Colabdef configure_plotly_browser_state(): import IPython display(IPython.core.display.HTML(''' <script src=\"/static/components/requirejs/require.js\"></script> <script> requirejs.config({ paths: { base: '/static/base', plotly: 'https://cdn.plot.ly/plotly-latest.min.js?noext', }, }); </script> ''')) # plotly importimport plotly.express as pxfrom plotly import __version__import cufflinks as cffrom plotly.offline import download_plotlyjs,init_notebook_mode,plot,iplotinit_notebook_mode(connected=True)cf.go_offline()import IPythonIPython.get_ipython().events.register('pre_run_cell', configure_plotly_browser_state)" }, { "code": null, "e": 3462, "s": 3454, "text": "Dataset" }, { "code": null, "e": 3574, "s": 3462, "text": "# Loading Datasetdf = pd.read_csv('/content/drive/My Drive/dataset/knn/datasets_228_482_diabetes.csv')df.head()" }, { "code": null, "e": 3640, "s": 3574, "text": "β€˜0’ value in below columns makes no sense. Hence making them NaN." }, { "code": null, "e": 3805, "s": 3640, "text": "df[['Glucose','BloodPressure','SkinThickness','Insulin','BMI']] = df[['Glucose','BloodPressure','SkinThickness','Insulin','BMI']].replace(0,np.NaN)df.isnull().sum()" }, { "code": null, "e": 3846, "s": 3805, "text": "import missingno as msnop = msno.bar(df)" }, { "code": null, "e": 4370, "s": 3846, "text": "!pip install impyuteimport sysfrom impyute.imputation.cs import fast_knnsys.setrecursionlimit(100000) #Increase the recursion limit of the OS# start the KNN trainingimputed_training=fast_knn(df[['Glucose','BloodPressure','SkinThickness','Insulin','BMI']].values, k=30)df_t1 = pd.DataFrame(imputed_training,columns=['Glucose','BloodPressure','SkinThickness','Insulin','BMI'])df[['Glucose','BloodPressure','SkinThickness','Insulin','BMI']] = df_t1[['Glucose','BloodPressure','SkinThickness','Insulin','BMI']]df.isnull().sum()" }, { "code": null, "e": 4380, "s": 4370, "text": "df.info()" }, { "code": null, "e": 4394, "s": 4380, "text": "df.describe()" }, { "code": null, "e": 4428, "s": 4394, "text": "sns.heatmap(df.corr(),annot=True)" }, { "code": null, "e": 4506, "s": 4428, "text": "p = df[df['Outcome']==1].hist(figsize = (20,20))plt.title('Diabetes Patient')" }, { "code": null, "e": 4550, "s": 4506, "text": "KNN Visualization all features with Outcome" }, { "code": null, "e": 4671, "s": 4550, "text": "X = df[[β€˜Pregnancies’, β€˜Glucose’, β€˜BloodPressure’, β€˜SkinThickness’, β€˜Insulin’,’BMI’, β€˜DiabetesPedigreeFunction’, β€˜Age’]]" }, { "code": null, "e": 4689, "s": 4671, "text": "y = df[β€˜Outcome’]" }, { "code": null, "e": 4745, "s": 4689, "text": "Note: 0 β€” Non Diabetic Patient and 1 β€” Diabetic Patient" }, { "code": null, "e": 5082, "s": 4745, "text": "from sklearn.decomposition import PCAfrom mlxtend.plotting import plot_decision_regionsfrom sklearn.svm import SVCclf = SVC(C=100,gamma=0.0001)pca = PCA(n_components = 2)X_train2 = pca.fit_transform(X)clf.fit(X_train2, df['Outcome'].astype(int).values)plot_decision_regions(X_train2, df['Outcome'].astype(int).values, clf=clf, legend=2)" }, { "code": null, "e": 5126, "s": 5082, "text": "KNN features visualization with each other:" }, { "code": null, "e": 5729, "s": 5126, "text": "from sklearn import datasets, neighborsfrom mlxtend.plotting import plot_decision_regionsdef ok(X,Y): x = df[[X,Y]].values y = df['Outcome'].astype(int).values clf = neighbors.KNeighborsClassifier(n_neighbors=9) clf.fit(x, y) # Plotting decision region plot_decision_regions(x, y, clf=clf, legend=2) # Adding axes annotations plt.xlabel(X) plt.ylabel(Y) plt.title('Knn with K='+ str(9)) plt.show()tt = ['Pregnancies', 'Glucose', 'BloodPressure', 'SkinThickness', 'Insulin','BMI', 'DiabetesPedigreeFunction', 'Age']ll = len(tt)for i in range(0,ll): for j in range(i+1,ll): ok(tt[i],tt[j])" }, { "code": null, "e": 5769, "s": 5729, "text": "Note: 0 β€” Non Diabetic and 1 β€” Diabetic" }, { "code": null, "e": 5834, "s": 5769, "text": "Data Z is rescaled to ΞΌ = 0 and ρ = 1, and this form is applied:" }, { "code": null, "e": 6183, "s": 5834, "text": "from sklearn.preprocessing import StandardScalerscaler = StandardScaler()scaler.fit(df.drop('Outcome', axis = 1))scaler_features = scaler.transform(df.drop('Outcome', axis = 1))df_feat = pd.DataFrame(scaler_features, columns = df.columns[:-1])# appending the outcome featuredf_feat['Outcome'] = df['Outcome'].astype(int)df = df_feat.copy()df.head()" }, { "code": null, "e": 6309, "s": 6183, "text": "# to reverse scaler transformation#s = scaler.inverse_transform(df_feat)#df_feat = pd.DataFrame(s, columns = df.columns[:-1])" }, { "code": null, "e": 6315, "s": 6309, "text": "Split" }, { "code": null, "e": 6507, "s": 6315, "text": "X = df.drop('Outcome', axis = 1)y = df['Outcome']from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.3, random_state=0)" }, { "code": null, "e": 6621, "s": 6507, "text": "Check for the best K value by getting Receiver Operating Characteristic Accuracy for each K ranging from 1 to 100" }, { "code": null, "e": 7088, "s": 6621, "text": "import sklearntt = {}il = []ac=[]for i in range(1,100): from sklearn.neighbors import KNeighborsClassifierknn = KNeighborsClassifier(n_neighbors=i)knn.fit(X_train,y_train)y_pred = knn.predict(X_test)from sklearn.metrics import accuracy_score il.append(i) ac.append( sklearn.metrics.roc_auc_score(y_test,y_pred) )tt.update({'K':il}) tt.update({'ROC_ACC':ac})vv = pd.DataFrame(tt)vv.sort_values('ROC_ACC',ascending=False,inplace=True,ignore_index=True)vv.head(10)" }, { "code": null, "e": 7106, "s": 7088, "text": "Selecting β€˜k = 9’" }, { "code": null, "e": 7342, "s": 7106, "text": "from sklearn.neighbors import KNeighborsClassifierknn = KNeighborsClassifier(n_neighbors=9)knn.fit(X_train,y_train)y_pred = knn.predict(X_test)from sklearn.metrics import classification_reportprint(classification_report(y_test,y_pred))" }, { "code": null, "e": 7480, "s": 7342, "text": "from sklearn.metrics import confusion_matrixprint(confusion_matrix(y_test,y_pred))sns.heatmap(confusion_matrix(y_test,y_pred),annot=True)" }, { "code": null, "e": 7889, "s": 7480, "text": "from sklearn.metrics import roc_curveplt.figure(dpi=100)fpr, tpr, thresholds = roc_curve(y_test, y_pred)plt.plot(fpr,tpr,label = \"%.2f\" %sklearn.metrics.roc_auc_score(y_test,y_pred))plt.legend(loc = 'lower right')plt.xlim([0.0, 1.0])plt.ylim([0.0, 1.0])plt.title('ROC curve for Diabetes classifier')plt.xlabel('False positive rate (1-Specificity)')plt.ylabel('True positive rate (Sensitivity)')plt.grid(True)" }, { "code": null, "e": 7948, "s": 7889, "text": "import sklearnsklearn.metrics.roc_auc_score(y_test,y_pred)" }, { "code": null, "e": 7967, "s": 7948, "text": "0.7399724565329662" } ]
6 Amazing TensorFlow.js Projects to Kickstart Machine Learning on Web | by Anupam Chugh | Towards Data Science
As machine learning continues to accelerate, more and more languages are joining the bandwagon. JavaScript which has been the leader of the web ecosystem for a while now has slowly gained pace in machine learning as well. An encouraging number of JavaScript libraries, specifically for machine learning have released over the past year. This would certainly boost AI-powered web browsers. Additionally, JavaScript for machine learning has the advantage of quick and easy deployment of models in mobile applications by leveraging web views. At the heart of TensorFlow, we have a Web GL accelerated TensorFlow.js library that lets you train and run models directly in the browser or with Node.js. The best thing is, you don’t need to be a machine learning expert in order to deploy basic models as the library already provides a bunch of pre-trained models for classification, segmentation, and more. Let’s look at a few awesome libraries build on top of TensorFlow.js to inspire your next machine learning project. Face detection has been one of the classic use cases in Open-CV and naturally, it became the common use case in machine learning as well. face-api.js is a JavaScript face recognition library implemented on top of TensorFlow.js. It lets you detect and recognize faces and landmarks while also determining emotions and gender in images. The library completely abstracts away the underlying implementation to provide you with an easy to use high-level API. All you need to do is invoke the methods for the relevant neural net model with an option to also call the ready-drawing functions for overlaying the feature points on the canvas. Here’s the basic code for setting up face detection with landmark and expression detection: const detection = await faceapi.detectAllFaces(image) .withFaceLandmarks() .withFaceExpressions(); Style transfer today, is the most popular deep learning tasks. From photo editing apps to customizing themes in your apps, its possibilities are endless. At a very high level, neural style transfer involves imparting the style from one image into another. Generally, you can use famous paintings or abstract arts to bring a new look to your input image. Arbitrary style transfer is built on top of TensorFlow.js to work fully in your browser. You can combine more than one style into an image and also set the style strength density to control the level of texture that’s visible in the final output. nsfw.js is another cool library that lets you screen and classify images or gifs in your browser. This is handy if you need to censor content that isn’t for kids. Running the model returns 5 classes with probabilities based on which you can choose to apply a blur or pixelate filter on the input image. Here’s the code that shows how easy it is to load the model and run inferences: const model = await nsfwjs.load()const predictions = await model.classify(img) nsfw-filter is a great extension of the above library that blocks NSFW images from displaying in your browsers. Image Segmentation helps us highlight and crop out certain features in an image. Changing the background of an image is the most straightforward use case. But what if you need to do just the opposite? Gladly, there’s a cool open source project that lets you remove humans from an image. This TensorFlow.js project works like a charm in real-time image processing and is handy when you’re using a video-call feature in your web apps. Hand tracking is another interesting machine learning task. By tracking the position of hands in real-time you can build touchless gesture-based browsers and do motion capture for clicking selfies. From writing and drawing doodles with your fingers to scrolling your screens without a mouse or swipe, the use cases of hand tracking are truly limitless. Handtrack.js is just the library you’d need in such times. Besides providing bounding box points it also lets you set custom parameters when running the model. Panda, a powerful Python package is one of the most sought after libraries in machine learning to perform data manipulation, cleaning, visualization and a lot of other tasks. JavaScript despite making good strides in machine learning always lacked a panda like library for pre-processing tasks. But not anymore. Danfo.js is a new open-source JavaScript library built on top of TensorFlow.js. It provides easy to use data structures to easily convert Arrays, JSON, Objects, Tensors, and differently-indexed data structures into DataFrame objects. This will make handling datasets and performing tasks like merging or splitting them a whole lot easier. TensorFlow.js aims at letting developers train, and run machine learning models entirely in their browsers. It’s a great way for JavaScript developers to find inroads into the world of machine learning. The best thing is unlike CoreML which runs within Apple’s ecosystem, TensorFlow.js can run on iOS, macOS, Linux, Android, and any platform that supports a browser. I hope the above libraries and projects inspire you to start building amazing AI-powered web applications. That’s it for this one. Thanks for reading.
[ { "code": null, "e": 394, "s": 172, "text": "As machine learning continues to accelerate, more and more languages are joining the bandwagon. JavaScript which has been the leader of the web ecosystem for a while now has slowly gained pace in machine learning as well." }, { "code": null, "e": 712, "s": 394, "text": "An encouraging number of JavaScript libraries, specifically for machine learning have released over the past year. This would certainly boost AI-powered web browsers. Additionally, JavaScript for machine learning has the advantage of quick and easy deployment of models in mobile applications by leveraging web views." }, { "code": null, "e": 1071, "s": 712, "text": "At the heart of TensorFlow, we have a Web GL accelerated TensorFlow.js library that lets you train and run models directly in the browser or with Node.js. The best thing is, you don’t need to be a machine learning expert in order to deploy basic models as the library already provides a bunch of pre-trained models for classification, segmentation, and more." }, { "code": null, "e": 1186, "s": 1071, "text": "Let’s look at a few awesome libraries build on top of TensorFlow.js to inspire your next machine learning project." }, { "code": null, "e": 1324, "s": 1186, "text": "Face detection has been one of the classic use cases in Open-CV and naturally, it became the common use case in machine learning as well." }, { "code": null, "e": 1521, "s": 1324, "text": "face-api.js is a JavaScript face recognition library implemented on top of TensorFlow.js. It lets you detect and recognize faces and landmarks while also determining emotions and gender in images." }, { "code": null, "e": 1820, "s": 1521, "text": "The library completely abstracts away the underlying implementation to provide you with an easy to use high-level API. All you need to do is invoke the methods for the relevant neural net model with an option to also call the ready-drawing functions for overlaying the feature points on the canvas." }, { "code": null, "e": 1912, "s": 1820, "text": "Here’s the basic code for setting up face detection with landmark and expression detection:" }, { "code": null, "e": 2082, "s": 1912, "text": "const detection = await faceapi.detectAllFaces(image) .withFaceLandmarks() .withFaceExpressions();" }, { "code": null, "e": 2236, "s": 2082, "text": "Style transfer today, is the most popular deep learning tasks. From photo editing apps to customizing themes in your apps, its possibilities are endless." }, { "code": null, "e": 2436, "s": 2236, "text": "At a very high level, neural style transfer involves imparting the style from one image into another. Generally, you can use famous paintings or abstract arts to bring a new look to your input image." }, { "code": null, "e": 2525, "s": 2436, "text": "Arbitrary style transfer is built on top of TensorFlow.js to work fully in your browser." }, { "code": null, "e": 2683, "s": 2525, "text": "You can combine more than one style into an image and also set the style strength density to control the level of texture that’s visible in the final output." }, { "code": null, "e": 2846, "s": 2683, "text": "nsfw.js is another cool library that lets you screen and classify images or gifs in your browser. This is handy if you need to censor content that isn’t for kids." }, { "code": null, "e": 2986, "s": 2846, "text": "Running the model returns 5 classes with probabilities based on which you can choose to apply a blur or pixelate filter on the input image." }, { "code": null, "e": 3066, "s": 2986, "text": "Here’s the code that shows how easy it is to load the model and run inferences:" }, { "code": null, "e": 3145, "s": 3066, "text": "const model = await nsfwjs.load()const predictions = await model.classify(img)" }, { "code": null, "e": 3257, "s": 3145, "text": "nsfw-filter is a great extension of the above library that blocks NSFW images from displaying in your browsers." }, { "code": null, "e": 3412, "s": 3257, "text": "Image Segmentation helps us highlight and crop out certain features in an image. Changing the background of an image is the most straightforward use case." }, { "code": null, "e": 3544, "s": 3412, "text": "But what if you need to do just the opposite? Gladly, there’s a cool open source project that lets you remove humans from an image." }, { "code": null, "e": 3690, "s": 3544, "text": "This TensorFlow.js project works like a charm in real-time image processing and is handy when you’re using a video-call feature in your web apps." }, { "code": null, "e": 3888, "s": 3690, "text": "Hand tracking is another interesting machine learning task. By tracking the position of hands in real-time you can build touchless gesture-based browsers and do motion capture for clicking selfies." }, { "code": null, "e": 4043, "s": 3888, "text": "From writing and drawing doodles with your fingers to scrolling your screens without a mouse or swipe, the use cases of hand tracking are truly limitless." }, { "code": null, "e": 4203, "s": 4043, "text": "Handtrack.js is just the library you’d need in such times. Besides providing bounding box points it also lets you set custom parameters when running the model." }, { "code": null, "e": 4378, "s": 4203, "text": "Panda, a powerful Python package is one of the most sought after libraries in machine learning to perform data manipulation, cleaning, visualization and a lot of other tasks." }, { "code": null, "e": 4515, "s": 4378, "text": "JavaScript despite making good strides in machine learning always lacked a panda like library for pre-processing tasks. But not anymore." }, { "code": null, "e": 4749, "s": 4515, "text": "Danfo.js is a new open-source JavaScript library built on top of TensorFlow.js. It provides easy to use data structures to easily convert Arrays, JSON, Objects, Tensors, and differently-indexed data structures into DataFrame objects." }, { "code": null, "e": 4854, "s": 4749, "text": "This will make handling datasets and performing tasks like merging or splitting them a whole lot easier." }, { "code": null, "e": 5057, "s": 4854, "text": "TensorFlow.js aims at letting developers train, and run machine learning models entirely in their browsers. It’s a great way for JavaScript developers to find inroads into the world of machine learning." }, { "code": null, "e": 5221, "s": 5057, "text": "The best thing is unlike CoreML which runs within Apple’s ecosystem, TensorFlow.js can run on iOS, macOS, Linux, Android, and any platform that supports a browser." }, { "code": null, "e": 5328, "s": 5221, "text": "I hope the above libraries and projects inspire you to start building amazing AI-powered web applications." } ]
LISP - Constants
In LISP, constants are variables that never change their values during program execution. Constants are declared using the defconstant construct. The following example shows declaring a global constant PI and later using this value inside a function named area-circle that calculates the area of a circle. The defun construct is used for defining a function, we will look into it in the Functions chapter. Create a new source code file named main.lisp and type the following code in it. (defconstant PI 3.141592) (defun area-circle(rad) (terpri) (format t "Radius: ~5f" rad) (format t "~%Area: ~10f" (* PI rad rad))) (area-circle 10) When you click the Execute button, or type Ctrl+E, LISP executes it immediately and the result returned is. Radius: 10.0 Area: 314.1592 79 Lectures 7 hours Arnold Higuit Print Add Notes Bookmark this page
[ { "code": null, "e": 2206, "s": 2060, "text": "In LISP, constants are variables that never change their values during program execution. Constants are declared using the defconstant construct." }, { "code": null, "e": 2366, "s": 2206, "text": "The following example shows declaring a global constant PI and later using this value inside a function named area-circle that calculates the area of a circle." }, { "code": null, "e": 2466, "s": 2366, "text": "The defun construct is used for defining a function, we will look into it in the Functions chapter." }, { "code": null, "e": 2547, "s": 2466, "text": "Create a new source code file named main.lisp and type the following code in it." }, { "code": null, "e": 2703, "s": 2547, "text": "(defconstant PI 3.141592)\n(defun area-circle(rad)\n (terpri)\n (format t \"Radius: ~5f\" rad)\n (format t \"~%Area: ~10f\" (* PI rad rad)))\n(area-circle 10)" }, { "code": null, "e": 2811, "s": 2703, "text": "When you click the Execute button, or type Ctrl+E, LISP executes it immediately and the result returned is." }, { "code": null, "e": 2843, "s": 2811, "text": "Radius: 10.0\nArea: 314.1592\n" }, { "code": null, "e": 2876, "s": 2843, "text": "\n 79 Lectures \n 7 hours \n" }, { "code": null, "e": 2891, "s": 2876, "text": " Arnold Higuit" }, { "code": null, "e": 2898, "s": 2891, "text": " Print" }, { "code": null, "e": 2909, "s": 2898, "text": " Add Notes" } ]
Create a Plotly Data Visualization App Using One Line of JS | by Edward Krueger | Towards Data Science
By: Edward Krueger and Douglas Franklin Here we discuss a Plotly data visualization application created using Python and a single line of JavaScript code. This pattern allows developers to code logic and visualizations almost completely into the backend of your application. You don’t need to know javascript to do what we cover here. Here is the link to our repository for the project. github.com This repository is part of Edwards's β€œPlotly six ways” or β€œp-6-w” series on his GitHub. Feel free to check out the other patterns if you are interested! Dash and Streamlit are great dashboarding technologies. However, they lack the flexibility offered by Flask. This is because they are more opinionated and have compatibility limitations with existing technologies. The β€˜lock-in’ effect can cause issues when transitioning from prototype to minimum viable product and beyond. While Dash and especially Streamlit are good for proof of concepts, it is better to keep one's options open by using Flask when building a prototype. Additionally, making most custom dashboards is not difficult and can be accomplished easily with Flask alone. For simple visualizations that don't need interactivity with your page, this pattern with Flask and Plotly is a great solution. You get all the nice D3 features, like hover text events, without limiting your available production paths. Plotly allows you to make interactive figures in just a few lines of code using either Python or JavaScript. Keep in mind, Plotly plots are all generated from JSONs being interpreted by d3. This allows us to be pretty light on the JavaScript as long as we can deliver a proper JSON to our front end. We can have plotly.py generate a plot just by placing a properly formatted JSON into our HTML with jinja. This is possible because Plotly uses D3.js under the hood to generate our visualizations. Plotly objects consist of one or more data components and a layout component. Both have subcomponents. Most, but not all, of the formatting is controlled in the layout. Additionally, we can code our layout and traces using Python syntax. Then use one line of JavaScript in our HTML page to create the visualization. You don’t need to create an account to use Plotly, contrary to how some document examples might make it seem. You don’t need to be online to use Plotly, either. You’ll simply need to install the package. pip install plotly You’ll have to follow the trace and layout structure specific to the visualization you are creating, seen in the Plotly Docs here. plotly.com Plotly Express is a built-in part of the plotly library, and is the recommended starting point for creating the most common figures. Plotly Express allows you to make more complete visualizations with less code. This often results in charts that look better than vanilla Plotly charts. Plotly Express was released in March 2019 and is in active development, with support for more charts on the way. Plotly Express can reduce the code required to make many Plotly figures from a Pandas DataFrame by a factor of 10. Plotly Express expects your DataFrame to arrive in Tidy format, meaning each row represents an observation and each column represents a variable. Install Plotly Express with: pip install plotly_express Express allows you to make many figure types quickly, but not all of the vanilla Plotly charts are available yet. The key here is to JSONify the Plotly trace properly in the Python app. This allows Plotly to use JSONs directly from the HTML to generate plots. Be sure to serialize JSON with cls=plotly.utils.plotlyJSONEncoder. Use jinja to bring JSON data into HTML, as seen here. The above code can be refactored into a single line of JavaScript. This line tells Plotly to use the newPlot method to generate β€œmyPlot” using the β€˜data’ and β€˜layout’ passed in through the jinja templating. You’ll need to import Plotly into your Python app, as seen below. import plotly.express as px Now instead of creating a layout and traces for our visualization, we simply need to generate a β€˜fig’ based on the Plotly Express documentation. plotly.com Plotly express can take in a dictionary or Dataframe to generate plots. Notice in our code that we are using β€˜data,’ which is a dictionary and list comprehensions to generate our x and y variables. Similarly, we use the plotly.utils.PlotlyJSONEncoder to properly serialize our JSONs before templating them into the HTML document. Now that we have refactored our app to use python and a single line of javascript, we deployed our app to Heroku. For more on how to deploy to Heroku, check out this article. towardsdatascience.com Remember creating custom dashboards is easy with Plotly and Flask. There is no need to lock yourself into technologies during a prototyping or proof of concept development phase. With Flask and Plotly or Plotly Express, you can create powerful dashboards without knowing any JavaScript code. Simply by serializing your plots properly and templating them into your front end with Jinja, you can have an app that is 99.9% Python. By keeping it simple early, you allow yourself a flexible path toward the data product you need. Thank you for reading, and best of luck in your data endeavors.
[ { "code": null, "e": 211, "s": 171, "text": "By: Edward Krueger and Douglas Franklin" }, { "code": null, "e": 506, "s": 211, "text": "Here we discuss a Plotly data visualization application created using Python and a single line of JavaScript code. This pattern allows developers to code logic and visualizations almost completely into the backend of your application. You don’t need to know javascript to do what we cover here." }, { "code": null, "e": 558, "s": 506, "text": "Here is the link to our repository for the project." }, { "code": null, "e": 569, "s": 558, "text": "github.com" }, { "code": null, "e": 722, "s": 569, "text": "This repository is part of Edwards's β€œPlotly six ways” or β€œp-6-w” series on his GitHub. Feel free to check out the other patterns if you are interested!" }, { "code": null, "e": 1046, "s": 722, "text": "Dash and Streamlit are great dashboarding technologies. However, they lack the flexibility offered by Flask. This is because they are more opinionated and have compatibility limitations with existing technologies. The β€˜lock-in’ effect can cause issues when transitioning from prototype to minimum viable product and beyond." }, { "code": null, "e": 1306, "s": 1046, "text": "While Dash and especially Streamlit are good for proof of concepts, it is better to keep one's options open by using Flask when building a prototype. Additionally, making most custom dashboards is not difficult and can be accomplished easily with Flask alone." }, { "code": null, "e": 1542, "s": 1306, "text": "For simple visualizations that don't need interactivity with your page, this pattern with Flask and Plotly is a great solution. You get all the nice D3 features, like hover text events, without limiting your available production paths." }, { "code": null, "e": 1842, "s": 1542, "text": "Plotly allows you to make interactive figures in just a few lines of code using either Python or JavaScript. Keep in mind, Plotly plots are all generated from JSONs being interpreted by d3. This allows us to be pretty light on the JavaScript as long as we can deliver a proper JSON to our front end." }, { "code": null, "e": 2354, "s": 1842, "text": "We can have plotly.py generate a plot just by placing a properly formatted JSON into our HTML with jinja. This is possible because Plotly uses D3.js under the hood to generate our visualizations. Plotly objects consist of one or more data components and a layout component. Both have subcomponents. Most, but not all, of the formatting is controlled in the layout. Additionally, we can code our layout and traces using Python syntax. Then use one line of JavaScript in our HTML page to create the visualization." }, { "code": null, "e": 2515, "s": 2354, "text": "You don’t need to create an account to use Plotly, contrary to how some document examples might make it seem. You don’t need to be online to use Plotly, either." }, { "code": null, "e": 2558, "s": 2515, "text": "You’ll simply need to install the package." }, { "code": null, "e": 2577, "s": 2558, "text": "pip install plotly" }, { "code": null, "e": 2708, "s": 2577, "text": "You’ll have to follow the trace and layout structure specific to the visualization you are creating, seen in the Plotly Docs here." }, { "code": null, "e": 2719, "s": 2708, "text": "plotly.com" }, { "code": null, "e": 3005, "s": 2719, "text": "Plotly Express is a built-in part of the plotly library, and is the recommended starting point for creating the most common figures. Plotly Express allows you to make more complete visualizations with less code. This often results in charts that look better than vanilla Plotly charts." }, { "code": null, "e": 3118, "s": 3005, "text": "Plotly Express was released in March 2019 and is in active development, with support for more charts on the way." }, { "code": null, "e": 3379, "s": 3118, "text": "Plotly Express can reduce the code required to make many Plotly figures from a Pandas DataFrame by a factor of 10. Plotly Express expects your DataFrame to arrive in Tidy format, meaning each row represents an observation and each column represents a variable." }, { "code": null, "e": 3408, "s": 3379, "text": "Install Plotly Express with:" }, { "code": null, "e": 3435, "s": 3408, "text": "pip install plotly_express" }, { "code": null, "e": 3549, "s": 3435, "text": "Express allows you to make many figure types quickly, but not all of the vanilla Plotly charts are available yet." }, { "code": null, "e": 3695, "s": 3549, "text": "The key here is to JSONify the Plotly trace properly in the Python app. This allows Plotly to use JSONs directly from the HTML to generate plots." }, { "code": null, "e": 3762, "s": 3695, "text": "Be sure to serialize JSON with cls=plotly.utils.plotlyJSONEncoder." }, { "code": null, "e": 3816, "s": 3762, "text": "Use jinja to bring JSON data into HTML, as seen here." }, { "code": null, "e": 3883, "s": 3816, "text": "The above code can be refactored into a single line of JavaScript." }, { "code": null, "e": 4023, "s": 3883, "text": "This line tells Plotly to use the newPlot method to generate β€œmyPlot” using the β€˜data’ and β€˜layout’ passed in through the jinja templating." }, { "code": null, "e": 4089, "s": 4023, "text": "You’ll need to import Plotly into your Python app, as seen below." }, { "code": null, "e": 4117, "s": 4089, "text": "import plotly.express as px" }, { "code": null, "e": 4262, "s": 4117, "text": "Now instead of creating a layout and traces for our visualization, we simply need to generate a β€˜fig’ based on the Plotly Express documentation." }, { "code": null, "e": 4273, "s": 4262, "text": "plotly.com" }, { "code": null, "e": 4471, "s": 4273, "text": "Plotly express can take in a dictionary or Dataframe to generate plots. Notice in our code that we are using β€˜data,’ which is a dictionary and list comprehensions to generate our x and y variables." }, { "code": null, "e": 4603, "s": 4471, "text": "Similarly, we use the plotly.utils.PlotlyJSONEncoder to properly serialize our JSONs before templating them into the HTML document." }, { "code": null, "e": 4778, "s": 4603, "text": "Now that we have refactored our app to use python and a single line of javascript, we deployed our app to Heroku. For more on how to deploy to Heroku, check out this article." }, { "code": null, "e": 4801, "s": 4778, "text": "towardsdatascience.com" }, { "code": null, "e": 4980, "s": 4801, "text": "Remember creating custom dashboards is easy with Plotly and Flask. There is no need to lock yourself into technologies during a prototyping or proof of concept development phase." }, { "code": null, "e": 5229, "s": 4980, "text": "With Flask and Plotly or Plotly Express, you can create powerful dashboards without knowing any JavaScript code. Simply by serializing your plots properly and templating them into your front end with Jinja, you can have an app that is 99.9% Python." } ]
How to get primary key of a table in MySQL?
To get the primary key of a table, you can use the show command. The syntax is as follows βˆ’ SHOW INDEX FROM yourDatebaseName.yourTableName WHERE Key_name = 'PRIMARY'; Suppose, we have a table with two primary keys; one of them is β€œId” and second is β€œRollNum". The query for a table is as follows βˆ’ mysql> create table TwoOrMorePrimary βˆ’> ( βˆ’> Id int, βˆ’> Name varchar(200), βˆ’> RollNum int βˆ’> , βˆ’> Primary key(Id,Age) βˆ’> ); Query OK, 0 rows affected (0.85 sec) Apply the above syntax to get primary key of a table. The query is as follows βˆ’ mysql> SHOW INDEX FROM business.TwoOrMorePrimary βˆ’> WHERE Key_name = 'PRIMARY'; The following is the output βˆ’ +------------------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+---------+------------+ | Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment | Visible | Expression | +------------------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+---------+------------+ | twoormoreprimary | 0 | PRIMARY | 1 | Id | A | 0 | NULL | NULL | | BTREE | | | YES | NULL | | twoormoreprimary | 0 | PRIMARY | 2 | RollNum | A | 0 | NULL | NULL | | BTREE | | | YES | NULL | +------------------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+---------+------------+ 2 rows in set (0.12 sec)
[ { "code": null, "e": 1154, "s": 1062, "text": "To get the primary key of a table, you can use the show command. The syntax is as follows βˆ’" }, { "code": null, "e": 1229, "s": 1154, "text": "SHOW INDEX FROM yourDatebaseName.yourTableName WHERE Key_name = 'PRIMARY';" }, { "code": null, "e": 1360, "s": 1229, "text": "Suppose, we have a table with two primary keys; one of them is β€œId” and second is β€œRollNum\". The query for a table is as follows βˆ’" }, { "code": null, "e": 1543, "s": 1360, "text": "mysql> create table TwoOrMorePrimary\n βˆ’> (\n βˆ’> Id int,\n βˆ’> Name varchar(200), \n βˆ’> RollNum int\n βˆ’> ,\n βˆ’> Primary key(Id,Age)\n βˆ’> );\nQuery OK, 0 rows affected (0.85 sec)" }, { "code": null, "e": 1623, "s": 1543, "text": "Apply the above syntax to get primary key of a table. The query is as follows βˆ’" }, { "code": null, "e": 1703, "s": 1623, "text": "mysql> SHOW INDEX FROM business.TwoOrMorePrimary\nβˆ’> WHERE Key_name = 'PRIMARY';" }, { "code": null, "e": 1733, "s": 1703, "text": "The following is the output βˆ’" }, { "code": null, "e": 2892, "s": 1733, "text": "+------------------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+---------+------------+\n| Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment | Visible | Expression |\n+------------------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+---------+------------+\n| twoormoreprimary | 0 | PRIMARY | 1 | Id | A | 0 | NULL | NULL | | BTREE | | | YES | NULL |\n| twoormoreprimary | 0 | PRIMARY | 2 | RollNum | A | 0 | NULL | NULL | | BTREE | | | YES | NULL |\n+------------------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+---------+------------+\n2 rows in set (0.12 sec)" } ]
Stop making form to reload a page in JavaScript
Let’s say what we need to achieve is when the user submits this HTML form, we handle the submit event on client side and prevent the browser to reload as soon as the form is submitted HTML form <form name="formcontact1" action="#"> <input type='text' name='email' size="36" placeholder="Your e-mail :)"/> <input type="submit" name="submit" value="SUBMIT" onclick="ValidateEmail(document.formcontact1.email)" /> </form> Now, the easiest and the most reliable way of doing so is by tweaking our ValidateEmail() function to include the following line right at the top of its definition βˆ’ function ValidateEmail(event, inputText){ event.preventDefault(); //remaining function logic goes here } What preventDefault() does is that it tells the browser to prevent its default behaviour and let us handle the form submitting event on the client side itself. The full HTML code for this is βˆ’ <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <form name="formcontact1" action="#"> <input type='text' name='email' size="36" placeholder="Your e-mail :)"/> <input type="submit" name="submit" value="SUBMIT" onclick="ValidateEmail(document.formcontact1.email)" /> </form> <script> { function ValidateEmail(event, inputText){ event.preventDefault(); //remaining function logic goes here } } </script> </body> </html>
[ { "code": null, "e": 1246, "s": 1062, "text": "Let’s say what we need to achieve is when the user submits this HTML form, we handle the\nsubmit event on client side and prevent the browser to reload as soon as the form is submitted" }, { "code": null, "e": 1256, "s": 1246, "text": "HTML form" }, { "code": null, "e": 1493, "s": 1256, "text": "<form name=\"formcontact1\" action=\"#\">\n<input\ntype='text'\nname='email'\nsize=\"36\"\nplaceholder=\"Your e-mail :)\"/>\n<input\n type=\"submit\"\n name=\"submit\"\n value=\"SUBMIT\"\n onclick=\"ValidateEmail(document.formcontact1.email)\"\n/>\n</form>" }, { "code": null, "e": 1659, "s": 1493, "text": "Now, the easiest and the most reliable way of doing so is by tweaking our ValidateEmail()\nfunction to include the following line right at the top of its definition βˆ’" }, { "code": null, "e": 1770, "s": 1659, "text": "function ValidateEmail(event, inputText){\n event.preventDefault();\n //remaining function logic goes here\n}" }, { "code": null, "e": 1930, "s": 1770, "text": "What preventDefault() does is that it tells the browser to prevent its default behaviour and let us\nhandle the form submitting event on the client side itself." }, { "code": null, "e": 1963, "s": 1930, "text": "The full HTML code for this is βˆ’" }, { "code": null, "e": 2535, "s": 1963, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n<title>Document</title>\n</head>\n<body>\n<form name=\"formcontact1\" action=\"#\">\n<input\ntype='text'\nname='email'\nsize=\"36\"\nplaceholder=\"Your e-mail :)\"/>\n<input\n type=\"submit\"\n name=\"submit\"\n value=\"SUBMIT\"\n onclick=\"ValidateEmail(document.formcontact1.email)\"\n/>\n</form>\n<script>\n{\n function ValidateEmail(event, inputText){\n event.preventDefault();\n //remaining function logic goes here\n }\n}\n</script>\n</body>\n</html>" } ]
Find combined mean and variance of two series - GeeksforGeeks
11 May, 2021 Given two different series arr1[n] and arr2[m] of size n and m. The task is to find the mean and variance of combined series.Examples : Input : arr1[] = {3, 5, 1, 7, 8, 5} arr2[] = {5, 9, 7, 1, 5, 4, 7, 3} Output : Mean1: 4.83333 mean2: 5.125 StandardDeviation1: 5.47222 StandardDeviation2: 5.60938 Combined Mean: 5 d1_square: 0.0277777 d2_square: 0.015625 Combined Variance: 5.57143 Input : arr1[] = {23, 45, 34, 78, 12, 76, 34} arr2[] = {65, 67, 34, 23, 45} Output : Mean1: 43.1429 mean2: 46.8 StandardDeviation1: 548.694 StandardDeviation2: 294.56 Combined Mean: 44.6667 d1_square: 2.32199 d2_square: 4.55112 Combined Variance: 446.056 Approach: The variance of the combined series is given by Where , and , is the mean of combined series. , are the means and , are the standard deviations of two series. Below is the implementation of above formula: C++ Java Python3 C# PHP Javascript // C++ program to find combined mean// and variance of two series.#include <bits/stdc++.h>using namespace std; // Function to find mean of series.float mean(int arr[], int n){ int sum = 0; for (int i = 0; i < n; i++) sum = sum + arr[i]; float mean = (float)sum / n; return mean;} // Function to find the standard// deviation of series.float sd(int arr[], int n){ float sum = 0; for (int i = 0; i < n; i++) sum = sum + (arr[i] - mean(arr, n)) * (arr[i] - mean(arr, n)); float sdd = sum / n; return sdd;} // Function to find combined variance// of two different series.float combinedVariance(int arr1[], int arr2[], int n, int m){ // mean1 and mean2 are the mean // of two arrays. float mean1 = mean(arr1, n); float mean2 = mean(arr2, m); cout << "Mean1: " << mean1 << " mean2: " << mean2 << endl; // sd1 and sd2 are the standard // deviation of two array. float sd1 = sd(arr1, n); float sd2 = sd(arr2, m); cout << "StandardDeviation1: " << sd1 << " StandardDeviation2: " << sd2 << endl; // combinedMean is variable to store // the combined mean of both array. float combinedMean = (float)(n * mean1 + m * mean2) / (n + m); cout << "Combined Mean: " << combinedMean << endl; // d1_square and d2_square are // the combined mean deviation. float d1_square = (mean1 - combinedMean) * (mean1 - combinedMean); float d2_square = (mean2 - combinedMean) * (mean2 - combinedMean); cout << "d1 square: " << d1_square << " d2_square: " << d2_square << endl; // combinedVar is variable to store // combined variance of both array. float combinedVar = (n * (sd1 + d1_square) + m * (sd2 + d2_square)) / (n + m); return combinedVar;} // Driver function.int main(){ int arr1[] = { 23, 45, 34, 78, 12, 76, 34 }; int arr2[] = { 65, 67, 34, 23, 45 }; int n = sizeof(arr1) / sizeof(arr1[0]); int m = sizeof(arr2) / sizeof(arr2[0]); // Function call to combined mean. cout << "Combined Variance: " << combinedVariance(arr1, arr2, n, m); return 0;} // Java program to find combined mean// and variance of two series. import java.io.*; class GFG { // Function to find mean of series. static float mean(int arr[], int n) { int sum = 0; for (int i = 0; i < n; i++) sum = sum + arr[i]; float mean = (float)sum / n; return mean; } // Function to find the standard // deviation of series. static float sd(int arr[], int n) { float sum = 0; for (int i = 0; i < n; i++) sum = sum + (arr[i] - mean(arr, n)) * (arr[i] - mean(arr, n)); float sdd = sum / n; return sdd; } // Function to find combined variance // of two different series. static float combinedVariance(int arr1[], int arr2[], int n, int m) { // mean1 and mean2 are the mean // of two arrays. float mean1 = mean(arr1, n); float mean2 = mean(arr2, m); System.out.print("Mean1: " + mean1 + " ") ; System.out.println("Mean2: " + mean2) ; // sd1 and sd2 are the standard // deviation of two array. float sd1 = sd(arr1, n); float sd2 = sd(arr2, m); System.out.print("StandardDeviation1: " + sd1 + " ") ; System.out.println("StandardDeviation2: " + sd2 + " "); // combinedMean is variable to store // the combined mean of both array. float combinedMean = (float)(n * mean1 + m * mean2) / (n + m); System.out.println( "Combined Mean: " + combinedMean + " "); // d1_square and d2_square are // the combined mean deviation. float d1_square = (mean1 - combinedMean) * (mean1 - combinedMean); float d2_square = (mean2 - combinedMean) * (mean2 - combinedMean); System.out.print("d1 square: " + d1_square + " " ); System.out.println("d2_square: " + d2_square); // combinedVar is variable to store // combined variance of both array. float combinedVar = (n * (sd1 + d1_square) + m * (sd2 + d2_square)) / (n + m); return combinedVar; } // Driver function. public static void main (String[] args) { int arr1[] = { 23, 45, 34, 78, 12, 76, 34 }; int arr2[] = { 65, 67, 34, 23, 45 }; int n = arr1.length; int m = arr2.length; // Function call to combined mean. System.out.println("Combined Variance: " + combinedVariance(arr1, arr2, n, m)); }} // This code is contributed by vt_m. # Python3 program to find# combined mean and variance# of two series. # Function to find# mean of series.def mean(arr, n): sum = 0; for i in range(n): sum = sum + arr[i]; mean = sum / n; return mean; # Function to find the# standard deviation# of series.def sd(arr, n): sum = 0; for i in range(n): sum = sum + ((arr[i] - mean(arr, n)) * (arr[i] - mean(arr, n))); sdd = sum / n; return sdd; # Function to find combined# variance of two different# series.def combinedVariance(arr1, arr2, n, m): # mean1 and mean2 are # the mean of two arrays. mean1 = mean(arr1, n); mean2 = mean(arr2, m); print("Mean1: ", round(mean1, 2), " mean2: ", round(mean2, 2)); # sd1 and sd2 are the standard # deviation of two array. sd1 = sd(arr1, n); sd2 = sd(arr2, m); print("StandardDeviation1: ", round(sd1, 2), " StandardDeviation2: ", round(sd2, 2)); # combinedMean is variable # to store the combined # mean of both array. combinedMean = (n * mean1 + m * mean2) / (n + m); print("Combined Mean: ", round(combinedMean, 2)); # d1_square and d2_square are # the combined mean deviation. d1_square = ((mean1 - combinedMean) * (mean1 - combinedMean)); d2_square = ((mean2 - combinedMean) * (mean2 - combinedMean)); print("d1 square: ", round(d1_square, 2), " d2_square: ", round(d2_square, 2)); # combinedVar is variable to # store combined variance of # both array. combinedVar = (n * (sd1 + d1_square) + m * (sd2 + d2_square)) / (n + m); print("Combined Variance: ", round(combinedVar, 2)); # Driver Codearr1 = [ 23, 45, 34, 78, 12, 76, 34 ];arr2 = [ 65, 67, 34, 23, 45 ];n = len(arr1);m = len(arr2); # Function call to combined mean.combinedVariance(arr1, arr2, n ,m); # This code is contributed by mits // C# program to find combined mean// and variance of two series.using System; class GFG { // Function to find mean of series. static float mean(int []arr, int n) { int sum = 0; for (int i = 0; i < n; i++) sum = sum + arr[i]; float mean = (float)sum / n; return mean; } // Function to find the standard // deviation of series. static float sd(int []arr, int n) { float sum = 0; for (int i = 0; i < n; i++) sum = sum + (arr[i] - mean(arr, n)) * (arr[i] - mean(arr, n)); float sdd = sum / n; return sdd; } // Function to find combined variance // of two different series. static float combinedVariance(int []arr1, int []arr2, int n, int m) { // mean1 and mean2 are the // mean of two arrays. float mean1 = mean(arr1, n); float mean2 = mean(arr2, m); Console.Write("Mean1: " + mean1 + " ") ; Console.WriteLine("Mean2: " + mean2) ; // sd1 and sd2 are the standard // deviation of two array. float sd1 = sd(arr1, n); float sd2 = sd(arr2, m); Console.Write("StandardDeviation1: " + sd1 + " ") ; Console.WriteLine("StandardDeviation2: " + sd2 + " "); // combinedMean is variable to store // the combined mean of both array. float combinedMean = (float)(n * mean1 + m * mean2) / (n + m); Console.WriteLine("Combined Mean: " + combinedMean + " "); // d1_square and d2_square are // the combined mean deviation. float d1_square = (mean1 - combinedMean) * (mean1 - combinedMean); float d2_square = (mean2 - combinedMean) * (mean2 - combinedMean); Console.Write("d1 square: " + d1_square + " " ); Console.WriteLine("d2_square: " + d2_square); // combinedVar is variable to store // combined variance of both array. float combinedVar = (n * (sd1 + d1_square) + m * (sd2 + d2_square)) / (n + m); return combinedVar; } // Driver codepublic static void Main (){ int []arr1 = {23, 45, 34, 78, 12, 76, 34}; int []arr2 = {65, 67, 34, 23, 45}; int n = arr1.Length; int m = arr2.Length; // Function call to combined mean. Console.WriteLine("Combined Variance: " + combinedVariance(arr1, arr2, n, m)); }} // This code is contributed by vt_m. <?php// PHP program to find combined mean// and variance of two series. // Function to find mean of series.function mean($arr, $n){ $sum = 0; for ($i = 0; $i < $n; $i++) $sum = $sum + $arr[$i]; $mean = (float)($sum / $n); return $mean;} // Function to find the standard// deviation of series.function sd($arr, $n){ $sum = 0; for ($i = 0; $i < $n; $i++) $sum = $sum + ($arr[$i] - mean($arr, $n)) * ($arr[$i] - mean($arr, $n)); $sdd = $sum / $n; return $sdd;} // Function to find combined variance// of two different series.function combinedVariance($arr1, $arr2, $n, $m){ // mean1 and mean2 are the mean // of two arrays. $mean1 = mean($arr1, $n); $mean2 = mean($arr2, $m); echo("Mean1: " . round($mean1, 2) . " " . " mean2: " . round($mean2, 2)); // sd1 and sd2 are the standard // deviation of two array. $sd1 = sd($arr1, $n); $sd2 = sd($arr2, $m); echo("\nStandardDeviation1: " . round($sd1, 2) . " " . " StandardDeviation2: " . round($sd2, 2)); // combinedMean is variable to store // the combined mean of both array. $combinedMean = (float)($n * $mean1 + $m * $mean2) / ($n + $m); echo("\nCombined Mean: " . round($combinedMean, 2)); // d1_square and d2_square are // the combined mean deviation. $d1_square = ($mean1 - $combinedMean) * ($mean1 - $combinedMean); $d2_square = ($mean2 - $combinedMean) * ($mean2 - $combinedMean); echo("\nd1 square: " . round($d1_square, 2) . " " . " d2_square: " . round($d2_square, 2)); // combinedVar is variable to store // combined variance of both array. $combinedVar = ($n * ($sd1 + $d1_square) + $m * ($sd2 + $d2_square)) / ($n + $m); return $combinedVar;} // Driver Code$arr1 = array( 23, 45, 34, 78, 12, 76, 34 );$arr2 = array( 65, 67, 34, 23, 45 );$n = sizeof($arr1);$m = sizeof($arr2); // Function call to combined mean.echo("\nCombined Variance: " . round(combinedVariance($arr1, $arr2, $n, $m), 2)); // This code is contributed by Ajit.?> <script> // JavaScript program to find combined mean// and variance of two series. // Function to find mean of series. function mean(arr, n) { var sum = 0; for (var i = 0; i < n; i++) sum = sum + arr[i]; var mean = sum / n; return mean; } // Function to find the standard // deviation of series. function sd(arr, n) { var sum = 0; for (var i = 0; i < n; i++) sum = sum + (arr[i] - mean(arr, n)) * (arr[i] - mean(arr, n)); var sdd = sum / n; return sdd; } // Function to find combined variance // of two different series. function combinedVariance(arr1,arr2,n,m) { // mean1 and mean2 are the // mean of two arrays. var mean1 = mean(arr1, n); var mean2 = mean(arr2, m); document.write("Mean1: " + mean1.toFixed(4) + " ") ; document.write("Mean2: " + mean2 + "<br>") ; // sd1 and sd2 are the standard // deviation of two array. var sd1 = sd(arr1, n); var sd2 = sd(arr2, m); document.write("StandardDeviation1: " + sd1.toFixed(3) + " ") ; document.write("StandardDeviation2: " + sd2 + " " + "<br>"); // combinedMean is variable to store // the combined mean of both array. var combinedMean = (n * mean1 + m * mean2) / (n + m); document.write("Combined Mean: " + combinedMean.toFixed(4) + " " + "<br>"); // d1_square and d2_square are // the combined mean deviation. var d1_square = (mean1 - combinedMean) * (mean1 - combinedMean); var d2_square = (mean2 - combinedMean) * (mean2 - combinedMean); document.write("d1 square: " + d1_square.toFixed(3) + " " ); document.write("d2_square: " + d2_square.toFixed(4) + "<br>"); // combinedVar is variable to store // combined variance of both array. var combinedVar = (n * (sd1 + d1_square) + m * (sd2 + d2_square)) / (n + m); return combinedVar; } // Driver code var arr1 = [23, 45, 34, 78, 12, 76, 34 ] var arr2 = [65, 67, 34, 23, 45 ] var n = arr1.length; var m = arr2.length; // Function call to combined mean. document.write("Combined Variance: " + combinedVariance(arr1, arr2,n, m).toFixed(3)); </script> Output: Mean1: 43.1429 mean2: 46.8 StandardDeviation1: 548.694 StandardDeviation2: 294.56 Combined Mean: 44.6667 d1 square: 2.322 d2_square: 4.5511 Combined Variance: 446.056 vt_m jit_t Mithun Kumar bunnyram19 statistical-algorithms Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Algorithm to solve Rubik's Cube Program to print prime numbers from 1 to N. Fizz Buzz Implementation Program to multiply two matrices Modular multiplicative inverse Check if a number is Palindrome Count ways to reach the n'th stair Find first and last digits of a number Find Union and Intersection of two unsorted arrays Program to convert a given number to words
[ { "code": null, "e": 24692, "s": 24664, "text": "\n11 May, 2021" }, { "code": null, "e": 24830, "s": 24692, "text": "Given two different series arr1[n] and arr2[m] of size n and m. The task is to find the mean and variance of combined series.Examples : " }, { "code": null, "e": 25472, "s": 24830, "text": "Input : arr1[] = {3, 5, 1, 7, 8, 5}\n arr2[] = {5, 9, 7, 1, 5, 4, 7, 3}\nOutput : Mean1: 4.83333 mean2: 5.125\n StandardDeviation1: 5.47222 \n StandardDeviation2: 5.60938\n Combined Mean: 5\n d1_square: 0.0277777 \n d2_square: 0.015625\n Combined Variance: 5.57143\n\nInput : arr1[] = {23, 45, 34, 78, 12, 76, 34}\n arr2[] = {65, 67, 34, 23, 45}\nOutput : Mean1: 43.1429 mean2: 46.8\n StandardDeviation1: 548.694 \n StandardDeviation2: 294.56\n Combined Mean: 44.6667\n d1_square: 2.32199 \n d2_square: 4.55112\n Combined Variance: 446.056" }, { "code": null, "e": 25691, "s": 25474, "text": "Approach: The variance of the combined series is given by Where , and , is the mean of combined series. , are the means and , are the standard deviations of two series. Below is the implementation of above formula: " }, { "code": null, "e": 25695, "s": 25691, "text": "C++" }, { "code": null, "e": 25700, "s": 25695, "text": "Java" }, { "code": null, "e": 25708, "s": 25700, "text": "Python3" }, { "code": null, "e": 25711, "s": 25708, "text": "C#" }, { "code": null, "e": 25715, "s": 25711, "text": "PHP" }, { "code": null, "e": 25726, "s": 25715, "text": "Javascript" }, { "code": "// C++ program to find combined mean// and variance of two series.#include <bits/stdc++.h>using namespace std; // Function to find mean of series.float mean(int arr[], int n){ int sum = 0; for (int i = 0; i < n; i++) sum = sum + arr[i]; float mean = (float)sum / n; return mean;} // Function to find the standard// deviation of series.float sd(int arr[], int n){ float sum = 0; for (int i = 0; i < n; i++) sum = sum + (arr[i] - mean(arr, n)) * (arr[i] - mean(arr, n)); float sdd = sum / n; return sdd;} // Function to find combined variance// of two different series.float combinedVariance(int arr1[], int arr2[], int n, int m){ // mean1 and mean2 are the mean // of two arrays. float mean1 = mean(arr1, n); float mean2 = mean(arr2, m); cout << \"Mean1: \" << mean1 << \" mean2: \" << mean2 << endl; // sd1 and sd2 are the standard // deviation of two array. float sd1 = sd(arr1, n); float sd2 = sd(arr2, m); cout << \"StandardDeviation1: \" << sd1 << \" StandardDeviation2: \" << sd2 << endl; // combinedMean is variable to store // the combined mean of both array. float combinedMean = (float)(n * mean1 + m * mean2) / (n + m); cout << \"Combined Mean: \" << combinedMean << endl; // d1_square and d2_square are // the combined mean deviation. float d1_square = (mean1 - combinedMean) * (mean1 - combinedMean); float d2_square = (mean2 - combinedMean) * (mean2 - combinedMean); cout << \"d1 square: \" << d1_square << \" d2_square: \" << d2_square << endl; // combinedVar is variable to store // combined variance of both array. float combinedVar = (n * (sd1 + d1_square) + m * (sd2 + d2_square)) / (n + m); return combinedVar;} // Driver function.int main(){ int arr1[] = { 23, 45, 34, 78, 12, 76, 34 }; int arr2[] = { 65, 67, 34, 23, 45 }; int n = sizeof(arr1) / sizeof(arr1[0]); int m = sizeof(arr2) / sizeof(arr2[0]); // Function call to combined mean. cout << \"Combined Variance: \" << combinedVariance(arr1, arr2, n, m); return 0;}", "e": 28006, "s": 25726, "text": null }, { "code": "// Java program to find combined mean// and variance of two series. import java.io.*; class GFG { // Function to find mean of series. static float mean(int arr[], int n) { int sum = 0; for (int i = 0; i < n; i++) sum = sum + arr[i]; float mean = (float)sum / n; return mean; } // Function to find the standard // deviation of series. static float sd(int arr[], int n) { float sum = 0; for (int i = 0; i < n; i++) sum = sum + (arr[i] - mean(arr, n)) * (arr[i] - mean(arr, n)); float sdd = sum / n; return sdd; } // Function to find combined variance // of two different series. static float combinedVariance(int arr1[], int arr2[], int n, int m) { // mean1 and mean2 are the mean // of two arrays. float mean1 = mean(arr1, n); float mean2 = mean(arr2, m); System.out.print(\"Mean1: \" + mean1 + \" \") ; System.out.println(\"Mean2: \" + mean2) ; // sd1 and sd2 are the standard // deviation of two array. float sd1 = sd(arr1, n); float sd2 = sd(arr2, m); System.out.print(\"StandardDeviation1: \" + sd1 + \" \") ; System.out.println(\"StandardDeviation2: \" + sd2 + \" \"); // combinedMean is variable to store // the combined mean of both array. float combinedMean = (float)(n * mean1 + m * mean2) / (n + m); System.out.println( \"Combined Mean: \" + combinedMean + \" \"); // d1_square and d2_square are // the combined mean deviation. float d1_square = (mean1 - combinedMean) * (mean1 - combinedMean); float d2_square = (mean2 - combinedMean) * (mean2 - combinedMean); System.out.print(\"d1 square: \" + d1_square + \" \" ); System.out.println(\"d2_square: \" + d2_square); // combinedVar is variable to store // combined variance of both array. float combinedVar = (n * (sd1 + d1_square) + m * (sd2 + d2_square)) / (n + m); return combinedVar; } // Driver function. public static void main (String[] args) { int arr1[] = { 23, 45, 34, 78, 12, 76, 34 }; int arr2[] = { 65, 67, 34, 23, 45 }; int n = arr1.length; int m = arr2.length; // Function call to combined mean. System.out.println(\"Combined Variance: \" + combinedVariance(arr1, arr2, n, m)); }} // This code is contributed by vt_m.", "e": 30917, "s": 28006, "text": null }, { "code": "# Python3 program to find# combined mean and variance# of two series. # Function to find# mean of series.def mean(arr, n): sum = 0; for i in range(n): sum = sum + arr[i]; mean = sum / n; return mean; # Function to find the# standard deviation# of series.def sd(arr, n): sum = 0; for i in range(n): sum = sum + ((arr[i] - mean(arr, n)) * (arr[i] - mean(arr, n))); sdd = sum / n; return sdd; # Function to find combined# variance of two different# series.def combinedVariance(arr1, arr2, n, m): # mean1 and mean2 are # the mean of two arrays. mean1 = mean(arr1, n); mean2 = mean(arr2, m); print(\"Mean1: \", round(mean1, 2), \" mean2: \", round(mean2, 2)); # sd1 and sd2 are the standard # deviation of two array. sd1 = sd(arr1, n); sd2 = sd(arr2, m); print(\"StandardDeviation1: \", round(sd1, 2), \" StandardDeviation2: \", round(sd2, 2)); # combinedMean is variable # to store the combined # mean of both array. combinedMean = (n * mean1 + m * mean2) / (n + m); print(\"Combined Mean: \", round(combinedMean, 2)); # d1_square and d2_square are # the combined mean deviation. d1_square = ((mean1 - combinedMean) * (mean1 - combinedMean)); d2_square = ((mean2 - combinedMean) * (mean2 - combinedMean)); print(\"d1 square: \", round(d1_square, 2), \" d2_square: \", round(d2_square, 2)); # combinedVar is variable to # store combined variance of # both array. combinedVar = (n * (sd1 + d1_square) + m * (sd2 + d2_square)) / (n + m); print(\"Combined Variance: \", round(combinedVar, 2)); # Driver Codearr1 = [ 23, 45, 34, 78, 12, 76, 34 ];arr2 = [ 65, 67, 34, 23, 45 ];n = len(arr1);m = len(arr2); # Function call to combined mean.combinedVariance(arr1, arr2, n ,m); # This code is contributed by mits", "e": 32883, "s": 30917, "text": null }, { "code": "// C# program to find combined mean// and variance of two series.using System; class GFG { // Function to find mean of series. static float mean(int []arr, int n) { int sum = 0; for (int i = 0; i < n; i++) sum = sum + arr[i]; float mean = (float)sum / n; return mean; } // Function to find the standard // deviation of series. static float sd(int []arr, int n) { float sum = 0; for (int i = 0; i < n; i++) sum = sum + (arr[i] - mean(arr, n)) * (arr[i] - mean(arr, n)); float sdd = sum / n; return sdd; } // Function to find combined variance // of two different series. static float combinedVariance(int []arr1, int []arr2, int n, int m) { // mean1 and mean2 are the // mean of two arrays. float mean1 = mean(arr1, n); float mean2 = mean(arr2, m); Console.Write(\"Mean1: \" + mean1 + \" \") ; Console.WriteLine(\"Mean2: \" + mean2) ; // sd1 and sd2 are the standard // deviation of two array. float sd1 = sd(arr1, n); float sd2 = sd(arr2, m); Console.Write(\"StandardDeviation1: \" + sd1 + \" \") ; Console.WriteLine(\"StandardDeviation2: \" + sd2 + \" \"); // combinedMean is variable to store // the combined mean of both array. float combinedMean = (float)(n * mean1 + m * mean2) / (n + m); Console.WriteLine(\"Combined Mean: \" + combinedMean + \" \"); // d1_square and d2_square are // the combined mean deviation. float d1_square = (mean1 - combinedMean) * (mean1 - combinedMean); float d2_square = (mean2 - combinedMean) * (mean2 - combinedMean); Console.Write(\"d1 square: \" + d1_square + \" \" ); Console.WriteLine(\"d2_square: \" + d2_square); // combinedVar is variable to store // combined variance of both array. float combinedVar = (n * (sd1 + d1_square) + m * (sd2 + d2_square)) / (n + m); return combinedVar; } // Driver codepublic static void Main (){ int []arr1 = {23, 45, 34, 78, 12, 76, 34}; int []arr2 = {65, 67, 34, 23, 45}; int n = arr1.Length; int m = arr2.Length; // Function call to combined mean. Console.WriteLine(\"Combined Variance: \" + combinedVariance(arr1, arr2, n, m)); }} // This code is contributed by vt_m.", "e": 35929, "s": 32883, "text": null }, { "code": "<?php// PHP program to find combined mean// and variance of two series. // Function to find mean of series.function mean($arr, $n){ $sum = 0; for ($i = 0; $i < $n; $i++) $sum = $sum + $arr[$i]; $mean = (float)($sum / $n); return $mean;} // Function to find the standard// deviation of series.function sd($arr, $n){ $sum = 0; for ($i = 0; $i < $n; $i++) $sum = $sum + ($arr[$i] - mean($arr, $n)) * ($arr[$i] - mean($arr, $n)); $sdd = $sum / $n; return $sdd;} // Function to find combined variance// of two different series.function combinedVariance($arr1, $arr2, $n, $m){ // mean1 and mean2 are the mean // of two arrays. $mean1 = mean($arr1, $n); $mean2 = mean($arr2, $m); echo(\"Mean1: \" . round($mean1, 2) . \" \" . \" mean2: \" . round($mean2, 2)); // sd1 and sd2 are the standard // deviation of two array. $sd1 = sd($arr1, $n); $sd2 = sd($arr2, $m); echo(\"\\nStandardDeviation1: \" . round($sd1, 2) . \" \" . \" StandardDeviation2: \" . round($sd2, 2)); // combinedMean is variable to store // the combined mean of both array. $combinedMean = (float)($n * $mean1 + $m * $mean2) / ($n + $m); echo(\"\\nCombined Mean: \" . round($combinedMean, 2)); // d1_square and d2_square are // the combined mean deviation. $d1_square = ($mean1 - $combinedMean) * ($mean1 - $combinedMean); $d2_square = ($mean2 - $combinedMean) * ($mean2 - $combinedMean); echo(\"\\nd1 square: \" . round($d1_square, 2) . \" \" . \" d2_square: \" . round($d2_square, 2)); // combinedVar is variable to store // combined variance of both array. $combinedVar = ($n * ($sd1 + $d1_square) + $m * ($sd2 + $d2_square)) / ($n + $m); return $combinedVar;} // Driver Code$arr1 = array( 23, 45, 34, 78, 12, 76, 34 );$arr2 = array( 65, 67, 34, 23, 45 );$n = sizeof($arr1);$m = sizeof($arr2); // Function call to combined mean.echo(\"\\nCombined Variance: \" . round(combinedVariance($arr1, $arr2, $n, $m), 2)); // This code is contributed by Ajit.?>", "e": 38246, "s": 35929, "text": null }, { "code": "<script> // JavaScript program to find combined mean// and variance of two series. // Function to find mean of series. function mean(arr, n) { var sum = 0; for (var i = 0; i < n; i++) sum = sum + arr[i]; var mean = sum / n; return mean; } // Function to find the standard // deviation of series. function sd(arr, n) { var sum = 0; for (var i = 0; i < n; i++) sum = sum + (arr[i] - mean(arr, n)) * (arr[i] - mean(arr, n)); var sdd = sum / n; return sdd; } // Function to find combined variance // of two different series. function combinedVariance(arr1,arr2,n,m) { // mean1 and mean2 are the // mean of two arrays. var mean1 = mean(arr1, n); var mean2 = mean(arr2, m); document.write(\"Mean1: \" + mean1.toFixed(4) + \" \") ; document.write(\"Mean2: \" + mean2 + \"<br>\") ; // sd1 and sd2 are the standard // deviation of two array. var sd1 = sd(arr1, n); var sd2 = sd(arr2, m); document.write(\"StandardDeviation1: \" + sd1.toFixed(3) + \" \") ; document.write(\"StandardDeviation2: \" + sd2 + \" \" + \"<br>\"); // combinedMean is variable to store // the combined mean of both array. var combinedMean = (n * mean1 + m * mean2) / (n + m); document.write(\"Combined Mean: \" + combinedMean.toFixed(4) + \" \" + \"<br>\"); // d1_square and d2_square are // the combined mean deviation. var d1_square = (mean1 - combinedMean) * (mean1 - combinedMean); var d2_square = (mean2 - combinedMean) * (mean2 - combinedMean); document.write(\"d1 square: \" + d1_square.toFixed(3) + \" \" ); document.write(\"d2_square: \" + d2_square.toFixed(4) + \"<br>\"); // combinedVar is variable to store // combined variance of both array. var combinedVar = (n * (sd1 + d1_square) + m * (sd2 + d2_square)) / (n + m); return combinedVar; } // Driver code var arr1 = [23, 45, 34, 78, 12, 76, 34 ] var arr2 = [65, 67, 34, 23, 45 ] var n = arr1.length; var m = arr2.length; // Function call to combined mean. document.write(\"Combined Variance: \" + combinedVariance(arr1, arr2,n, m).toFixed(3)); </script> ", "e": 40920, "s": 38246, "text": null }, { "code": null, "e": 40930, "s": 40920, "text": "Output: " }, { "code": null, "e": 41097, "s": 40930, "text": "Mean1: 43.1429 mean2: 46.8\nStandardDeviation1: 548.694 StandardDeviation2: 294.56\nCombined Mean: 44.6667\nd1 square: 2.322 d2_square: 4.5511\nCombined Variance: 446.056" }, { "code": null, "e": 41104, "s": 41099, "text": "vt_m" }, { "code": null, "e": 41110, "s": 41104, "text": "jit_t" }, { "code": null, "e": 41123, "s": 41110, "text": "Mithun Kumar" }, { "code": null, "e": 41134, "s": 41123, "text": "bunnyram19" }, { "code": null, "e": 41157, "s": 41134, "text": "statistical-algorithms" }, { "code": null, "e": 41170, "s": 41157, "text": "Mathematical" }, { "code": null, "e": 41183, "s": 41170, "text": "Mathematical" }, { "code": null, "e": 41281, "s": 41183, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 41313, "s": 41281, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 41357, "s": 41313, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 41382, "s": 41357, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 41415, "s": 41382, "text": "Program to multiply two matrices" }, { "code": null, "e": 41446, "s": 41415, "text": "Modular multiplicative inverse" }, { "code": null, "e": 41478, "s": 41446, "text": "Check if a number is Palindrome" }, { "code": null, "e": 41513, "s": 41478, "text": "Count ways to reach the n'th stair" }, { "code": null, "e": 41552, "s": 41513, "text": "Find first and last digits of a number" }, { "code": null, "e": 41603, "s": 41552, "text": "Find Union and Intersection of two unsorted arrays" } ]
Spring - Bean Life Cycle
The life cycle of a Spring bean is easy to understand. When a bean is instantiated, it may be required to perform some initialization to get it into a usable state. Similarly, when the bean is no longer required and is removed from the container, some cleanup may be required. Though, there are lists of the activities that take place behind the scene between the time of bean Instantiation and its destruction, this chapter will discuss only two important bean life cycle callback methods, which are required at the time of bean initialization and its destruction. To define setup and teardown for a bean, we simply declare the <bean> with initmethod and/or destroy-method parameters. The init-method attribute specifies a method that is to be called on the bean immediately upon instantiation. Similarly, destroymethod specifies a method that is called just before a bean is removed from the container. The org.springframework.beans.factory.InitializingBean interface specifies a single method βˆ’ void afterPropertiesSet() throws Exception; Thus, you can simply implement the above interface and initialization work can be done inside afterPropertiesSet() method as follows βˆ’ public class ExampleBean implements InitializingBean { public void afterPropertiesSet() { // do some initialization work } } In the case of XML-based configuration metadata, you can use the init-method attribute to specify the name of the method that has a void no-argument signature. For example βˆ’ <bean id = "exampleBean" class = "examples.ExampleBean" init-method = "init"/> Following is the class definition βˆ’ public class ExampleBean { public void init() { // do some initialization work } } The org.springframework.beans.factory.DisposableBean interface specifies a single method βˆ’ void destroy() throws Exception; Thus, you can simply implement the above interface and finalization work can be done inside destroy() method as follows βˆ’ public class ExampleBean implements DisposableBean { public void destroy() { // do some destruction work } } In the case of XML-based configuration metadata, you can use the destroy-method attribute to specify the name of the method that has a void no-argument signature. For example βˆ’ <bean id = "exampleBean" class = "examples.ExampleBean" destroy-method = "destroy"/> Following is the class definition βˆ’ public class ExampleBean { public void destroy() { // do some destruction work } } If you are using Spring's IoC container in a non-web application environment; for example, in a rich client desktop environment, you register a shutdown hook with the JVM. Doing so ensures a graceful shutdown and calls the relevant destroy methods on your singleton beans so that all resources are released. It is recommended that you do not use the InitializingBean or DisposableBean callbacks, because XML configuration gives much flexibility in terms of naming your method. Let us have a working Eclipse IDE in place and take the following steps to create a Spring application βˆ’ Here is the content of HelloWorld.java file βˆ’ package com.tutorialspoint; public class HelloWorld { private String message; public void setMessage(String message){ this.message = message; } public void getMessage(){ System.out.println("Your Message : " + message); } public void init(){ System.out.println("Bean is going through init."); } public void destroy() { System.out.println("Bean will destroy now."); } } Following is the content of the MainApp.java file. Here you need to register a shutdown hook registerShutdownHook() method that is declared on the AbstractApplicationContext class. This will ensure a graceful shutdown and call the relevant destroy methods. package com.tutorialspoint; import org.springframework.context.support.AbstractApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MainApp { public static void main(String[] args) { AbstractApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml"); HelloWorld obj = (HelloWorld) context.getBean("helloWorld"); obj.getMessage(); context.registerShutdownHook(); } } Following is the configuration file Beans.xml required for init and destroy methods βˆ’ <?xml version = "1.0" encoding = "UTF-8"?> <beans xmlns = "http://www.springframework.org/schema/beans" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id = "helloWorld" class = "com.tutorialspoint.HelloWorld" init-method = "init" destroy-method = "destroy"> <property name = "message" value = "Hello World!"/> </bean> </beans> Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message βˆ’ Bean is going through init. Your Message : Hello World! Bean will destroy now. If you have too many beans having initialization and/or destroy methods with the same name, you don't need to declare init-method and destroy-method on each individual bean. Instead, the framework provides the flexibility to configure such situation using default-init-method and default-destroy-method attributes on the <beans> element as follows βˆ’ <beans xmlns = "http://www.springframework.org/schema/beans" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd" default-init-method = "init" default-destroy-method = "destroy"> <bean id = "..." class = "..."> <!-- collaborators and configuration for this bean go here --> </bean> </beans> 102 Lectures 8 hours Karthikeya T 39 Lectures 5 hours Chaand Sheikh 73 Lectures 5.5 hours Senol Atac 62 Lectures 4.5 hours Senol Atac 67 Lectures 4.5 hours Senol Atac 69 Lectures 5 hours Senol Atac Print Add Notes Bookmark this page
[ { "code": null, "e": 2569, "s": 2292, "text": "The life cycle of a Spring bean is easy to understand. When a bean is instantiated, it may be required to perform some initialization to get it into a usable state. Similarly, when the bean is no longer required and is removed from the container, some cleanup may be required." }, { "code": null, "e": 2858, "s": 2569, "text": "Though, there are lists of the activities that take place behind the scene between the time of bean Instantiation and its destruction, this chapter will discuss only two important bean life cycle callback methods, which are required at the time of bean initialization and its destruction." }, { "code": null, "e": 3197, "s": 2858, "text": "To define setup and teardown for a bean, we simply declare the <bean> with initmethod and/or destroy-method parameters. The init-method attribute specifies a method that is to be called on the bean immediately upon instantiation. Similarly, destroymethod specifies a method that is called just before a bean is removed from the container." }, { "code": null, "e": 3290, "s": 3197, "text": "The org.springframework.beans.factory.InitializingBean interface specifies a single method βˆ’" }, { "code": null, "e": 3335, "s": 3290, "text": "void afterPropertiesSet() throws Exception;\n" }, { "code": null, "e": 3470, "s": 3335, "text": "Thus, you can simply implement the above interface and initialization work can be done inside afterPropertiesSet() method as follows βˆ’" }, { "code": null, "e": 3607, "s": 3470, "text": "public class ExampleBean implements InitializingBean {\n public void afterPropertiesSet() {\n // do some initialization work\n }\n}" }, { "code": null, "e": 3781, "s": 3607, "text": "In the case of XML-based configuration metadata, you can use the init-method attribute to specify the name of the method that has a void no-argument signature. For example βˆ’" }, { "code": null, "e": 3861, "s": 3781, "text": "<bean id = \"exampleBean\" class = \"examples.ExampleBean\" init-method = \"init\"/>\n" }, { "code": null, "e": 3897, "s": 3861, "text": "Following is the class definition βˆ’" }, { "code": null, "e": 3992, "s": 3897, "text": "public class ExampleBean {\n public void init() {\n // do some initialization work\n }\n}" }, { "code": null, "e": 4083, "s": 3992, "text": "The org.springframework.beans.factory.DisposableBean interface specifies a single method βˆ’" }, { "code": null, "e": 4117, "s": 4083, "text": "void destroy() throws Exception;\n" }, { "code": null, "e": 4239, "s": 4117, "text": "Thus, you can simply implement the above interface and finalization work can be done inside destroy() method as follows βˆ’" }, { "code": null, "e": 4360, "s": 4239, "text": "public class ExampleBean implements DisposableBean {\n public void destroy() {\n // do some destruction work\n }\n}" }, { "code": null, "e": 4537, "s": 4360, "text": "In the case of XML-based configuration metadata, you can use the destroy-method attribute to specify the name of the method that has a void no-argument signature. For example βˆ’" }, { "code": null, "e": 4623, "s": 4537, "text": "<bean id = \"exampleBean\" class = \"examples.ExampleBean\" destroy-method = \"destroy\"/>\n" }, { "code": null, "e": 4659, "s": 4623, "text": "Following is the class definition βˆ’" }, { "code": null, "e": 4754, "s": 4659, "text": "public class ExampleBean {\n public void destroy() {\n // do some destruction work\n }\n}" }, { "code": null, "e": 5062, "s": 4754, "text": "If you are using Spring's IoC container in a non-web application environment; for example, in a rich client desktop environment, you register a shutdown hook with the JVM. Doing so ensures a graceful shutdown and calls the relevant destroy methods on your singleton beans so that all resources are released." }, { "code": null, "e": 5231, "s": 5062, "text": "It is recommended that you do not use the InitializingBean or DisposableBean callbacks, because XML configuration gives much flexibility in terms of naming your method." }, { "code": null, "e": 5336, "s": 5231, "text": "Let us have a working Eclipse IDE in place and take the following steps to create a Spring application βˆ’" }, { "code": null, "e": 5382, "s": 5336, "text": "Here is the content of HelloWorld.java file βˆ’" }, { "code": null, "e": 5803, "s": 5382, "text": "package com.tutorialspoint;\n\npublic class HelloWorld {\n private String message;\n\n public void setMessage(String message){\n this.message = message;\n }\n public void getMessage(){\n System.out.println(\"Your Message : \" + message);\n }\n public void init(){\n System.out.println(\"Bean is going through init.\");\n }\n public void destroy() {\n System.out.println(\"Bean will destroy now.\");\n }\n}" }, { "code": null, "e": 6060, "s": 5803, "text": "Following is the content of the MainApp.java file. Here you need to register a shutdown hook registerShutdownHook() method that is declared on the AbstractApplicationContext class. This will ensure a graceful shutdown and call the relevant destroy methods." }, { "code": null, "e": 6532, "s": 6060, "text": "package com.tutorialspoint;\n\nimport org.springframework.context.support.AbstractApplicationContext;\nimport org.springframework.context.support.ClassPathXmlApplicationContext;\n\npublic class MainApp {\n public static void main(String[] args) {\n AbstractApplicationContext context = new ClassPathXmlApplicationContext(\"Beans.xml\");\n\n HelloWorld obj = (HelloWorld) context.getBean(\"helloWorld\");\n obj.getMessage();\n context.registerShutdownHook();\n }\n}" }, { "code": null, "e": 6618, "s": 6532, "text": "Following is the configuration file Beans.xml required for init and destroy methods βˆ’" }, { "code": null, "e": 7124, "s": 6618, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n\n<beans xmlns = \"http://www.springframework.org/schema/beans\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://www.springframework.org/schema/beans\n http://www.springframework.org/schema/beans/spring-beans-3.0.xsd\">\n\n <bean id = \"helloWorld\" class = \"com.tutorialspoint.HelloWorld\" init-method = \"init\" \n destroy-method = \"destroy\">\n <property name = \"message\" value = \"Hello World!\"/>\n </bean>\n\n</beans>" }, { "code": null, "e": 7303, "s": 7124, "text": "Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message βˆ’" }, { "code": null, "e": 7383, "s": 7303, "text": "Bean is going through init.\nYour Message : Hello World!\nBean will destroy now.\n" }, { "code": null, "e": 7733, "s": 7383, "text": "If you have too many beans having initialization and/or destroy methods with the same name, you don't need to declare init-method and destroy-method on each individual bean. Instead, the framework provides the flexibility to configure such situation using default-init-method and default-destroy-method attributes on the <beans> element as follows βˆ’" }, { "code": null, "e": 8192, "s": 7733, "text": "<beans xmlns = \"http://www.springframework.org/schema/beans\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://www.springframework.org/schema/beans\n http://www.springframework.org/schema/beans/spring-beans-3.0.xsd\"\n default-init-method = \"init\" \n default-destroy-method = \"destroy\">\n\n <bean id = \"...\" class = \"...\">\n <!-- collaborators and configuration for this bean go here -->\n </bean>\n \n</beans>" }, { "code": null, "e": 8226, "s": 8192, "text": "\n 102 Lectures \n 8 hours \n" }, { "code": null, "e": 8240, "s": 8226, "text": " Karthikeya T" }, { "code": null, "e": 8273, "s": 8240, "text": "\n 39 Lectures \n 5 hours \n" }, { "code": null, "e": 8288, "s": 8273, "text": " Chaand Sheikh" }, { "code": null, "e": 8323, "s": 8288, "text": "\n 73 Lectures \n 5.5 hours \n" }, { "code": null, "e": 8335, "s": 8323, "text": " Senol Atac" }, { "code": null, "e": 8370, "s": 8335, "text": "\n 62 Lectures \n 4.5 hours \n" }, { "code": null, "e": 8382, "s": 8370, "text": " Senol Atac" }, { "code": null, "e": 8417, "s": 8382, "text": "\n 67 Lectures \n 4.5 hours \n" }, { "code": null, "e": 8429, "s": 8417, "text": " Senol Atac" }, { "code": null, "e": 8462, "s": 8429, "text": "\n 69 Lectures \n 5 hours \n" }, { "code": null, "e": 8474, "s": 8462, "text": " Senol Atac" }, { "code": null, "e": 8481, "s": 8474, "text": " Print" }, { "code": null, "e": 8492, "s": 8481, "text": " Add Notes" } ]
F# - Basic I/O
Basic Input Output includes βˆ’ Reading from and writing into console. Reading from and writing into file. We have used the printf and the printfn functions for writing into the console. In this section, we will look into the details of the Printf module of F#. Apart from the above functions, the Core.Printf module of F# has various other methods for printing and formatting using % markers as placeholders. The following table shows the methods with brief description βˆ’ Format specifications are used for formatting the input or output, according to the programmers’ need. These are strings with % markers indicating format placeholders. The syntax of a Format placeholders is βˆ’ %[flags][width][.precision][type] The type is interpreted as βˆ’ A general format specifier, requires two arguments. The first argument is a function which accepts two arguments: first, a context parameter of the appropriate type for the given formatting function (for example, a TextWriter), and second, a value to print and which either outputs or returns appropriate text. The second argument is the particular value to print. The width is an optional parameter. It is an integer that indicates the minimal width of the result. For example, %5d prints an integer with at least spaces of 5 characters. Valid flags are described in the following table βˆ’ printf "Hello " printf "World" printfn "" printfn "Hello " printfn "World" printf "Hi, I'm %s and I'm a %s" "Rohit" "Medical Student" printfn "d: %f" 212.098f printfn "e: %f" 504.768f printfn "x: %g" 212.098f printfn "y: %g" 504.768f printfn "x: %e" 212.098f printfn "y: %e" 504.768f printfn "True: %b" true When you compile and execute the program, it yields the following output βˆ’ Hello World Hello World Hi, I'm Rohit and I'm a Medical Studentd: 212.098000 e: 504.768000 x: 212.098 y: 504.768 x: 2.120980e+002 y: 5.047680e+002 True: true This class is a part of the .NET framework. It represents the standard input, output, and error streams for console applications. It provides various methods for reading from and writing into the console. The following table shows the methods βˆ’ The following example demonstrates reading from console and writing into it βˆ’ open System let main() = Console.Write("What's your name? ") let name = Console.ReadLine() Console.Write("Hello, {0}\n", name) Console.WriteLine(System.String.Format("Big Greetings from {0} and {1}", "TutorialsPoint", "Absoulte Classes")) Console.WriteLine(System.String.Format("|{0:yyyy-MMM-dd}|", System.DateTime.Now)) main() When you compile and execute the program, it yields the following output βˆ’ What's your name? Kabir Hello, Kabir Big Greetings from TutorialsPoint and Absoulte Classes |2015-Jan-05| The System.IO namespace contains a variety of useful classes for performing basic I/O. It contains types or classes that allow reading and writing to files and data streams and types that provide basic file and directory support. Classes useful for working with the file system βˆ’ The System.IO.File class is used for creating, appending, and deleting files. System.IO.Directory class is used for creating, moving, and deleting directories. System.IO.Path class performs operations on strings, which represent file paths. System.IO.FileSystemWatcher class allows users to listen to a directory for changes. Classes useful for working with the streams (sequence of bytes) βˆ’ System.IO.StreamReader class is used to read characters from a stream. System.IO.StreamWriter class is used to write characters to a stream. System.IO.MemoryStream class creates an in-memory stream of bytes. The following table shows all the classes provided in the namespace along with a brief description βˆ’ The following example creates a file called test.txt, writes a message there, reads the text from the file and prints it on the console. Note βˆ’ The amount of code needed to do this is surprisingly less! open System.IO // Name spaces can be opened just as modules File.WriteAllText("test.txt", "Hello There\n Welcome to:\n Tutorials Point") let msg = File.ReadAllText("test.txt") printfn "%s" msg When you compile and execute the program, it yields the following output βˆ’ Hello There Welcome to: Tutorials Point Print Add Notes Bookmark this page
[ { "code": null, "e": 2191, "s": 2161, "text": "Basic Input Output includes βˆ’" }, { "code": null, "e": 2230, "s": 2191, "text": "Reading from and writing into console." }, { "code": null, "e": 2266, "s": 2230, "text": "Reading from and writing into file." }, { "code": null, "e": 2421, "s": 2266, "text": "We have used the printf and the printfn functions for writing into the console. In this section, we will look into the details of the Printf module of F#." }, { "code": null, "e": 2632, "s": 2421, "text": "Apart from the above functions, the Core.Printf module of F# has various other methods for printing and formatting using % markers as placeholders. The following table shows the methods with brief description βˆ’" }, { "code": null, "e": 2735, "s": 2632, "text": "Format specifications are used for formatting the input or output, according to the programmers’ need." }, { "code": null, "e": 2800, "s": 2735, "text": "These are strings with % markers indicating format placeholders." }, { "code": null, "e": 2841, "s": 2800, "text": "The syntax of a Format placeholders is βˆ’" }, { "code": null, "e": 2876, "s": 2841, "text": "%[flags][width][.precision][type]\n" }, { "code": null, "e": 2905, "s": 2876, "text": "The type is interpreted as βˆ’" }, { "code": null, "e": 3216, "s": 2905, "text": "A general format specifier, requires two arguments. The first argument is a function which accepts two arguments: first, a context parameter of the appropriate type for the given formatting function (for example, a TextWriter), and second, a value to print and which either outputs or returns appropriate text." }, { "code": null, "e": 3270, "s": 3216, "text": "The second argument is the particular value to print." }, { "code": null, "e": 3444, "s": 3270, "text": "The width is an optional parameter. It is an integer that indicates the minimal width of the result. For example, %5d prints an integer with at least spaces of 5 characters." }, { "code": null, "e": 3495, "s": 3444, "text": "Valid flags are described in the following table βˆ’" }, { "code": null, "e": 3806, "s": 3495, "text": "printf \"Hello \"\nprintf \"World\"\nprintfn \"\"\nprintfn \"Hello \"\nprintfn \"World\"\nprintf \"Hi, I'm %s and I'm a %s\" \"Rohit\" \"Medical Student\"\n\nprintfn \"d: %f\" 212.098f\nprintfn \"e: %f\" 504.768f\n\nprintfn \"x: %g\" 212.098f\nprintfn \"y: %g\" 504.768f\n\nprintfn \"x: %e\" 212.098f\nprintfn \"y: %e\" 504.768f\nprintfn \"True: %b\" true" }, { "code": null, "e": 3881, "s": 3806, "text": "When you compile and execute the program, it yields the following output βˆ’" }, { "code": null, "e": 4040, "s": 3881, "text": "Hello World\nHello\nWorld\nHi, I'm Rohit and I'm a Medical Studentd: 212.098000\ne: 504.768000\nx: 212.098\ny: 504.768\nx: 2.120980e+002\ny: 5.047680e+002\nTrue: true\n" }, { "code": null, "e": 4170, "s": 4040, "text": "This class is a part of the .NET framework. It represents the standard input, output, and error streams for console applications." }, { "code": null, "e": 4285, "s": 4170, "text": "It provides various methods for reading from and writing into the console. The following table shows the methods βˆ’" }, { "code": null, "e": 4363, "s": 4285, "text": "The following example demonstrates reading from console and writing into it βˆ’" }, { "code": null, "e": 4706, "s": 4363, "text": "open System\nlet main() =\n Console.Write(\"What's your name? \")\n let name = Console.ReadLine()\n Console.Write(\"Hello, {0}\\n\", name)\n Console.WriteLine(System.String.Format(\"Big Greetings from {0} and {1}\", \"TutorialsPoint\", \"Absoulte Classes\"))\n Console.WriteLine(System.String.Format(\"|{0:yyyy-MMM-dd}|\", System.DateTime.Now))\nmain()" }, { "code": null, "e": 4781, "s": 4706, "text": "When you compile and execute the program, it yields the following output βˆ’" }, { "code": null, "e": 4888, "s": 4781, "text": "What's your name? Kabir\nHello, Kabir\nBig Greetings from TutorialsPoint and Absoulte Classes\n|2015-Jan-05|\n" }, { "code": null, "e": 4975, "s": 4888, "text": "The System.IO namespace contains a variety of useful classes for performing basic I/O." }, { "code": null, "e": 5118, "s": 4975, "text": "It contains types or classes that allow reading and writing to files and data streams and types that provide basic file and directory support." }, { "code": null, "e": 5168, "s": 5118, "text": "Classes useful for working with the file system βˆ’" }, { "code": null, "e": 5246, "s": 5168, "text": "The System.IO.File class is used for creating, appending, and deleting files." }, { "code": null, "e": 5328, "s": 5246, "text": "System.IO.Directory class is used for creating, moving, and deleting directories." }, { "code": null, "e": 5409, "s": 5328, "text": "System.IO.Path class performs operations on strings, which represent file paths." }, { "code": null, "e": 5494, "s": 5409, "text": "System.IO.FileSystemWatcher class allows users to listen to a directory for changes." }, { "code": null, "e": 5560, "s": 5494, "text": "Classes useful for working with the streams (sequence of bytes) βˆ’" }, { "code": null, "e": 5631, "s": 5560, "text": "System.IO.StreamReader class is used to read characters from a stream." }, { "code": null, "e": 5701, "s": 5631, "text": "System.IO.StreamWriter class is used to write characters to a stream." }, { "code": null, "e": 5768, "s": 5701, "text": "System.IO.MemoryStream class creates an in-memory stream of bytes." }, { "code": null, "e": 5869, "s": 5768, "text": "The following table shows all the classes provided in the namespace along with a brief description βˆ’" }, { "code": null, "e": 6006, "s": 5869, "text": "The following example creates a file called test.txt, writes a message there, reads the text from the file and prints it on the console." }, { "code": null, "e": 6073, "s": 6006, "text": "Note βˆ’ The amount of code needed to do this is surprisingly less!" }, { "code": null, "e": 6266, "s": 6073, "text": "open System.IO // Name spaces can be opened just as modules\nFile.WriteAllText(\"test.txt\", \"Hello There\\n Welcome to:\\n Tutorials Point\")\nlet msg = File.ReadAllText(\"test.txt\")\nprintfn \"%s\" msg" }, { "code": null, "e": 6341, "s": 6266, "text": "When you compile and execute the program, it yields the following output βˆ’" }, { "code": null, "e": 6382, "s": 6341, "text": "Hello There\nWelcome to:\nTutorials Point\n" }, { "code": null, "e": 6389, "s": 6382, "text": " Print" }, { "code": null, "e": 6400, "s": 6389, "text": " Add Notes" } ]
Clone() method in C#
The Clone() method in C# is used to create a similar copy of the array. Let us see an example to clone an array using the Clone() method βˆ’ Live Demo using System; class Program { static void Main() { string[] arr = { "one", "two", "three", "four", "five" }; string[] arrCloned = arr.Clone() as string[]; Console.WriteLine(string.Join(",", arr)); // cloned array Console.WriteLine(string.Join(",", arrCloned)); Console.WriteLine(); } } one,two,three,four,five one,two,three,four,five Above, we have a string array βˆ’ string[] arr = { "one", "two", "three", "four", "five" }; With that, in a new string array, we have used the Clone() method with the as operator to clone the array βˆ’ string[] arrCloned = arr.Clone() as string[];
[ { "code": null, "e": 1134, "s": 1062, "text": "The Clone() method in C# is used to create a similar copy of the array." }, { "code": null, "e": 1201, "s": 1134, "text": "Let us see an example to clone an array using the Clone() method βˆ’" }, { "code": null, "e": 1212, "s": 1201, "text": " Live Demo" }, { "code": null, "e": 1540, "s": 1212, "text": "using System;\nclass Program {\n static void Main() {\n string[] arr = { \"one\", \"two\", \"three\", \"four\", \"five\" };\n string[] arrCloned = arr.Clone() as string[];\n Console.WriteLine(string.Join(\",\", arr));\n // cloned array\n Console.WriteLine(string.Join(\",\", arrCloned));\n Console.WriteLine();\n }\n}" }, { "code": null, "e": 1588, "s": 1540, "text": "one,two,three,four,five\none,two,three,four,five" }, { "code": null, "e": 1620, "s": 1588, "text": "Above, we have a string array βˆ’" }, { "code": null, "e": 1678, "s": 1620, "text": "string[] arr = { \"one\", \"two\", \"three\", \"four\", \"five\" };" }, { "code": null, "e": 1786, "s": 1678, "text": "With that, in a new string array, we have used the Clone() method with the as operator to clone the array βˆ’" }, { "code": null, "e": 1832, "s": 1786, "text": "string[] arrCloned = arr.Clone() as string[];" } ]
Shifting values of rows in MySQL to change the existing id values for existing rows?
Let us first create a table βˆ’ mysql> create table DemoTable -> ( -> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> StudentName varchar(20) -> ); Query OK, 0 rows affected (1.07 sec) Insert some records in the table using insert command βˆ’ mysql> insert into DemoTable(StudentName) values('Chris'); Query OK, 1 row affected (0.23 sec) mysql> insert into DemoTable(StudentName) values('Robert'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable(StudentName) values('David'); Query OK, 1 row affected (0.18 sec) mysql> insert into DemoTable(StudentName) values('Mike'); Query OK, 1 row affected (0.10 sec) Display all records from the table using select statement βˆ’ mysql> select *from DemoTable; This will produce the following output βˆ’ +-----------+-------------+ | StudentId | StudentName | +-----------+-------------+ | 1 | Chris | | 2 | Robert | | 3 | David | | 4 | Mike | +-----------+-------------+ 4 rows in set (0.00 sec) Here is the query to shift id values of existing rows in MySQL βˆ’ mysql> update DemoTable set StudentId=StudentId+1000; Query OK, 4 rows affected (0.18 sec) Rows matched: 4 Changed: 4 Warnings: 0 Let us check the table records once again βˆ’ mysql> select *from DemoTable; This will produce the following output βˆ’ +-----------+-------------+ | StudentId | StudentName | +-----------+-------------+ | 1001 | Chris | | 1002 | Robert | | 1003 | David | | 1004 | Mike | +-----------+-------------+ 4 rows in set (0.00 sec)
[ { "code": null, "e": 1092, "s": 1062, "text": "Let us first create a table βˆ’" }, { "code": null, "e": 1263, "s": 1092, "text": "mysql> create table DemoTable\n -> (\n -> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n -> StudentName varchar(20)\n -> );\nQuery OK, 0 rows affected (1.07 sec)" }, { "code": null, "e": 1319, "s": 1263, "text": "Insert some records in the table using insert command βˆ’" }, { "code": null, "e": 1699, "s": 1319, "text": "mysql> insert into DemoTable(StudentName) values('Chris');\nQuery OK, 1 row affected (0.23 sec)\nmysql> insert into DemoTable(StudentName) values('Robert');\nQuery OK, 1 row affected (0.12 sec)\nmysql> insert into DemoTable(StudentName) values('David');\nQuery OK, 1 row affected (0.18 sec)\nmysql> insert into DemoTable(StudentName) values('Mike');\nQuery OK, 1 row affected (0.10 sec)" }, { "code": null, "e": 1759, "s": 1699, "text": "Display all records from the table using select statement βˆ’" }, { "code": null, "e": 1790, "s": 1759, "text": "mysql> select *from DemoTable;" }, { "code": null, "e": 1831, "s": 1790, "text": "This will produce the following output βˆ’" }, { "code": null, "e": 2080, "s": 1831, "text": "+-----------+-------------+\n| StudentId | StudentName |\n+-----------+-------------+\n| 1 | Chris |\n| 2 | Robert |\n| 3 | David |\n| 4 | Mike |\n+-----------+-------------+\n4 rows in set (0.00 sec)" }, { "code": null, "e": 2145, "s": 2080, "text": "Here is the query to shift id values of existing rows in MySQL βˆ’" }, { "code": null, "e": 2275, "s": 2145, "text": "mysql> update DemoTable set StudentId=StudentId+1000;\nQuery OK, 4 rows affected (0.18 sec)\nRows matched: 4 Changed: 4 Warnings: 0" }, { "code": null, "e": 2319, "s": 2275, "text": "Let us check the table records once again βˆ’" }, { "code": null, "e": 2350, "s": 2319, "text": "mysql> select *from DemoTable;" }, { "code": null, "e": 2391, "s": 2350, "text": "This will produce the following output βˆ’" }, { "code": null, "e": 2640, "s": 2391, "text": "+-----------+-------------+\n| StudentId | StudentName |\n+-----------+-------------+\n| 1001 | Chris |\n| 1002 | Robert |\n| 1003 | David |\n| 1004 | Mike |\n+-----------+-------------+\n4 rows in set (0.00 sec)" } ]
Comparison of the Logistic Regression, Decision Tree, and Random Forest Models to Predict Red Wine Quality in R | by Claudia Cartaya | Towards Data Science
In the following project, I applied three different machine learning algorithms to predict the quality of a wine. The dataset I used for the project is called Wine Quality Data Set (specifically the β€œwinequality-red.csv” file), taken from the UCI Machine Learning Repository. The dataset contains 1,599 observations and 12 attributes related to the red variants of the Portuguese β€œVinho Verde” wine. Each row describes the physicochemical properties of one bottle of wine. The first 11 independent variables display numeric information about these characteristics, and the last dependent variable revels the quality of the wine on a scale from 0 (bad quality wine) to 10 (good quality wine) based on sensory data. Since the outcome variable is ordinal, I chose logistic regression, decision trees, and random forest classification algorithms to answer the following questions: Which machine learning algorithm will enable the most accurate prediction of wine quality from its physicochemical properties?What physicochemical properties of red wine have the highest impact on its quality? Which machine learning algorithm will enable the most accurate prediction of wine quality from its physicochemical properties? What physicochemical properties of red wine have the highest impact on its quality? For the following project, I used the R programming language to explore, prepare, and model the data. Once the working directory is set and the dataset is download into our computer, I imported the data. #Importing the datasetdata <- read.csv('winequality-red.csv', sep = ';')str(data) With the str() function, we could see that all the variable types are numerical, which is the correct format except the outcome variable. I proceed to transform the dependent variable into a binary categorical response. #Format outcome variabledata$quality <- ifelse(data$quality >= 7, 1, 0)data$quality <- factor(data$quality, levels = c(0, 1)) The arbitrary criteria I selected to modify the levels of the outcome variable is as follows: Values above or equal to seven will be changed to 1, meaning a good quality wine.On the other hand, amounts less than seven will be converted to 0 and will indicate bad or mediocre quality. Values above or equal to seven will be changed to 1, meaning a good quality wine. On the other hand, amounts less than seven will be converted to 0 and will indicate bad or mediocre quality. Furthermore, I modified the type of the variable β€œquality” to factor, indicating that the variable is categorical. Now, I proceed to develop an EDA on the data to find essential insights and to determine specific relationships between the variables. First, I developed a descriptive analysis where I collected the five-number summary statistics of the data by using the summary() function. #Descriptive statisticssummary(data) The image shows the five-number summary values of each of the variables in the data. In other words, with the function, I obtained the minimum and maximum, the 1st and 3rd quartile, the mean, and the median values of the numerical variables. Additionally, the summary shows the frequency of the level of the dependent variable. Next, I developed a univariate analysis, which consists of examining each of the variables separately. First, I analyzed the dependent variable. To analyze the outcome variable, I developed a bar plot to visualize the frequency count of the categorical levels. Also, I generated a table of frequency count to know the exact amount and percentage of value that are in the different levels in each category. #Univariate analysis #Dependent variable #Frequency plotpar(mfrow=c(1,1))barplot(table(data[[12]]), main = sprintf('Frequency plot of the variable: %s', colnames(data[12])), xlab = colnames(data[12]), ylab = 'Frequency')#Check class BIAStable(data$quality)round(prop.table((table(data$quality))),2) Analyzing the plot, I stated that the dataset has a considerably higher amount of 0 values, indicating that the data has more rows that represent a bad quality of the wine. In other words, the data is biased. Further, by analyzing the tables, I declared that the data has 1,382 rows that were qualified as a bad quality wine and 217 as a good quality wine. Likewise, the dataset contains approximately 86% of 0 outcome values and 14% of 1 outcome values. In that sense, it is necessary to take into consideration that the dataset is biased. That is why it is essential to follow a stratified sampling method when splitting the data into the train and test set. Now, I proceed to analyze the independent variables. To develop the analysis, I chose to create boxplots and histogram plots for each variable. These visualizations will help us identify the location of the five-number summary values, the outliers it possesses, and the distribution that the variable follows. #Independent variable #Boxplotspar(mfrow=c(3,4))for (i in 1:(length(data)-1)){ boxplot(x = data[i], horizontal = TRUE, main = sprintf('Boxplot of the variable: %s', colnames(data[i])), xlab = colnames(data[i]))}#Histogramspar(mfrow=c(3,4))for (i in 1:(length(data)-1)){ hist(x = data[[i]], main = sprintf('Histogram of the variable: %s', colnames(data[i])), xlab = colnames(data[i]))} As we can see, the boxplots show where are the mean, median, and quartile measurements located for each variable, as well as the range of values each variable has. By analyzing the boxplots, I concluded that all the variables have outliers. Furthermore, the variables β€œresidual sugar” and β€œchlorides” are the variables that have the most amount of outliers. As we can see, there is a concentration of values near the mean and median, which is reflected by a very slim interquartile range (IQR). This information will come in handy at the data preparation step when I proceed to assess the outlier values. Visualizing the histogram plots, I identified the pattern of each of the variables. As we can see, there is a right skewness in most of the distributions. However, the variables β€œdensity” and β€œpH” show that they follow a normal distribution. Also, I can mention that the variables β€œresidual sugar” and β€œchlorides” have a wide range of values, with most of the observations grouped to the left side of the graph. This phenomenon indicates that the variables have a large number of outlier values. Finally, I developed a bivariate analysis to understand the relationship that the variables have with each other. #Bivariate analysis #Correlation matrixlibrary(ggcorrplot)ggcorrplot(round(cor(data[-12]), 2), type = "lower", lab = TRUE, title = 'Correlation matrix of the red wine quality dataset') In the image, we can visualize the positive and negative relationships between the independent variables. As the matrix shows, there is a positive correlation of 0.67 between the β€œfixed acidity” variable and the variables β€œcitric acid” and β€œdensity”. In other words, as the β€œfixed acidity” variable increases the β€œcitric acid” will also increase. Likewise, the same concept will apply to the relationship between β€œfree sulfur dioxide” and β€œtotal sulfur dioxide” variables. Moreover, I can state that the variables β€œfixed acidity” and β€œpH” have a negative linear correlation of -0.68. This relationship indicates that when the fixed acidity of the wine increases, the pH value of the wine decreases. This assumption is correct because we know as a fact that when the value of the pH of a component decreases means that the element is gaining acidity. Once I finished the EDA, I proceed to prepare the data to develop the prediction models. In this step of the project, I focused on finding missing data and assessed the outlier values. #Missing valuessum(is.na(data)) Now that I have identified that the dataset does not contain any missing values, I will proceed to work with the outliers. First, I identified the number of outliers each variable has. To complete this step, I created and applied a specific function that identifies outliers. Then, I generated a data frame to store the information. Further, I used a for-loop to gather and store the information. #Outliers #Identifing outliersis_outlier <- function(x) { return(x < quantile(x, 0.25) - 1.5 * IQR(x) | x > quantile(x, 0.75) + 1.5 * IQR(x))}outlier <- data.frame(variable = character(), sum_outliers = integer(), stringsAsFactors=FALSE)for (j in 1:(length(data)-1)){ variable <- colnames(data[j]) for (i in data[j]){ sum_outliers <- sum(is_outlier(i)) } row <- data.frame(variable,sum_outliers) outlier <- rbind(outlier, row)} As we can visualize, all of the variables in the data have outliers. To assess these values, I followed a criterion which dictates that I will accept variables that have less than 5% of outlier values throughout all the observations of the dataset. It is essential to mention that I do not proceed to drop the outlier values because they represent and carry necessary information about the dataset. Deleting the outliers can bias the result of our model in a significant way. #Identifying the percentage of outliersfor (i in 1:nrow(outlier)){ if (outlier[i,2]/nrow(data) * 100 >= 5){ print(paste(outlier[i,1], '=', round(outlier[i,2]/nrow(data) * 100, digits = 2), '%')) }} With the code display above, I was able to identify that the variables β€œresidual sugar” and β€œchlorides” have approximately 10% and 7% of outlier values, respectively. Further, I proceed to input the outlier values of these variables. I chose to change the outlier values with the mean value of the variables because, as we can see in the histogram plot, both variables have a large concentration of value neer the mean. For that reason, by inputting the values with the mean number, will not affect the essence of the data in a significant matter. #Inputting outlier valuesfor (i in 4:5){ for (j in 1:nrow(data)){ if (data[[j, i]] > as.numeric(quantile(data[[i]], 0.75) + 1.5 * IQR(data[[i]]))){ if (i == 4){ data[[j, i]] <- round(mean(data[[i]]), digits = 2) } else{ data[[j, i]] <- round(mean(data[[i]]), digits = 3) } } }} Now that I correctly arranged the dataset, I proceed to develop the machine learning models that will predict the red wine quality. The first step is to split the data into train and test. Since the data is unbalanced, I proceed to develop a stratified sampling. I used 80% of the observations that represent a good quality wine (1 outcome of the β€œquality” variable) to balance the train set. In other words, the dependent variable will have the same number of observations of 0 and 1 in the train set. #Splitting the dataset into the Training set and Test set #Stratified sampledata_ones <- data[which(data$quality == 1), ]data_zeros <- data[which(data$quality == 0), ]#Train dataset.seed(123)train_ones_rows <- sample(1:nrow(data_ones), 0.8*nrow(data_ones))train_zeros_rows <- sample(1:nrow(data_zeros), 0.8*nrow(data_ones))train_ones <- data_ones[train_ones_rows, ] train_zeros <- data_zeros[train_zeros_rows, ]train_set <- rbind(train_ones, train_zeros)table(train_set$quality)#Test Datatest_ones <- data_ones[-train_ones_rows, ]test_zeros <- data_zeros[-train_zeros_rows, ]test_set <- rbind(test_ones, test_zeros)table(test_set$quality) As we can see in the image, the train set will contain fewer observations than the test set. However, the train set will be balanced to train the models efficiently. Now that I have completed this step, I proceed to develop the models and determine which model can accurately predict the quality of red wine. #Logistic Regressionlr = glm(formula = quality ~., data = training_set, family = binomial)#Predictionsprob_pred = predict(lr, type = 'response', newdata = test_set[-12])library(InformationValue)optCutOff <- optimalCutoff(test_set$quality, prob_pred)[1]y_pred = ifelse(prob_pred > optCutOff, 1, 0) Once the model is created, with the training set, I proceed to predict the values with the test set data. Since the logistic regression will deliver probability values, I proceed to calculate the optimal cut-off point, which will categorize the outcome values into 1 or 0. Then, with the predicted values obtained, I proceed to develop a confusion matrix where we can visualize the test set values with the predicted values for the logistic regression model. #Making the confusion matrixcm_lr = table(test_set[, 12], y_pred)cm_lr#Accuracyaccuracy_lr = (cm_lr[1,1] + cm_lr[1,1])/ (cm_lr[1,1] + cm_lr[1,1] + cm_lr[2,1] + cm_lr[1,2])accuracy_lr Visualizing the table, I stated that the model has accurately predicted 1,208 values, meaning that the model misclassified 45 of the observations. Additionally, I concluded that the model has an accuracy of 96.41%. #ROC curvelibrary(ROSE)par(mfrow = c(1, 1))roc.curve(test_set$quality, y_pred) Further, I proceed to develop a ROC curve to know the capability of the model to distinguish the outcome classes. Finally, I founded that the area under the curve (AUC) is 51.1%. Now I followed the same step as before. Once the model is created, with the training set, I proceed to predict the values with the test set data. #Decision Treelibrary(rpart)dt = rpart(formula = quality ~ ., data = training_set, method = 'class')#Predictionsy_pred = predict(dt, type = 'class', newdata = test_set[-12]) Further, I proceed to generate a confusion matrix where we can see the test set values with the predicted values for the decision tree model. #Making the confusion matrixcm_dt = table(test_set[, 12], y_pred)cm_dt#Accuracyaccuracy_dt = (cm_dt[1,1] + cm_dt[1,1])/ (cm_dt[1,1] + cm_dt[1,1] + cm_dt[2,1] + cm_dt[1,2])accuracy_dt Visualizing the table, I declared that the model has accurately predicted 873 observations, indicating that the model misclassified 380 of the values. Also, I founded that the model has an accuracy of 69.67%. #ROC curvelibrary(ROSE)roc.curve(test_set$quality, y_pred) Then, with the ROC curve, I have obtained that the area under the curve (AUC), which has a value of 81%. Finally, I continued to create the random forest model with the training set and also predict the values with the test set data. #Random forestlibrary(randomForest)rf = randomForest(x = training_set[-12], y = training_set$quality, ntree = 10)#Predictionsy_pred = predict(rf, type = 'class', newdata = test_set[-12]) Now, I proceed to visualize the test set values with the predicted values for the random forest model by creating a confusion matrix. #Making the confusion matrixcm_rf = table(test_set[, 12], y_pred)cm_rf#Accuracyaccuracy_rf = (cm_rf[1,1] + cm_rf[1,1])/ (cm_rf[1,1] + cm_rf[1,1] + cm_rf[2,1] + cm_rf[1,2])accuracy_rf Evaluating the table, I demonstrated that the model has accurately predicted 991 values, which means that the model misclassified 262 observations. Moreover, I obtained that the model’s accuracy is 79.09%. #ROC curvelibrary(ROSE)roc.curve(test_set$quality, y_pred) Finally, with the ROC curve, I obtained a value of the AUC of 83.7%. Moreover, I proceed to answer the second question of the project by calculating the variable importance of the model with the highest accuracy. In other words, I calculated the variable importance of the logistic regression model. #Variable importancelibrary(caret)varImp(lr) By analyzing the results, I declared that the most significant variable for this model is β€œalcohol”, followed by the variables β€œsulphates” and β€œfixed acidity”. Further, I effectuated an investigation to know the performance and impact of these components on the red wine quality. I founded that sulphate is the component of the wine that is responsible for the freshness of the drink. In that sense, wines that do not contain sulphates or contain a low amount of this element, generally are wines that have a shorter shelf life. In other words, sulphate gives more control over the life of the wine since it helps to ensure the wine will be fresh and clean when opened. On the other hand, the alcohol ingredient also plays a meaningful part in the wine’s quality. The alcohol will help balance the firmer and acid taste of the wine, making an interrelationship of the hard and soft characters of the wine. As we analyzed, the logistic regression model explains the actual theory facts. The investigation about the essential components for a good wine quality involved the variables obtained as necessary in the model. For this reason, the variables β€œalcohol” and β€œsulphates” are very significant to the model because these elements will be an essential component in indicating if a wine has a good or bad quality. After obtaining the results of the different machine learning algorithms, I stated that the Logistic Regression model displayed a higher accuracy in predicting the quality of red wine. With an accuracy of 96.41%, this model was able to predict correctly 1,209 values, meaning that the misclassification error of the model was 3.59%. On the other hand, by analyzing the ROC curve, I declared that the model performance is not as good as expected. By evaluating the area under the curve (AUC = 51.1%), I labeled the ROC curve as a fail curve. In other words, the model is not capable of identifying the different classes, which indicates that the model has a low performance. For this reason, I concluded that even though the model has good accuracy in predicting the test set values, it has a pitful rate of quickly identifying true positive values. Moreover, by analyzing the other ROC curves, I revealed that the random forest did have the best performance by obtaining an area under the curve of 83.7%. Meaning that even though the random forest model did not display the highest accuracy between the three models, it has the best performance by detecting the different classes of the dependent variable better than the logistic regression. Further, with the logistic regression model, I proceed to identify which of the physicochemical properties has the highest impact on the quality of red wine. I distinguished that the β€œalcohol”, β€œsulphates”, and β€œfixed acidity” are the variables that have the most crucial influence in the model. For that matter, if one of these variables changes, the results of the model will be affected strongly.
[ { "code": null, "e": 448, "s": 172, "text": "In the following project, I applied three different machine learning algorithms to predict the quality of a wine. The dataset I used for the project is called Wine Quality Data Set (specifically the β€œwinequality-red.csv” file), taken from the UCI Machine Learning Repository." }, { "code": null, "e": 886, "s": 448, "text": "The dataset contains 1,599 observations and 12 attributes related to the red variants of the Portuguese β€œVinho Verde” wine. Each row describes the physicochemical properties of one bottle of wine. The first 11 independent variables display numeric information about these characteristics, and the last dependent variable revels the quality of the wine on a scale from 0 (bad quality wine) to 10 (good quality wine) based on sensory data." }, { "code": null, "e": 1049, "s": 886, "text": "Since the outcome variable is ordinal, I chose logistic regression, decision trees, and random forest classification algorithms to answer the following questions:" }, { "code": null, "e": 1259, "s": 1049, "text": "Which machine learning algorithm will enable the most accurate prediction of wine quality from its physicochemical properties?What physicochemical properties of red wine have the highest impact on its quality?" }, { "code": null, "e": 1386, "s": 1259, "text": "Which machine learning algorithm will enable the most accurate prediction of wine quality from its physicochemical properties?" }, { "code": null, "e": 1470, "s": 1386, "text": "What physicochemical properties of red wine have the highest impact on its quality?" }, { "code": null, "e": 1572, "s": 1470, "text": "For the following project, I used the R programming language to explore, prepare, and model the data." }, { "code": null, "e": 1674, "s": 1572, "text": "Once the working directory is set and the dataset is download into our computer, I imported the data." }, { "code": null, "e": 1756, "s": 1674, "text": "#Importing the datasetdata <- read.csv('winequality-red.csv', sep = ';')str(data)" }, { "code": null, "e": 1976, "s": 1756, "text": "With the str() function, we could see that all the variable types are numerical, which is the correct format except the outcome variable. I proceed to transform the dependent variable into a binary categorical response." }, { "code": null, "e": 2102, "s": 1976, "text": "#Format outcome variabledata$quality <- ifelse(data$quality >= 7, 1, 0)data$quality <- factor(data$quality, levels = c(0, 1))" }, { "code": null, "e": 2196, "s": 2102, "text": "The arbitrary criteria I selected to modify the levels of the outcome variable is as follows:" }, { "code": null, "e": 2386, "s": 2196, "text": "Values above or equal to seven will be changed to 1, meaning a good quality wine.On the other hand, amounts less than seven will be converted to 0 and will indicate bad or mediocre quality." }, { "code": null, "e": 2468, "s": 2386, "text": "Values above or equal to seven will be changed to 1, meaning a good quality wine." }, { "code": null, "e": 2577, "s": 2468, "text": "On the other hand, amounts less than seven will be converted to 0 and will indicate bad or mediocre quality." }, { "code": null, "e": 2692, "s": 2577, "text": "Furthermore, I modified the type of the variable β€œquality” to factor, indicating that the variable is categorical." }, { "code": null, "e": 2827, "s": 2692, "text": "Now, I proceed to develop an EDA on the data to find essential insights and to determine specific relationships between the variables." }, { "code": null, "e": 2967, "s": 2827, "text": "First, I developed a descriptive analysis where I collected the five-number summary statistics of the data by using the summary() function." }, { "code": null, "e": 3004, "s": 2967, "text": "#Descriptive statisticssummary(data)" }, { "code": null, "e": 3332, "s": 3004, "text": "The image shows the five-number summary values of each of the variables in the data. In other words, with the function, I obtained the minimum and maximum, the 1st and 3rd quartile, the mean, and the median values of the numerical variables. Additionally, the summary shows the frequency of the level of the dependent variable." }, { "code": null, "e": 3477, "s": 3332, "text": "Next, I developed a univariate analysis, which consists of examining each of the variables separately. First, I analyzed the dependent variable." }, { "code": null, "e": 3738, "s": 3477, "text": "To analyze the outcome variable, I developed a bar plot to visualize the frequency count of the categorical levels. Also, I generated a table of frequency count to know the exact amount and percentage of value that are in the different levels in each category." }, { "code": null, "e": 4086, "s": 3738, "text": "#Univariate analysis #Dependent variable #Frequency plotpar(mfrow=c(1,1))barplot(table(data[[12]]), main = sprintf('Frequency plot of the variable: %s', colnames(data[12])), xlab = colnames(data[12]), ylab = 'Frequency')#Check class BIAStable(data$quality)round(prop.table((table(data$quality))),2)" }, { "code": null, "e": 4295, "s": 4086, "text": "Analyzing the plot, I stated that the dataset has a considerably higher amount of 0 values, indicating that the data has more rows that represent a bad quality of the wine. In other words, the data is biased." }, { "code": null, "e": 4541, "s": 4295, "text": "Further, by analyzing the tables, I declared that the data has 1,382 rows that were qualified as a bad quality wine and 217 as a good quality wine. Likewise, the dataset contains approximately 86% of 0 outcome values and 14% of 1 outcome values." }, { "code": null, "e": 4747, "s": 4541, "text": "In that sense, it is necessary to take into consideration that the dataset is biased. That is why it is essential to follow a stratified sampling method when splitting the data into the train and test set." }, { "code": null, "e": 5057, "s": 4747, "text": "Now, I proceed to analyze the independent variables. To develop the analysis, I chose to create boxplots and histogram plots for each variable. These visualizations will help us identify the location of the five-number summary values, the outliers it possesses, and the distribution that the variable follows." }, { "code": null, "e": 5534, "s": 5057, "text": "#Independent variable #Boxplotspar(mfrow=c(3,4))for (i in 1:(length(data)-1)){ boxplot(x = data[i], horizontal = TRUE, main = sprintf('Boxplot of the variable: %s', colnames(data[i])), xlab = colnames(data[i]))}#Histogramspar(mfrow=c(3,4))for (i in 1:(length(data)-1)){ hist(x = data[[i]], main = sprintf('Histogram of the variable: %s', colnames(data[i])), xlab = colnames(data[i]))}" }, { "code": null, "e": 5698, "s": 5534, "text": "As we can see, the boxplots show where are the mean, median, and quartile measurements located for each variable, as well as the range of values each variable has." }, { "code": null, "e": 6029, "s": 5698, "text": "By analyzing the boxplots, I concluded that all the variables have outliers. Furthermore, the variables β€œresidual sugar” and β€œchlorides” are the variables that have the most amount of outliers. As we can see, there is a concentration of values near the mean and median, which is reflected by a very slim interquartile range (IQR)." }, { "code": null, "e": 6139, "s": 6029, "text": "This information will come in handy at the data preparation step when I proceed to assess the outlier values." }, { "code": null, "e": 6635, "s": 6139, "text": "Visualizing the histogram plots, I identified the pattern of each of the variables. As we can see, there is a right skewness in most of the distributions. However, the variables β€œdensity” and β€œpH” show that they follow a normal distribution. Also, I can mention that the variables β€œresidual sugar” and β€œchlorides” have a wide range of values, with most of the observations grouped to the left side of the graph. This phenomenon indicates that the variables have a large number of outlier values." }, { "code": null, "e": 6749, "s": 6635, "text": "Finally, I developed a bivariate analysis to understand the relationship that the variables have with each other." }, { "code": null, "e": 6981, "s": 6749, "text": "#Bivariate analysis #Correlation matrixlibrary(ggcorrplot)ggcorrplot(round(cor(data[-12]), 2), type = \"lower\", lab = TRUE, title = 'Correlation matrix of the red wine quality dataset')" }, { "code": null, "e": 7454, "s": 6981, "text": "In the image, we can visualize the positive and negative relationships between the independent variables. As the matrix shows, there is a positive correlation of 0.67 between the β€œfixed acidity” variable and the variables β€œcitric acid” and β€œdensity”. In other words, as the β€œfixed acidity” variable increases the β€œcitric acid” will also increase. Likewise, the same concept will apply to the relationship between β€œfree sulfur dioxide” and β€œtotal sulfur dioxide” variables." }, { "code": null, "e": 7831, "s": 7454, "text": "Moreover, I can state that the variables β€œfixed acidity” and β€œpH” have a negative linear correlation of -0.68. This relationship indicates that when the fixed acidity of the wine increases, the pH value of the wine decreases. This assumption is correct because we know as a fact that when the value of the pH of a component decreases means that the element is gaining acidity." }, { "code": null, "e": 8016, "s": 7831, "text": "Once I finished the EDA, I proceed to prepare the data to develop the prediction models. In this step of the project, I focused on finding missing data and assessed the outlier values." }, { "code": null, "e": 8048, "s": 8016, "text": "#Missing valuessum(is.na(data))" }, { "code": null, "e": 8171, "s": 8048, "text": "Now that I have identified that the dataset does not contain any missing values, I will proceed to work with the outliers." }, { "code": null, "e": 8445, "s": 8171, "text": "First, I identified the number of outliers each variable has. To complete this step, I created and applied a specific function that identifies outliers. Then, I generated a data frame to store the information. Further, I used a for-loop to gather and store the information." }, { "code": null, "e": 8937, "s": 8445, "text": "#Outliers #Identifing outliersis_outlier <- function(x) { return(x < quantile(x, 0.25) - 1.5 * IQR(x) | x > quantile(x, 0.75) + 1.5 * IQR(x))}outlier <- data.frame(variable = character(), sum_outliers = integer(), stringsAsFactors=FALSE)for (j in 1:(length(data)-1)){ variable <- colnames(data[j]) for (i in data[j]){ sum_outliers <- sum(is_outlier(i)) } row <- data.frame(variable,sum_outliers) outlier <- rbind(outlier, row)}" }, { "code": null, "e": 9186, "s": 8937, "text": "As we can visualize, all of the variables in the data have outliers. To assess these values, I followed a criterion which dictates that I will accept variables that have less than 5% of outlier values throughout all the observations of the dataset." }, { "code": null, "e": 9413, "s": 9186, "text": "It is essential to mention that I do not proceed to drop the outlier values because they represent and carry necessary information about the dataset. Deleting the outliers can bias the result of our model in a significant way." }, { "code": null, "e": 9663, "s": 9413, "text": "#Identifying the percentage of outliersfor (i in 1:nrow(outlier)){ if (outlier[i,2]/nrow(data) * 100 >= 5){ print(paste(outlier[i,1], '=', round(outlier[i,2]/nrow(data) * 100, digits = 2), '%')) }}" }, { "code": null, "e": 9830, "s": 9663, "text": "With the code display above, I was able to identify that the variables β€œresidual sugar” and β€œchlorides” have approximately 10% and 7% of outlier values, respectively." }, { "code": null, "e": 10211, "s": 9830, "text": "Further, I proceed to input the outlier values of these variables. I chose to change the outlier values with the mean value of the variables because, as we can see in the histogram plot, both variables have a large concentration of value neer the mean. For that reason, by inputting the values with the mean number, will not affect the essence of the data in a significant matter." }, { "code": null, "e": 10560, "s": 10211, "text": "#Inputting outlier valuesfor (i in 4:5){ for (j in 1:nrow(data)){ if (data[[j, i]] > as.numeric(quantile(data[[i]], 0.75) + 1.5 * IQR(data[[i]]))){ if (i == 4){ data[[j, i]] <- round(mean(data[[i]]), digits = 2) } else{ data[[j, i]] <- round(mean(data[[i]]), digits = 3) } } }}" }, { "code": null, "e": 11063, "s": 10560, "text": "Now that I correctly arranged the dataset, I proceed to develop the machine learning models that will predict the red wine quality. The first step is to split the data into train and test. Since the data is unbalanced, I proceed to develop a stratified sampling. I used 80% of the observations that represent a good quality wine (1 outcome of the β€œquality” variable) to balance the train set. In other words, the dependent variable will have the same number of observations of 0 and 1 in the train set." }, { "code": null, "e": 11704, "s": 11063, "text": "#Splitting the dataset into the Training set and Test set #Stratified sampledata_ones <- data[which(data$quality == 1), ]data_zeros <- data[which(data$quality == 0), ]#Train dataset.seed(123)train_ones_rows <- sample(1:nrow(data_ones), 0.8*nrow(data_ones))train_zeros_rows <- sample(1:nrow(data_zeros), 0.8*nrow(data_ones))train_ones <- data_ones[train_ones_rows, ] train_zeros <- data_zeros[train_zeros_rows, ]train_set <- rbind(train_ones, train_zeros)table(train_set$quality)#Test Datatest_ones <- data_ones[-train_ones_rows, ]test_zeros <- data_zeros[-train_zeros_rows, ]test_set <- rbind(test_ones, test_zeros)table(test_set$quality)" }, { "code": null, "e": 11870, "s": 11704, "text": "As we can see in the image, the train set will contain fewer observations than the test set. However, the train set will be balanced to train the models efficiently." }, { "code": null, "e": 12013, "s": 11870, "text": "Now that I have completed this step, I proceed to develop the models and determine which model can accurately predict the quality of red wine." }, { "code": null, "e": 12366, "s": 12013, "text": "#Logistic Regressionlr = glm(formula = quality ~., data = training_set, family = binomial)#Predictionsprob_pred = predict(lr, type = 'response', newdata = test_set[-12])library(InformationValue)optCutOff <- optimalCutoff(test_set$quality, prob_pred)[1]y_pred = ifelse(prob_pred > optCutOff, 1, 0)" }, { "code": null, "e": 12472, "s": 12366, "text": "Once the model is created, with the training set, I proceed to predict the values with the test set data." }, { "code": null, "e": 12639, "s": 12472, "text": "Since the logistic regression will deliver probability values, I proceed to calculate the optimal cut-off point, which will categorize the outcome values into 1 or 0." }, { "code": null, "e": 12825, "s": 12639, "text": "Then, with the predicted values obtained, I proceed to develop a confusion matrix where we can visualize the test set values with the predicted values for the logistic regression model." }, { "code": null, "e": 13009, "s": 12825, "text": "#Making the confusion matrixcm_lr = table(test_set[, 12], y_pred)cm_lr#Accuracyaccuracy_lr = (cm_lr[1,1] + cm_lr[1,1])/ (cm_lr[1,1] + cm_lr[1,1] + cm_lr[2,1] + cm_lr[1,2])accuracy_lr" }, { "code": null, "e": 13224, "s": 13009, "text": "Visualizing the table, I stated that the model has accurately predicted 1,208 values, meaning that the model misclassified 45 of the observations. Additionally, I concluded that the model has an accuracy of 96.41%." }, { "code": null, "e": 13303, "s": 13224, "text": "#ROC curvelibrary(ROSE)par(mfrow = c(1, 1))roc.curve(test_set$quality, y_pred)" }, { "code": null, "e": 13482, "s": 13303, "text": "Further, I proceed to develop a ROC curve to know the capability of the model to distinguish the outcome classes. Finally, I founded that the area under the curve (AUC) is 51.1%." }, { "code": null, "e": 13628, "s": 13482, "text": "Now I followed the same step as before. Once the model is created, with the training set, I proceed to predict the values with the test set data." }, { "code": null, "e": 13856, "s": 13628, "text": "#Decision Treelibrary(rpart)dt = rpart(formula = quality ~ ., data = training_set, method = 'class')#Predictionsy_pred = predict(dt, type = 'class', newdata = test_set[-12])" }, { "code": null, "e": 13998, "s": 13856, "text": "Further, I proceed to generate a confusion matrix where we can see the test set values with the predicted values for the decision tree model." }, { "code": null, "e": 14182, "s": 13998, "text": "#Making the confusion matrixcm_dt = table(test_set[, 12], y_pred)cm_dt#Accuracyaccuracy_dt = (cm_dt[1,1] + cm_dt[1,1])/ (cm_dt[1,1] + cm_dt[1,1] + cm_dt[2,1] + cm_dt[1,2])accuracy_dt" }, { "code": null, "e": 14391, "s": 14182, "text": "Visualizing the table, I declared that the model has accurately predicted 873 observations, indicating that the model misclassified 380 of the values. Also, I founded that the model has an accuracy of 69.67%." }, { "code": null, "e": 14450, "s": 14391, "text": "#ROC curvelibrary(ROSE)roc.curve(test_set$quality, y_pred)" }, { "code": null, "e": 14555, "s": 14450, "text": "Then, with the ROC curve, I have obtained that the area under the curve (AUC), which has a value of 81%." }, { "code": null, "e": 14684, "s": 14555, "text": "Finally, I continued to create the random forest model with the training set and also predict the values with the test set data." }, { "code": null, "e": 14939, "s": 14684, "text": "#Random forestlibrary(randomForest)rf = randomForest(x = training_set[-12], y = training_set$quality, ntree = 10)#Predictionsy_pred = predict(rf, type = 'class', newdata = test_set[-12])" }, { "code": null, "e": 15073, "s": 14939, "text": "Now, I proceed to visualize the test set values with the predicted values for the random forest model by creating a confusion matrix." }, { "code": null, "e": 15257, "s": 15073, "text": "#Making the confusion matrixcm_rf = table(test_set[, 12], y_pred)cm_rf#Accuracyaccuracy_rf = (cm_rf[1,1] + cm_rf[1,1])/ (cm_rf[1,1] + cm_rf[1,1] + cm_rf[2,1] + cm_rf[1,2])accuracy_rf" }, { "code": null, "e": 15463, "s": 15257, "text": "Evaluating the table, I demonstrated that the model has accurately predicted 991 values, which means that the model misclassified 262 observations. Moreover, I obtained that the model’s accuracy is 79.09%." }, { "code": null, "e": 15522, "s": 15463, "text": "#ROC curvelibrary(ROSE)roc.curve(test_set$quality, y_pred)" }, { "code": null, "e": 15591, "s": 15522, "text": "Finally, with the ROC curve, I obtained a value of the AUC of 83.7%." }, { "code": null, "e": 15822, "s": 15591, "text": "Moreover, I proceed to answer the second question of the project by calculating the variable importance of the model with the highest accuracy. In other words, I calculated the variable importance of the logistic regression model." }, { "code": null, "e": 15867, "s": 15822, "text": "#Variable importancelibrary(caret)varImp(lr)" }, { "code": null, "e": 16027, "s": 15867, "text": "By analyzing the results, I declared that the most significant variable for this model is β€œalcohol”, followed by the variables β€œsulphates” and β€œfixed acidity”." }, { "code": null, "e": 16773, "s": 16027, "text": "Further, I effectuated an investigation to know the performance and impact of these components on the red wine quality. I founded that sulphate is the component of the wine that is responsible for the freshness of the drink. In that sense, wines that do not contain sulphates or contain a low amount of this element, generally are wines that have a shorter shelf life. In other words, sulphate gives more control over the life of the wine since it helps to ensure the wine will be fresh and clean when opened. On the other hand, the alcohol ingredient also plays a meaningful part in the wine’s quality. The alcohol will help balance the firmer and acid taste of the wine, making an interrelationship of the hard and soft characters of the wine." }, { "code": null, "e": 17181, "s": 16773, "text": "As we analyzed, the logistic regression model explains the actual theory facts. The investigation about the essential components for a good wine quality involved the variables obtained as necessary in the model. For this reason, the variables β€œalcohol” and β€œsulphates” are very significant to the model because these elements will be an essential component in indicating if a wine has a good or bad quality." }, { "code": null, "e": 17514, "s": 17181, "text": "After obtaining the results of the different machine learning algorithms, I stated that the Logistic Regression model displayed a higher accuracy in predicting the quality of red wine. With an accuracy of 96.41%, this model was able to predict correctly 1,209 values, meaning that the misclassification error of the model was 3.59%." }, { "code": null, "e": 18030, "s": 17514, "text": "On the other hand, by analyzing the ROC curve, I declared that the model performance is not as good as expected. By evaluating the area under the curve (AUC = 51.1%), I labeled the ROC curve as a fail curve. In other words, the model is not capable of identifying the different classes, which indicates that the model has a low performance. For this reason, I concluded that even though the model has good accuracy in predicting the test set values, it has a pitful rate of quickly identifying true positive values." }, { "code": null, "e": 18424, "s": 18030, "text": "Moreover, by analyzing the other ROC curves, I revealed that the random forest did have the best performance by obtaining an area under the curve of 83.7%. Meaning that even though the random forest model did not display the highest accuracy between the three models, it has the best performance by detecting the different classes of the dependent variable better than the logistic regression." } ]
How to handle right to left swipe gestures?
This example demonstrate about How to handle right to left swipe gestures 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"?> <LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" xmlns:app = "http://schemas.android.com/apk/res-auto" xmlns:tools = "http://schemas.android.com/tools" android:layout_width = "match_parent" android:gravity = "center" android:layout_height = "match_parent" tools:context = ".MainActivity" android:orientation = "vertical"> <Button android:id = "@+id/swap" android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:layout_alignParentTop = "true" android:layout_centerHorizontal = "true" android:layout_marginTop = "27dp" android:text = "Swap here"/> </LinearLayout> In the above code, we have taken button view to handle swaps Step 3 βˆ’ Add the following code to src/MainActivity.java package com.example.myapplication; import android.content.ActivityNotFoundException; import android.content.Intent; import android.content.pm.ResolveInfo; import android.content.res.Configuration; import android.graphics.PixelFormat; import android.os.Build; import android.os.Bundle; import android.support.annotation.RequiresApi; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.Gravity; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.WindowManager; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import java.util.List; import java.util.Locale; public class MainActivity extends AppCompatActivity { private WindowManager windowManager; private ImageView chatHead; WindowManager.LayoutParams params; @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); findViewById(R.id.swap).setOnTouchListener(new OnSwipeTouchListener(MainActivity.this) { public void onSwipeTop() { Toast.makeText(MainActivity.this, "top", Toast.LENGTH_SHORT).show(); } public void onSwipeRight() { Toast.makeText(MainActivity.this, "right", Toast.LENGTH_SHORT).show(); } public void onSwipeLeft() { Toast.makeText(MainActivity.this, "left", Toast.LENGTH_SHORT).show(); } public void onSwipeBottom() { Toast.makeText(MainActivity.this, "bottom", Toast.LENGTH_SHORT).show(); } }); } } Step 3 βˆ’ Add the following code to src/ OnSwipeTouchListener.java package com.example.myapplication; import android.content.Context; import android.view.GestureDetector; import android.view.GestureDetector.SimpleOnGestureListener; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; public class OnSwipeTouchListener implements OnTouchListener { private final GestureDetector gestureDetector; public OnSwipeTouchListener (Context ctx){ gestureDetector = new GestureDetector(ctx, new GestureListener()); } @Override public boolean onTouch(View v, MotionEvent event) { return gestureDetector.onTouchEvent(event); } private final class GestureListener extends SimpleOnGestureListener { private static final int SWIPE_THRESHOLD = 100; private static final int SWIPE_VELOCITY_THRESHOLD = 100; @Override public boolean onDown(MotionEvent e) { return true; } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { boolean result = false; try { float diffY = e2.getY() - e1.getY(); float diffX = e2.getX() - e1.getX(); if (Math.abs(diffX) > Math.abs(diffY)) { if (Math.abs(diffX) > SWIPE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) { if (diffX > 0) { onSwipeRight(); } else { onSwipeLeft(); } result = true; } } else if (Math.abs(diffY) > SWIPE_THRESHOLD && Math.abs(velocityY) > SWIPE_VELOCITY_THRESHOLD) { if (diffY > 0) { onSwipeBottom(); } else { onSwipeTop(); } result = true; } } catch (Exception exception) { exception.printStackTrace(); } return result; } } public void onSwipeRight() { } public void onSwipeLeft() { } public void onSwipeTop() { } public void onSwipeBottom() { } } Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen – Now swipe on button as shown below- Click here to download the project code
[ { "code": null, "e": 1136, "s": 1062, "text": "This example demonstrate about How to handle right to left swipe gestures" }, { "code": null, "e": 1265, "s": 1136, "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": 1330, "s": 1265, "text": "Step 2 βˆ’ Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2056, "s": 1330, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout 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:gravity = \"center\"\n android:layout_height = \"match_parent\"\n tools:context = \".MainActivity\"\n android:orientation = \"vertical\">\n <Button\n android:id = \"@+id/swap\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\"\n android:layout_alignParentTop = \"true\"\n android:layout_centerHorizontal = \"true\"\n android:layout_marginTop = \"27dp\"\n android:text = \"Swap here\"/>\n</LinearLayout>" }, { "code": null, "e": 2117, "s": 2056, "text": "In the above code, we have taken button view to handle swaps" }, { "code": null, "e": 2174, "s": 2117, "text": "Step 3 βˆ’ Add the following code to src/MainActivity.java" }, { "code": null, "e": 3920, "s": 2174, "text": "package com.example.myapplication;\nimport android.content.ActivityNotFoundException;\nimport android.content.Intent;\nimport android.content.pm.ResolveInfo;\nimport android.content.res.Configuration;\nimport android.graphics.PixelFormat;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.support.annotation.RequiresApi;\nimport android.support.v7.app.AppCompatActivity;\nimport android.util.Log;\nimport android.view.Gravity;\nimport android.view.LayoutInflater;\nimport android.view.MotionEvent;\nimport android.view.View;\nimport android.view.WindowManager;\nimport android.widget.Button;\nimport android.widget.ImageView;\nimport android.widget.TextView;\nimport android.widget.Toast;\nimport java.util.List;\nimport java.util.Locale;\n\npublic class MainActivity extends AppCompatActivity {\n private WindowManager windowManager;\n private ImageView chatHead;\n WindowManager.LayoutParams params;\n @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n findViewById(R.id.swap).setOnTouchListener(new OnSwipeTouchListener(MainActivity.this) {\n public void onSwipeTop() {\n Toast.makeText(MainActivity.this, \"top\", Toast.LENGTH_SHORT).show();\n }\n public void onSwipeRight() {\n Toast.makeText(MainActivity.this, \"right\", Toast.LENGTH_SHORT).show();\n }\n public void onSwipeLeft() {\n Toast.makeText(MainActivity.this, \"left\", Toast.LENGTH_SHORT).show();\n }\n public void onSwipeBottom() {\n Toast.makeText(MainActivity.this, \"bottom\", Toast.LENGTH_SHORT).show();\n }\n });\n }\n}" }, { "code": null, "e": 3986, "s": 3920, "text": "Step 3 βˆ’ Add the following code to src/ OnSwipeTouchListener.java" }, { "code": null, "e": 6101, "s": 3986, "text": "package com.example.myapplication;\nimport android.content.Context;\nimport android.view.GestureDetector;\nimport android.view.GestureDetector.SimpleOnGestureListener;\nimport android.view.MotionEvent;\nimport android.view.View;\nimport android.view.View.OnTouchListener;\n\npublic class OnSwipeTouchListener implements OnTouchListener {\n private final GestureDetector gestureDetector;\n public OnSwipeTouchListener (Context ctx){\n gestureDetector = new GestureDetector(ctx, new GestureListener());\n }\n @Override\n public boolean onTouch(View v, MotionEvent event) {\n return gestureDetector.onTouchEvent(event);\n }\n private final class GestureListener extends SimpleOnGestureListener {\n private static final int SWIPE_THRESHOLD = 100;\n private static final int SWIPE_VELOCITY_THRESHOLD = 100;\n @Override\n public boolean onDown(MotionEvent e) {\n return true;\n }\n @Override\n public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {\n boolean result = false;\n try {\n float diffY = e2.getY() - e1.getY();\n float diffX = e2.getX() - e1.getX();\n if (Math.abs(diffX) > Math.abs(diffY)) {\n if (Math.abs(diffX) > SWIPE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {\n if (diffX > 0) {\n onSwipeRight();\n } else {\n onSwipeLeft();\n }\n result = true;\n }\n }\n else if (Math.abs(diffY) > SWIPE_THRESHOLD && Math.abs(velocityY) > SWIPE_VELOCITY_THRESHOLD) {\n if (diffY > 0) {\n onSwipeBottom();\n } else {\n onSwipeTop();\n }\n result = true;\n }\n } catch (Exception exception) {\n exception.printStackTrace();\n }\n return result;\n }\n }\n public void onSwipeRight() {\n }\n public void onSwipeLeft() {\n }\n public void onSwipeTop() {\n }\n public void onSwipeBottom() {\n }\n}" }, { "code": null, "e": 6448, "s": 6101, "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": 6484, "s": 6448, "text": "Now swipe on button as shown below-" }, { "code": null, "e": 6526, "s": 6486, "text": "Click here to download the project code" } ]
Git Security SSH
Up to this point, we have used HTTPS to connect to our remote repository. HTTPS will usually work just fine, but you should use SSH if you work with unsecured networks. And sometimes, a project will require that you use SSH. SSH is a secure shell network protocol that is used for network management, remote file transfer, and remote system access. SSH uses a pair of SSH keys to establish an authenticated and encrypted secure network protocol. It allows for secure remote communication on unsecured open networks. SSH keys are used to initiate a secure "handshake". When generating a set of keys, you will generate a "public" and "private" key. The "public" key is the one you share with the remote party. Think of this more as the lock. The "private" key is the one you keep for yourself in a secure place. Think of this as the key to the lock. SSH keys are generated through a security algorithm. It is all very complicated, but it uses prime numbers, and large random numbers to make the public and private key. It is created so that the public key can be derived from the private key, but not the other way around. In rhe command line for Linux, Apple, and in the Git Bash for Windows, you can generate an SSH key. Let's go through it, step by step. Start by creating a new key, using your email as a label: ssh-keygen -t rsa -b 4096 -C "test@w3schools.com" Generating public/private rsa key pair. Enter file in which to save the key (/Users/user/.ssh/id_rsa): Created directory '/Users/user/.ssh'. Enter passphrase (empty for no passphrase): Enter same passphrase again: Your identification has been saved in /Users/user/.ssh/id_rsa Your public key has been saved in /Users/user/.ssh/id_rsa.pub The key fingerprint is: SHA256:******************************************* test@w3schools.com The key's randomart image is: +---[RSA 4096]----+ | | | | | | | | | | | | | | | | | | +----[SHA256]-----+ You will be prompted with the following through this creation: Enter file in which to save the key (/c/Users/user/.ssh/id_rsa): Select a file location, or press "Enter" to use the default file location. Enter passphrase (empty for no passphrase): Enter same passphrase again: Entering a secure passphrase will create an additional layer of security. Preventing anyone who gains access to the computer to use that key without the passphrase. However, it will require you to supply the passphrase anytime the SSH key is used. Now we add this SSH key pair to the SSH-Agent (using the file location from above): ssh-add /Users/user/.ssh/id_rsa Enter passphrase for /Users/user/.ssh/id_rsa: Identity added: /Users/user/.ssh/id_rsa (test@w3schools.com) You will be prompted to supply the passphrase, if you added one. Now the SSH key pair is ready to use. 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": 74, "s": 0, "text": "Up to this point, we have used HTTPS to connect to our remote repository." }, { "code": null, "e": 225, "s": 74, "text": "HTTPS will usually work just fine, but you should use SSH if you work with unsecured networks. And sometimes, a project will require that you use SSH." }, { "code": null, "e": 350, "s": 225, "text": "SSH is a secure shell network protocol that is used for network management, \nremote file transfer, and remote system access." }, { "code": null, "e": 519, "s": 350, "text": "SSH uses a pair of SSH keys to establish an authenticated and encrypted \nsecure network protocol. It allows for secure remote communication on unsecured \nopen networks." }, { "code": null, "e": 651, "s": 519, "text": "SSH keys are used to initiate a secure \"handshake\". When generating a set of \nkeys, you will generate a \"public\" and \"private\" key." }, { "code": null, "e": 745, "s": 651, "text": "The \"public\" key is the one you share with the remote party. Think of this \nmore as the lock." }, { "code": null, "e": 854, "s": 745, "text": "The \"private\" key is the one you keep for yourself in a secure place. Think of \nthis as the key to the lock." }, { "code": null, "e": 1024, "s": 854, "text": "SSH keys are generated through a security algorithm. It is all very complicated, but it uses prime numbers, and \nlarge random numbers to make the public and private key." }, { "code": null, "e": 1129, "s": 1024, "text": "It is created so that the public key can be derived from the private \nkey, but not the other way around." }, { "code": null, "e": 1230, "s": 1129, "text": "In rhe command line for Linux, Apple, and in the Git Bash for Windows, you can \ngenerate an SSH key." }, { "code": null, "e": 1265, "s": 1230, "text": "Let's go through it, step by step." }, { "code": null, "e": 1323, "s": 1265, "text": "Start by creating a new key, using your email as a label:" }, { "code": null, "e": 2055, "s": 1323, "text": "ssh-keygen -t rsa -b 4096 -C \"test@w3schools.com\"\nGenerating public/private rsa key pair.\nEnter file in which to save the key (/Users/user/.ssh/id_rsa):\nCreated directory '/Users/user/.ssh'.\nEnter passphrase (empty for no passphrase):\nEnter same passphrase again:\nYour identification has been saved in /Users/user/.ssh/id_rsa\nYour public key has been saved in /Users/user/.ssh/id_rsa.pub\nThe key fingerprint is:\nSHA256:******************************************* test@w3schools.com\nThe key's randomart image is:\n+---[RSA 4096]----+\n| |\n| |\n| |\n| |\n| |\n| |\n| |\n| |\n| |\n+----[SHA256]-----+" }, { "code": null, "e": 2118, "s": 2055, "text": "You will be prompted with the following through this creation:" }, { "code": null, "e": 2183, "s": 2118, "text": "Enter file in which to save the key (/c/Users/user/.ssh/id_rsa):" }, { "code": null, "e": 2258, "s": 2183, "text": "Select a file location, or press \"Enter\" to use the default file location." }, { "code": null, "e": 2331, "s": 2258, "text": "Enter passphrase (empty for no passphrase):\nEnter same passphrase again:" }, { "code": null, "e": 2579, "s": 2331, "text": "Entering a secure passphrase will create an additional layer of security. Preventing anyone who gains access to the computer to use that key without the passphrase. However, it will require you to supply the passphrase anytime the SSH key is used." }, { "code": null, "e": 2663, "s": 2579, "text": "Now we add this SSH key pair to the SSH-Agent (using the file location from above):" }, { "code": null, "e": 2802, "s": 2663, "text": "ssh-add /Users/user/.ssh/id_rsa\nEnter passphrase for /Users/user/.ssh/id_rsa:\nIdentity added: /Users/user/.ssh/id_rsa (test@w3schools.com)" }, { "code": null, "e": 2867, "s": 2802, "text": "You will be prompted to supply the passphrase, if you added one." }, { "code": null, "e": 2905, "s": 2867, "text": "Now the SSH key pair is ready to use." }, { "code": null, "e": 2938, "s": 2905, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 2980, "s": 2938, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 3087, "s": 2980, "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": 3106, "s": 3087, "text": "help@w3schools.com" } ]
Code Formatting in Kotlin using ktlint - GeeksforGeeks
04 Jan, 2022 As we all know about the kotlin language which is recommended by google particularly for android app development, and of course, it made the life of android app developers easier. But if you are a beginner in this field then you may not know that you need to write the codes in the desired format. and it is definitely helpful for developers, but if you are not familiar with how to write clean code using Kotlin then don’t worry you need not learn something to achieve this, instead, you just have to use ktlint that is used for the same purpose. ktlint: ktlint is an anti-bikeshedding Kotlin linter with a built-in format. In simple words, it checks our code styling and also helps us to format our code and make it better for understanding. Ktlitn can save your time It can save your energy (because you don’t have to manually check your code styling) It can simplify your process Before this, let’s talk about some important things like ktlint breaks down into two things. linting tool: The lining tool is based on the kotlin standard style guide, and it will validate and make sure that your code adheres to that style guide.formatter: If ktlint detects that there are issues in your code you can then run the formatter and have ktlint try to automatically fix those issues for you. linting tool: The lining tool is based on the kotlin standard style guide, and it will validate and make sure that your code adheres to that style guide. formatter: If ktlint detects that there are issues in your code you can then run the formatter and have ktlint try to automatically fix those issues for you. Add ktlint to your project and more specifically we are going to be integrating ktlint with the ktlint Gradle plugin, this is a separate third party plugin on top of the basic ktlint tool and it makes working with ktlint very easy by providing out of the box Gradle tasks with, which to run ktlint commands. There are several options, but the easiest way is to make use of the ktlint-Gradle plugin which provides out of the box Gradle tasks for ktlint’s tools For Adding the ktlint-gradle plugin just Add the ktlint-gradle plugin to your root-level build.gradle file For Apply the plugin to subprojects just Apply the ktlint-gradle plugin to any Gradle modules that you would like to check Verify added Gradle tasks as Check that ktlintCheck and ktlintFormat tasks have been added for your various build targets If using a version of Gradle which supports the plugins DSL, you can add ktlint-gradle to your project with the following code: Kotlin // root-level build.gradleplugins { id "org.jlleitschuh.gradle.ktlint" version "7.1.0"} // root-level build.gradlebuildscript { repositories { maven { url "https://plugins.gradle.org/m2/" } } dependencies { classpath "org.jlleitschuh.gradle:ktlint-gradle:7.1.0" }} You’ll want to apply the ktlint-gradle plugin to the various modules within your project. You can do this using the allProjects{} block in the root-level build.gradle file. Kotlin // root-level build.gradleallprojects { ... apply plugin: "org.jlleitschuh.gradle.ktlint"} Finally, you’ll want to test that the ktlint Gradle tasks are now available for use. You can do it in these ways run ./gradlew tasks from the command line and look for any ktlint tasks try to run ./gradlew ktlintCheck from the command line use the Gradle tool window in IntelliJ or Android Studio to see if the tasks are listed To actually check your code’s formatting, run the following command from the command line: ./gradlew ktlintCheck This will run through your project and report back any errors which are found using the default ktlint-gradle plugin configuration. To automatically fix any errors which are reported by ktlintCheck, you can run the following command from the command line: ./gradlew ktlintFormat This will attempt to auto-fix any errors and will report back any issues that could not automatically be fixed. When everything is correctly formatted, you should see something like the following image when you run ktlintCheck. ktlint is an open-source project that is maintained by Pinterest and you can find more info. Click here. clintra Picked Android Kotlin Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Flutter - Custom Bottom Navigation Bar Retrofit with Kotlin Coroutine in Android GridView in Android with Example How to Change the Background Color After Clicking the Button in Android? Android Listview in Java with Example Android UI Layouts Kotlin Array Retrofit with Kotlin Coroutine in Android Android Menus MVP (Model View Presenter) Architecture Pattern in Android with Example
[ { "code": null, "e": 25142, "s": 25114, "text": "\n04 Jan, 2022" }, { "code": null, "e": 25690, "s": 25142, "text": "As we all know about the kotlin language which is recommended by google particularly for android app development, and of course, it made the life of android app developers easier. But if you are a beginner in this field then you may not know that you need to write the codes in the desired format. and it is definitely helpful for developers, but if you are not familiar with how to write clean code using Kotlin then don’t worry you need not learn something to achieve this, instead, you just have to use ktlint that is used for the same purpose." }, { "code": null, "e": 25886, "s": 25690, "text": "ktlint: ktlint is an anti-bikeshedding Kotlin linter with a built-in format. In simple words, it checks our code styling and also helps us to format our code and make it better for understanding." }, { "code": null, "e": 25912, "s": 25886, "text": "Ktlitn can save your time" }, { "code": null, "e": 25997, "s": 25912, "text": "It can save your energy (because you don’t have to manually check your code styling)" }, { "code": null, "e": 26026, "s": 25997, "text": "It can simplify your process" }, { "code": null, "e": 26119, "s": 26026, "text": "Before this, let’s talk about some important things like ktlint breaks down into two things." }, { "code": null, "e": 26430, "s": 26119, "text": "linting tool: The lining tool is based on the kotlin standard style guide, and it will validate and make sure that your code adheres to that style guide.formatter: If ktlint detects that there are issues in your code you can then run the formatter and have ktlint try to automatically fix those issues for you." }, { "code": null, "e": 26584, "s": 26430, "text": "linting tool: The lining tool is based on the kotlin standard style guide, and it will validate and make sure that your code adheres to that style guide." }, { "code": null, "e": 26742, "s": 26584, "text": "formatter: If ktlint detects that there are issues in your code you can then run the formatter and have ktlint try to automatically fix those issues for you." }, { "code": null, "e": 27050, "s": 26742, "text": "Add ktlint to your project and more specifically we are going to be integrating ktlint with the ktlint Gradle plugin, this is a separate third party plugin on top of the basic ktlint tool and it makes working with ktlint very easy by providing out of the box Gradle tasks with, which to run ktlint commands." }, { "code": null, "e": 27202, "s": 27050, "text": "There are several options, but the easiest way is to make use of the ktlint-Gradle plugin which provides out of the box Gradle tasks for ktlint’s tools" }, { "code": null, "e": 27309, "s": 27202, "text": "For Adding the ktlint-gradle plugin just Add the ktlint-gradle plugin to your root-level build.gradle file" }, { "code": null, "e": 27432, "s": 27309, "text": "For Apply the plugin to subprojects just Apply the ktlint-gradle plugin to any Gradle modules that you would like to check" }, { "code": null, "e": 27554, "s": 27432, "text": "Verify added Gradle tasks as Check that ktlintCheck and ktlintFormat tasks have been added for your various build targets" }, { "code": null, "e": 27682, "s": 27554, "text": "If using a version of Gradle which supports the plugins DSL, you can add ktlint-gradle to your project with the following code:" }, { "code": null, "e": 27689, "s": 27682, "text": "Kotlin" }, { "code": "// root-level build.gradleplugins { id \"org.jlleitschuh.gradle.ktlint\" version \"7.1.0\"} // root-level build.gradlebuildscript { repositories { maven { url \"https://plugins.gradle.org/m2/\" } } dependencies { classpath \"org.jlleitschuh.gradle:ktlint-gradle:7.1.0\" }}", "e": 27975, "s": 27689, "text": null }, { "code": null, "e": 28148, "s": 27975, "text": "You’ll want to apply the ktlint-gradle plugin to the various modules within your project. You can do this using the allProjects{} block in the root-level build.gradle file." }, { "code": null, "e": 28155, "s": 28148, "text": "Kotlin" }, { "code": "// root-level build.gradleallprojects { ... apply plugin: \"org.jlleitschuh.gradle.ktlint\"}", "e": 28252, "s": 28155, "text": null }, { "code": null, "e": 28365, "s": 28252, "text": "Finally, you’ll want to test that the ktlint Gradle tasks are now available for use. You can do it in these ways" }, { "code": null, "e": 28437, "s": 28365, "text": "run ./gradlew tasks from the command line and look for any ktlint tasks" }, { "code": null, "e": 28492, "s": 28437, "text": "try to run ./gradlew ktlintCheck from the command line" }, { "code": null, "e": 28580, "s": 28492, "text": "use the Gradle tool window in IntelliJ or Android Studio to see if the tasks are listed" }, { "code": null, "e": 28672, "s": 28580, "text": "To actually check your code’s formatting, run the following command from the command line: " }, { "code": null, "e": 28694, "s": 28672, "text": "./gradlew ktlintCheck" }, { "code": null, "e": 28826, "s": 28694, "text": "This will run through your project and report back any errors which are found using the default ktlint-gradle plugin configuration." }, { "code": null, "e": 28951, "s": 28826, "text": "To automatically fix any errors which are reported by ktlintCheck, you can run the following command from the command line: " }, { "code": null, "e": 28974, "s": 28951, "text": "./gradlew ktlintFormat" }, { "code": null, "e": 29086, "s": 28974, "text": "This will attempt to auto-fix any errors and will report back any issues that could not automatically be fixed." }, { "code": null, "e": 29307, "s": 29086, "text": "When everything is correctly formatted, you should see something like the following image when you run ktlintCheck. ktlint is an open-source project that is maintained by Pinterest and you can find more info. Click here." }, { "code": null, "e": 29315, "s": 29307, "text": "clintra" }, { "code": null, "e": 29322, "s": 29315, "text": "Picked" }, { "code": null, "e": 29330, "s": 29322, "text": "Android" }, { "code": null, "e": 29337, "s": 29330, "text": "Kotlin" }, { "code": null, "e": 29345, "s": 29337, "text": "Android" }, { "code": null, "e": 29443, "s": 29345, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29452, "s": 29443, "text": "Comments" }, { "code": null, "e": 29465, "s": 29452, "text": "Old Comments" }, { "code": null, "e": 29504, "s": 29465, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 29546, "s": 29504, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 29579, "s": 29546, "text": "GridView in Android with Example" }, { "code": null, "e": 29652, "s": 29579, "text": "How to Change the Background Color After Clicking the Button in Android?" }, { "code": null, "e": 29690, "s": 29652, "text": "Android Listview in Java with Example" }, { "code": null, "e": 29709, "s": 29690, "text": "Android UI Layouts" }, { "code": null, "e": 29722, "s": 29709, "text": "Kotlin Array" }, { "code": null, "e": 29764, "s": 29722, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 29778, "s": 29764, "text": "Android Menus" } ]
Listing out directories and files in Python?
There are several ways to list the directories and files in python. One of the easiest ways to get all the files or directories from a particular path is by using os.listdir() method. Live Demo import os for x in os.listdir('.'): print(x) .pytest_cache 4forces.json annotation1.py asyncWrite.txt attribute_access.py background_process.py background_process2.py BeautifulSoup_script1.py bottle_exampl1.py bottole_test1.py build built-in_funct.py callable_objects1.py cars.csv classes_instance.py class_attributes.py class_attributes1.py code_gmplot.py config.py data1.json datafile.txt ...... Above code is showing a list of files and directories from a current working directory. If you want to list-files and directories from a particular directory, just pass the absolute pathname, import os for x in os.listdir(r'C:\Python\Python361\selenium'): print(x) geckodriver.log test1.py webdriver The result is similar to our folder hierarchy βˆ’ Above output is not giving any indication of whether our output is file or directory or link etc. If you want to find whether the entry is a file, directory etc., we can use os.path.isfile() as shown below: for x in os.listdir('.'): if os.path.isfile(x): print ('file-', x) elif os.path.isdir(x): print ('directory-', x) elif os.path.islink(x): print ('link-', x) else: print ('---', x) directory- .pytest_cache file- 4forces.json file- annotation1.py file- asyncWrite.txt file- attribute_access.py file- background_process.py file- background_process2.py file- BeautifulSoup_script1.py file- bottle_exampl1.py file- bottole_test1.py directory- build file- built-in_funct.py file- callable_objects1.py file- cars.csv file- classes_instance.py file- class_attributes.py file- class_attributes1.py file- code_gmplot.py file- config.py file- data1.json file- datafile.txt file- datawork file- data_pandas1.csv file- data_pandas1.xlsx file- debugger_pdb.py file- debugging_timeit1.py file- debugging_timeit2.py file- define_class.py file- directoryTreeStruc.py directory- dist directory- django directory- DLLs directory- Doc file- dynamic_array_implementation.py We can have one-liner using filter() to collect the files from a particular path βˆ’ list(filter(lambda x: os.path.isfile(x), os.listdir('.'))) ['4forces.json', 'annotation1.py', 'asyncWrite.txt', 'attribute_access.py', 'background_process.py', 'background_process2.py', 'BeautifulSoup_script1.py', 'bottle_exampl1.py', 'bottole_test1.py', 'built-in_funct.py', 'callable_objects1.py', 'cars.csv', 'classes_instance.py', 'class_attributes.py', 'class_attributes1.py', 'code_gmplot.py', 'config.py', 'data1.json', 'datafile.txt', 'datawork', 'data_pandas1.csv', 'data_pandas1.xlsx', 'debugger_pdb.py', 'debugging_timeit1.py', 'debugging_timeit2.py', 'define_class.py', 'directoryTreeStruc.py', 'dynamic_array_implementation.py', 'EDA_python1.py', 'EmpID.pickle', 'encapsulation.py', 'encapsulation1.py', 'enumerate1.py', 'eRecord.yaml', 'exampleCSV.csv', 'exampleCSV.py', 'exception1.py', 'exception2.py', 'exception2_1.py', 'exception3.py', 'exception3_1.py', 'exception4.py', 'exception5.py', 'exercise.txt', 'faking_files.py', 'fileone', 'files_background.py', 'finally.txt', 'finally_try_except.py', 'finally_try_except1.py', 'finally_try_except2.py', 'flatten&Ravel_Numpy1.py', 'functions_are_object_too.py', 'function_annotation.py', 'function_annotation1.py', 'function_annotation2.py', 'function_annotation3.py', 'function_annotation4.py', 'func_method.py', 'gc1.py', 'gmplot.py', 'gmplot1.py', 'gmplot11.py', 'gmplot2.py', 'google_search1.py', 'google_search_using_python.py', 'inheritance_example.py', 'inheriting from built-in.py', 'inheriting from built-in1.py', 'inheriting_attributes.py', 'inheriting_the_constructor.py', 'instance_data.py', 'instance_methods.py', 'interques1.py', 'invoice_file1.yaml', 'iterables1.py', 'iterables2.py', 'johnde_test1', 'jsonToPython.py', 'json_example1.json', 'json_example1.py', 'json_example2.py', 'json_script1_loadeRecord.py', 'LDE_EQUITIES_LAST_5_YEARS.csv', 'lib_request.py', 'LICENSE.txt', 'listing_files_directories.py', 'list_comprehension1.py', 'list_comprehension2.py', 'logging.log', 'logging1.py', 'magicmethods_operator_add.py', 'magicmethods_operator_add1.py', 'MainP.py', 'matplotlibsam1.py', 'metaclass1.py', 'metaclass2.py', 'metaclass3.py', 'metaclass4.py', 'method.py', 'methodOverloading.py', 'methodOverloading1.py', 'methodOverloading_defaultArgument.py', 'multiple_inheritance.py', 'multiple_inheritance1.py', 'myfile.py', 'my_map.html', 'NegativeAgeException.py', 'NegativeNumberException.py', 'NEWS.txt', 'object_lookup.py', 'OtherP.py', 'out.txt', 'pandas_script.py', 'pandas_script1.py', 'pandas_script2.py', 'pattern_matching1.py', 'pattern_matching2.py', 'pdb_example1.py', 'pdb_example2.py', 'pickle1.py', 'pickle2.py', 'pickled_list', 'pickle_dictionary1.py', 'pickle_list1.py', 'pickle_test1.py', 'placing_it_in_context.py', 'plotly.py', 'polymorphism_example.py', 'primeNum1.py', 'privateVar1.py', 'private_variable_naming.py', 'project_scrap1.py', 'pygame_script1.py', 'pygmap1.py', 'pygmap2.py', 'pygmaps.py', 'pymaps1.py', 'python.exe', 'python.pdb', 'python3.dll', 'python36.dll', 'python36.pdb', 'pythonw.exe', 'pythonw.pdb', 'python_tricks1.py', 'python_tricks2.py', 'replacing_string_to_number1.py', 'serialization web objects encoder.py', 'serialization web objects.py', 'serialization_JSON.py', 'serialization_pickle.py', 'serialization_pickle1.py', 'serialization_pickle2.py', 'serialization_pickle_storing_instances.py', 'serialization_pyaml_file1.py', 'serialization_pyaml_file2.py', 'serialization_pyaml_script1.py', 'serialization_unpickle.py', 'serialization_unpickle2.py', 'sets1.py', 'simpy1.py', 'simpy2.py', 'stocks_list.csv', 'storing_object1.py', 'storing_objects.py', 'termcolor1.py', 'test.py', 'test.txt', 'test1.py', 'test1.txt', 'test123.py', 'test2.json', 'test2.py', 'test2.txt', 'test_project1', 'test_sample1.py', 'test_sample2.py', 'test_sample3.py', 'test_sample4.py', 'tkinter1.py', 'tkinter2.py', 'tkinter_firstApp.py', 'try_except_block.py', 'tuple1.py', 'unpickle.py', 'unpickle3.py', 'unpickle_dict1.py', 'unpickle_list1.py', 'variable_arguments_list.py', 'variable_arguments_list1.py', 'vcruntime140.dll', 'winquality1.py', 'workfile1', '__init__ Constructor.py'] To get the list of directories using filter: list(filter(lambda x: os.path.isdir(x), os.listdir('.'))) ['.pytest_cache', 'build', 'dist', 'django', 'DLLs', 'Doc', 'etc', 'gmplot', 'gmplot-1.2.0', 'gmplot.egg-info', 'include', 'Lib', 'libs', 'networkP', 'Scripts', 'selenium', 'share', 'tcl', 'Tools', '__pycache__'] Below is a one-liner to find text files in a directory. Please note this does not descend into directory hierarchy but will just return the matching entries in the specified directory. list(filter(lambda x: x.endswith('.txt'), os.listdir('.'))) ['asyncWrite.txt', 'datafile.txt', 'exercise.txt', 'finally.txt', 'LICENSE.txt', 'NEWS.txt', 'out.txt', 'test.txt', 'test1.txt', 'test2.txt'] We can write above code using list comprehension too, >>> list(x for x in os.listdir('.') if x.endswith('.txt')) ['asyncWrite.txt', 'datafile.txt', 'exercise.txt', 'finally.txt', 'LICENSE.txt', 'NEWS.txt', 'out.txt', 'test.txt', 'test1.txt', 'test2.txt'] Another way is through regular expression βˆ’ import re fx = re.compile(r'\.(txt|py)') print(list(filter(fx.search, os.listdir('.')))) ['.pytest_cache', 'annotation1.py', 'asyncWrite.txt', 'attribute_access.py', 'background_process.py', 'background_process2.py', 'BeautifulSoup_script1.py', 'bottle_exampl1.py', 'bottole_test1.py', 'built-in_funct.py', 'callable_objects1.py', 'classes_instance.py', 'class_attributes.py', 'class_attributes1.py', 'code_gmplot.py', 'config.py', 'datafile.txt', 'debugger_pdb.py', 'debugging_timeit1.py', 'debugging_timeit2.py', 'define_class.py', 'directoryTreeStruc.py', 'dynamic_array_implementation.py', 'EDA_python1.py', 'encapsulation.py', 'encapsulation1.py', 'enumerate1.py', 'exampleCSV.py', 'exception1.py', 'exception2.py', 'exception2_1.py', 'exception3.py', 'exception3_1.py', 'exception4.py', 'exception5.py', 'exercise.txt', 'faking_files.py', 'files_background.py', 'finally.txt', 'finally_try_except.py', 'finally_try_except1.py', 'finally_try_except2.py', 'flatten&Ravel_Numpy1.py', 'functions_are_object_too.py', 'function_annotation.py', 'function_annotation1.py', 'function_annotation2.py', 'function_annotation3.py', 'function_annotation4.py', 'func_method.py', 'gc1.py', 'gmplot.py', 'gmplot1.py', 'gmplot11.py', 'gmplot2.py', 'google_search1.py', 'google_search_using_python.py', 'inheritance_example.py', 'inheriting from built-in.py', 'inheriting from built-in1.py', 'inheriting_attributes.py', 'inheriting_the_constructor.py', 'instance_data.py', 'instance_methods.py', 'interques1.py', 'iterables1.py', 'iterables2.py', 'jsonToPython.py', 'json_example1.py', 'json_example2.py', 'json_script1_loadeRecord.py', 'lib_request.py', 'LICENSE.txt', 'listing_files_directories.py', 'list_comprehension1.py', 'list_comprehension2.py', 'logging1.py', 'magicmethods_operator_add.py', 'magicmethods_operator_add1.py', 'MainP.py', 'matplotlibsam1.py', 'metaclass1.py', 'metaclass2.py', 'metaclass3.py', 'metaclass4.py', 'method.py', 'methodOverloading.py', 'methodOverloading1.py', 'methodOverloading_defaultArgument.py', 'multiple_inheritance.py', 'multiple_inheritance1.py', 'myfile.py', 'NegativeAgeException.py', 'NegativeNumberException.py', 'NEWS.txt', 'object_lookup.py', 'OtherP.py', 'out.txt', 'pandas_script.py', 'pandas_script1.py', 'pandas_script2.py', 'pattern_matching1.py', 'pattern_matching2.py', 'pdb_example1.py', 'pdb_example2.py', 'pickle1.py', 'pickle2.py', 'pickle_dictionary1.py', 'pickle_list1.py', 'pickle_test1.py', 'placing_it_in_context.py', 'plotly.py', 'polymorphism_example.py', 'primeNum1.py', 'privateVar1.py', 'private_variable_naming.py', 'project_scrap1.py', 'pygame_script1.py', 'pygmap1.py', 'pygmap2.py', 'pygmaps.py', 'pymaps1.py', 'python_tricks1.py', 'python_tricks2.py', 'replacing_string_to_number1.py', 'serialization web objects encoder.py', 'serialization web objects.py', 'serialization_JSON.py', 'serialization_pickle.py', 'serialization_pickle1.py', 'serialization_pickle2.py', 'serialization_pickle_storing_instances.py', 'serialization_pyaml_file1.py', 'serialization_pyaml_file2.py', 'serialization_pyaml_script1.py', 'serialization_unpickle.py', 'serialization_unpickle2.py', 'sets1.py', 'simpy1.py', 'simpy2.py', 'storing_object1.py', 'storing_objects.py', 'termcolor1.py', 'test.py', 'test.txt', 'test1.py', 'test1.txt', 'test123.py', 'test2.py', 'test2.txt', 'test_sample1.py', 'test_sample2.py', 'test_sample3.py', 'test_sample4.py', 'tkinter1.py', 'tkinter2.py', 'tkinter_firstApp.py', 'try_except_block.py', 'tuple1.py', 'unpickle.py', 'unpickle3.py', 'unpickle_dict1.py', 'unpickle_list1.py', 'variable_arguments_list.py', 'variable_arguments_list1.py', 'winquality1.py', '__init__ Constructor.py'] The os.walk() method generates the filenames in a directory tree. import os for root, dirs, files in os.walk(r'C:\Python\Python361\selenium'): for filename in files: print(filename geckodriver.log test1.py x_ignore_nofocus.so x_ignore_nofocus.so getAttribute.js isDisplayed.js
[ { "code": null, "e": 1130, "s": 1062, "text": "There are several ways to list the directories and files in python." }, { "code": null, "e": 1246, "s": 1130, "text": "One of the easiest ways to get all the files or directories from a particular path is by using os.listdir() method." }, { "code": null, "e": 1257, "s": 1246, "text": " Live Demo" }, { "code": null, "e": 1305, "s": 1257, "text": "import os\nfor x in os.listdir('.'):\n print(x)" }, { "code": null, "e": 1658, "s": 1305, "text": ".pytest_cache\n4forces.json\nannotation1.py\nasyncWrite.txt\nattribute_access.py\nbackground_process.py\nbackground_process2.py\nBeautifulSoup_script1.py\nbottle_exampl1.py\nbottole_test1.py\nbuild\nbuilt-in_funct.py\ncallable_objects1.py\ncars.csv\nclasses_instance.py\nclass_attributes.py\nclass_attributes1.py\ncode_gmplot.py\nconfig.py\ndata1.json\ndatafile.txt\n......" }, { "code": null, "e": 1850, "s": 1658, "text": "Above code is showing a list of files and directories from a current working directory. If you want to list-files and directories from a particular directory, just pass the absolute pathname," }, { "code": null, "e": 1926, "s": 1850, "text": "import os\nfor x in os.listdir(r'C:\\Python\\Python361\\selenium'):\n print(x)" }, { "code": null, "e": 1961, "s": 1926, "text": "geckodriver.log\ntest1.py\nwebdriver" }, { "code": null, "e": 2009, "s": 1961, "text": "The result is similar to our folder hierarchy βˆ’" }, { "code": null, "e": 2216, "s": 2009, "text": "Above output is not giving any indication of whether our output is file or directory or link etc. If you want to find whether the entry is a file, directory etc., we can use os.path.isfile() as shown below:" }, { "code": null, "e": 2408, "s": 2216, "text": "for x in os.listdir('.'):\n if os.path.isfile(x): print ('file-', x)\n elif os.path.isdir(x): print ('directory-', x)\n elif os.path.islink(x): print ('link-', x)\n else: print ('---', x)" }, { "code": null, "e": 3181, "s": 2408, "text": "directory- .pytest_cache\nfile- 4forces.json\nfile- annotation1.py\nfile- asyncWrite.txt\nfile- attribute_access.py\nfile- background_process.py\nfile- background_process2.py\nfile- BeautifulSoup_script1.py\nfile- bottle_exampl1.py\nfile- bottole_test1.py\ndirectory- build\nfile- built-in_funct.py\nfile- callable_objects1.py\nfile- cars.csv\nfile- classes_instance.py\nfile- class_attributes.py\nfile- class_attributes1.py\nfile- code_gmplot.py\nfile- config.py\nfile- data1.json\nfile- datafile.txt\nfile- datawork\nfile- data_pandas1.csv\nfile- data_pandas1.xlsx\nfile- debugger_pdb.py\nfile- debugging_timeit1.py\nfile- debugging_timeit2.py\nfile- define_class.py\nfile- directoryTreeStruc.py\ndirectory- dist\ndirectory- django\ndirectory- DLLs\ndirectory- Doc\nfile- dynamic_array_implementation.py" }, { "code": null, "e": 3264, "s": 3181, "text": "We can have one-liner using filter() to collect the files from a particular path βˆ’" }, { "code": null, "e": 3323, "s": 3264, "text": "list(filter(lambda x: os.path.isfile(x), os.listdir('.')))" }, { "code": null, "e": 7362, "s": 3323, "text": "['4forces.json', 'annotation1.py', 'asyncWrite.txt', 'attribute_access.py', 'background_process.py', 'background_process2.py', 'BeautifulSoup_script1.py', 'bottle_exampl1.py', 'bottole_test1.py', 'built-in_funct.py', 'callable_objects1.py', 'cars.csv', 'classes_instance.py', 'class_attributes.py', 'class_attributes1.py', 'code_gmplot.py', 'config.py', 'data1.json', 'datafile.txt', 'datawork', 'data_pandas1.csv', 'data_pandas1.xlsx', 'debugger_pdb.py', 'debugging_timeit1.py', 'debugging_timeit2.py', 'define_class.py', 'directoryTreeStruc.py', 'dynamic_array_implementation.py', 'EDA_python1.py', 'EmpID.pickle', 'encapsulation.py', 'encapsulation1.py', 'enumerate1.py', 'eRecord.yaml', 'exampleCSV.csv', 'exampleCSV.py', 'exception1.py', 'exception2.py', 'exception2_1.py', 'exception3.py', 'exception3_1.py', 'exception4.py', 'exception5.py', 'exercise.txt', 'faking_files.py', 'fileone', 'files_background.py', 'finally.txt', 'finally_try_except.py', 'finally_try_except1.py', 'finally_try_except2.py', 'flatten&Ravel_Numpy1.py', 'functions_are_object_too.py', 'function_annotation.py', 'function_annotation1.py', 'function_annotation2.py', 'function_annotation3.py', 'function_annotation4.py', 'func_method.py', 'gc1.py', 'gmplot.py', 'gmplot1.py', 'gmplot11.py', 'gmplot2.py', 'google_search1.py', 'google_search_using_python.py', 'inheritance_example.py', 'inheriting from built-in.py', 'inheriting from built-in1.py', 'inheriting_attributes.py', 'inheriting_the_constructor.py', 'instance_data.py', 'instance_methods.py', 'interques1.py', 'invoice_file1.yaml', 'iterables1.py', 'iterables2.py', 'johnde_test1', 'jsonToPython.py', 'json_example1.json', 'json_example1.py', 'json_example2.py', 'json_script1_loadeRecord.py', 'LDE_EQUITIES_LAST_5_YEARS.csv', 'lib_request.py', 'LICENSE.txt', 'listing_files_directories.py', 'list_comprehension1.py', 'list_comprehension2.py', 'logging.log', 'logging1.py', 'magicmethods_operator_add.py', 'magicmethods_operator_add1.py', 'MainP.py', 'matplotlibsam1.py', 'metaclass1.py', 'metaclass2.py', 'metaclass3.py', 'metaclass4.py', 'method.py', 'methodOverloading.py', 'methodOverloading1.py', 'methodOverloading_defaultArgument.py', 'multiple_inheritance.py', 'multiple_inheritance1.py', 'myfile.py', 'my_map.html', 'NegativeAgeException.py', 'NegativeNumberException.py', 'NEWS.txt', 'object_lookup.py', 'OtherP.py', 'out.txt', 'pandas_script.py', 'pandas_script1.py', 'pandas_script2.py', 'pattern_matching1.py', 'pattern_matching2.py', 'pdb_example1.py', 'pdb_example2.py', 'pickle1.py', 'pickle2.py', 'pickled_list', 'pickle_dictionary1.py', 'pickle_list1.py', 'pickle_test1.py', 'placing_it_in_context.py', 'plotly.py', 'polymorphism_example.py', 'primeNum1.py', 'privateVar1.py', 'private_variable_naming.py', 'project_scrap1.py', 'pygame_script1.py', 'pygmap1.py', 'pygmap2.py', 'pygmaps.py', 'pymaps1.py', 'python.exe', 'python.pdb', 'python3.dll', 'python36.dll', 'python36.pdb', 'pythonw.exe', 'pythonw.pdb', 'python_tricks1.py', 'python_tricks2.py', 'replacing_string_to_number1.py', 'serialization web objects encoder.py', 'serialization web objects.py', 'serialization_JSON.py', 'serialization_pickle.py', 'serialization_pickle1.py', 'serialization_pickle2.py', 'serialization_pickle_storing_instances.py', 'serialization_pyaml_file1.py', 'serialization_pyaml_file2.py', 'serialization_pyaml_script1.py', 'serialization_unpickle.py', 'serialization_unpickle2.py', 'sets1.py', 'simpy1.py', 'simpy2.py', 'stocks_list.csv', 'storing_object1.py', 'storing_objects.py', 'termcolor1.py', 'test.py', 'test.txt', 'test1.py', 'test1.txt', 'test123.py', 'test2.json', 'test2.py', 'test2.txt', 'test_project1', 'test_sample1.py', 'test_sample2.py', 'test_sample3.py', 'test_sample4.py', 'tkinter1.py', 'tkinter2.py', 'tkinter_firstApp.py', 'try_except_block.py', 'tuple1.py', 'unpickle.py', 'unpickle3.py', 'unpickle_dict1.py', 'unpickle_list1.py', 'variable_arguments_list.py', 'variable_arguments_list1.py', 'vcruntime140.dll', 'winquality1.py', 'workfile1', '__init__ Constructor.py']" }, { "code": null, "e": 7407, "s": 7362, "text": "To get the list of directories using filter:" }, { "code": null, "e": 7465, "s": 7407, "text": "list(filter(lambda x: os.path.isdir(x), os.listdir('.')))" }, { "code": null, "e": 7678, "s": 7465, "text": "['.pytest_cache', 'build', 'dist', 'django', 'DLLs', 'Doc', 'etc', 'gmplot', 'gmplot-1.2.0', 'gmplot.egg-info', 'include', 'Lib', 'libs', 'networkP', 'Scripts', 'selenium', 'share', 'tcl', 'Tools', '__pycache__']" }, { "code": null, "e": 7863, "s": 7678, "text": "Below is a one-liner to find text files in a directory. Please note this does not descend into directory hierarchy but will just return the matching entries in the specified directory." }, { "code": null, "e": 7923, "s": 7863, "text": "list(filter(lambda x: x.endswith('.txt'), os.listdir('.')))" }, { "code": null, "e": 8065, "s": 7923, "text": "['asyncWrite.txt', 'datafile.txt', 'exercise.txt', 'finally.txt', 'LICENSE.txt', 'NEWS.txt', 'out.txt', 'test.txt', 'test1.txt', 'test2.txt']" }, { "code": null, "e": 8119, "s": 8065, "text": "We can write above code using list comprehension too," }, { "code": null, "e": 8320, "s": 8119, "text": ">>> list(x for x in os.listdir('.') if x.endswith('.txt'))\n['asyncWrite.txt', 'datafile.txt', 'exercise.txt', 'finally.txt', 'LICENSE.txt', 'NEWS.txt', 'out.txt', 'test.txt', 'test1.txt', 'test2.txt']" }, { "code": null, "e": 8364, "s": 8320, "text": "Another way is through regular expression βˆ’" }, { "code": null, "e": 8453, "s": 8364, "text": "import re\nfx = re.compile(r'\\.(txt|py)')\nprint(list(filter(fx.search, os.listdir('.'))))" }, { "code": null, "e": 12026, "s": 8453, "text": "['.pytest_cache', 'annotation1.py', 'asyncWrite.txt', 'attribute_access.py', 'background_process.py', 'background_process2.py', 'BeautifulSoup_script1.py', 'bottle_exampl1.py', 'bottole_test1.py', 'built-in_funct.py', 'callable_objects1.py', 'classes_instance.py', 'class_attributes.py', 'class_attributes1.py', 'code_gmplot.py', 'config.py', 'datafile.txt', 'debugger_pdb.py', 'debugging_timeit1.py', 'debugging_timeit2.py', 'define_class.py', 'directoryTreeStruc.py', 'dynamic_array_implementation.py', 'EDA_python1.py', 'encapsulation.py', 'encapsulation1.py', 'enumerate1.py', 'exampleCSV.py', 'exception1.py', 'exception2.py', 'exception2_1.py', 'exception3.py', 'exception3_1.py', 'exception4.py', 'exception5.py', 'exercise.txt', 'faking_files.py', 'files_background.py', 'finally.txt', 'finally_try_except.py', 'finally_try_except1.py', 'finally_try_except2.py', 'flatten&Ravel_Numpy1.py', 'functions_are_object_too.py', 'function_annotation.py', 'function_annotation1.py', 'function_annotation2.py', 'function_annotation3.py', 'function_annotation4.py', 'func_method.py', 'gc1.py', 'gmplot.py', 'gmplot1.py', 'gmplot11.py', 'gmplot2.py', 'google_search1.py', 'google_search_using_python.py', 'inheritance_example.py', 'inheriting from built-in.py', 'inheriting from built-in1.py', 'inheriting_attributes.py', 'inheriting_the_constructor.py', 'instance_data.py', 'instance_methods.py', 'interques1.py', 'iterables1.py', 'iterables2.py', 'jsonToPython.py', 'json_example1.py', 'json_example2.py', 'json_script1_loadeRecord.py', 'lib_request.py', 'LICENSE.txt', 'listing_files_directories.py', 'list_comprehension1.py', 'list_comprehension2.py', 'logging1.py', 'magicmethods_operator_add.py', 'magicmethods_operator_add1.py', 'MainP.py', 'matplotlibsam1.py', 'metaclass1.py', 'metaclass2.py', 'metaclass3.py', 'metaclass4.py', 'method.py', 'methodOverloading.py', 'methodOverloading1.py', 'methodOverloading_defaultArgument.py', 'multiple_inheritance.py', 'multiple_inheritance1.py', 'myfile.py', 'NegativeAgeException.py', 'NegativeNumberException.py', 'NEWS.txt', 'object_lookup.py', 'OtherP.py', 'out.txt', 'pandas_script.py', 'pandas_script1.py', 'pandas_script2.py', 'pattern_matching1.py', 'pattern_matching2.py', 'pdb_example1.py', 'pdb_example2.py', 'pickle1.py', 'pickle2.py', 'pickle_dictionary1.py', 'pickle_list1.py', 'pickle_test1.py', 'placing_it_in_context.py', 'plotly.py', 'polymorphism_example.py', 'primeNum1.py', 'privateVar1.py', 'private_variable_naming.py', 'project_scrap1.py', 'pygame_script1.py', 'pygmap1.py', 'pygmap2.py', 'pygmaps.py', 'pymaps1.py', 'python_tricks1.py', 'python_tricks2.py', 'replacing_string_to_number1.py', 'serialization web objects encoder.py', 'serialization web objects.py', 'serialization_JSON.py', 'serialization_pickle.py', 'serialization_pickle1.py', 'serialization_pickle2.py', 'serialization_pickle_storing_instances.py', 'serialization_pyaml_file1.py', 'serialization_pyaml_file2.py', 'serialization_pyaml_script1.py', 'serialization_unpickle.py', 'serialization_unpickle2.py', 'sets1.py', 'simpy1.py', 'simpy2.py', 'storing_object1.py', 'storing_objects.py', 'termcolor1.py', 'test.py', 'test.txt', 'test1.py', 'test1.txt', 'test123.py', 'test2.py', 'test2.txt', 'test_sample1.py', 'test_sample2.py', 'test_sample3.py', 'test_sample4.py', 'tkinter1.py', 'tkinter2.py', 'tkinter_firstApp.py', 'try_except_block.py', 'tuple1.py', 'unpickle.py', 'unpickle3.py', 'unpickle_dict1.py', 'unpickle_list1.py', 'variable_arguments_list.py', 'variable_arguments_list1.py', 'winquality1.py', '__init__ Constructor.py']" }, { "code": null, "e": 12092, "s": 12026, "text": "The os.walk() method generates the filenames in a directory tree." }, { "code": null, "e": 12216, "s": 12092, "text": "import os\nfor root, dirs, files in os.walk(r'C:\\Python\\Python361\\selenium'):\n for filename in files:\n print(filename" }, { "code": null, "e": 12312, "s": 12216, "text": "geckodriver.log\ntest1.py\nx_ignore_nofocus.so\nx_ignore_nofocus.so\ngetAttribute.js\nisDisplayed.js" } ]
Byte Struct in C# - GeeksforGeeks
03 Jan, 2020 In C#, Byte Struct is used to represent 8-bit unsigned integers. The Byte is an immutable value type and the range of Byte is from 0 to 255. This class allows you to create Byte data types and you can perform mathematical and bitwise operations on them like addition, subtraction, multiplication, division, XOR, AND etc. Example: // C# program to illustrate the concept// of MaxValue and MinValue fields in Byteusing System; public class GFG { // Main method static public void Main() { // Display the minimum and // the maximum value of Byte Console.WriteLine("The minimum value "+ "of Byte: {0}", Byte.MinValue); Console.WriteLine("The maximum value "+ "of Byte: {0}", Byte.MaxValue); }} The minimum value of Byte: 0 The maximum value of Byte: 255 Example: // C# program to illustrate the concept// of CompareTo(Byte) method in Byteusing System; public class GFG { // Main method static public void Main() { // val1, val2, and val3 are of byte type byte val1 = 32; byte val2 = 40; byte val3 = 10; // Display the comparison // Using CompareTo(Byte) method Console.WriteLine("Comparison 1: {0}", val1.CompareTo(val2)); Console.WriteLine("Comparison 2: {0}", val2.CompareTo(val3)); Console.WriteLine("Comparison 3: {0}", val3.CompareTo(val3)); Console.WriteLine("Comparison 4: {0}", val1.CompareTo(val3)); }} Comparison 1: -8 Comparison 2: 30 Comparison 3: 0 Comparison 4: 22 Reference: https://docs.microsoft.com/en-us/dotnet/api/system.byte?view=netframework-4.7.2 Akanksha_Rai CSharp-Byte-Struct C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments C# Dictionary with examples Difference between Ref and Out keywords in C# Introduction to .NET Framework Extension Method in C# C# | String.IndexOf( ) Method | Set - 1 C# | Abstract Classes C# | Delegates Top 50 C# Interview Questions & Answers Different ways to sort an array in descending order in C# C# | Replace() Method
[ { "code": null, "e": 23874, "s": 23846, "text": "\n03 Jan, 2020" }, { "code": null, "e": 24195, "s": 23874, "text": "In C#, Byte Struct is used to represent 8-bit unsigned integers. The Byte is an immutable value type and the range of Byte is from 0 to 255. This class allows you to create Byte data types and you can perform mathematical and bitwise operations on them like addition, subtraction, multiplication, division, XOR, AND etc." }, { "code": null, "e": 24204, "s": 24195, "text": "Example:" }, { "code": "// C# program to illustrate the concept// of MaxValue and MinValue fields in Byteusing System; public class GFG { // Main method static public void Main() { // Display the minimum and // the maximum value of Byte Console.WriteLine(\"The minimum value \"+ \"of Byte: {0}\", Byte.MinValue); Console.WriteLine(\"The maximum value \"+ \"of Byte: {0}\", Byte.MaxValue); }}", "e": 24643, "s": 24204, "text": null }, { "code": null, "e": 24704, "s": 24643, "text": "The minimum value of Byte: 0\nThe maximum value of Byte: 255\n" }, { "code": null, "e": 24713, "s": 24704, "text": "Example:" }, { "code": "// C# program to illustrate the concept// of CompareTo(Byte) method in Byteusing System; public class GFG { // Main method static public void Main() { // val1, val2, and val3 are of byte type byte val1 = 32; byte val2 = 40; byte val3 = 10; // Display the comparison // Using CompareTo(Byte) method Console.WriteLine(\"Comparison 1: {0}\", val1.CompareTo(val2)); Console.WriteLine(\"Comparison 2: {0}\", val2.CompareTo(val3)); Console.WriteLine(\"Comparison 3: {0}\", val3.CompareTo(val3)); Console.WriteLine(\"Comparison 4: {0}\", val1.CompareTo(val3)); }}", "e": 25454, "s": 24713, "text": null }, { "code": null, "e": 25522, "s": 25454, "text": "Comparison 1: -8\nComparison 2: 30\nComparison 3: 0\nComparison 4: 22\n" }, { "code": null, "e": 25533, "s": 25522, "text": "Reference:" }, { "code": null, "e": 25613, "s": 25533, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.byte?view=netframework-4.7.2" }, { "code": null, "e": 25626, "s": 25613, "text": "Akanksha_Rai" }, { "code": null, "e": 25645, "s": 25626, "text": "CSharp-Byte-Struct" }, { "code": null, "e": 25648, "s": 25645, "text": "C#" }, { "code": null, "e": 25746, "s": 25648, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25755, "s": 25746, "text": "Comments" }, { "code": null, "e": 25768, "s": 25755, "text": "Old Comments" }, { "code": null, "e": 25796, "s": 25768, "text": "C# Dictionary with examples" }, { "code": null, "e": 25842, "s": 25796, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 25873, "s": 25842, "text": "Introduction to .NET Framework" }, { "code": null, "e": 25896, "s": 25873, "text": "Extension Method in C#" }, { "code": null, "e": 25936, "s": 25896, "text": "C# | String.IndexOf( ) Method | Set - 1" }, { "code": null, "e": 25958, "s": 25936, "text": "C# | Abstract Classes" }, { "code": null, "e": 25973, "s": 25958, "text": "C# | Delegates" }, { "code": null, "e": 26013, "s": 25973, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 26071, "s": 26013, "text": "Different ways to sort an array in descending order in C#" } ]
Merge JavaScript objects with the same key value and count them
Suppose, we have an array of objects like this βˆ’ const arr = [{ "value": 10, "id": "111", "name": "BlackCat", }, { "value": 10, "id": "111", "name": "BlackCat", }, { "value": 15, "id": "777", "name": "WhiteCat", }]; We are required to write a JavaScript function that takes in one such array. The function should then merge all those objects together that have the common value for "id" property. Therefore, for the above array, the output should look like βˆ’ const output = [{ "value": 10, "id": "111", "name": "BlackCat", "count": 2, }, { "value": 15, "id": "777", "name": "WhiteCat", "count": 1, }] const arr = [{ "value": 10, "id": "111", "name": "BlackCat", }, { "value": 10, "id": "111", "name": "BlackCat", }, { "value": 15, "id": "777", "name": "WhiteCat", }]; const combinedItems = (arr = []) => { const res = arr.reduce((acc, obj) => { let found = false; for (let i = 0; i < acc.length; i++) { if (acc[i].id === obj.id) { found = true; acc[i].count++; }; } if (!found) { obj.count = 1; acc.push(obj); } return acc; }, []); return res; } console.log(combinedItems(arr)); And the output in the console will be βˆ’ [ { value: 10, id: '111', name: 'BlackCat', count: 2 }, { value: 15, id: '777', name: 'WhiteCat', count: 1 } ]
[ { "code": null, "e": 1111, "s": 1062, "text": "Suppose, we have an array of objects like this βˆ’" }, { "code": null, "e": 1308, "s": 1111, "text": "const arr = [{\n \"value\": 10,\n \"id\": \"111\",\n \"name\": \"BlackCat\",\n}, {\n \"value\": 10,\n \"id\": \"111\",\n \"name\":\n \"BlackCat\",\n}, {\n \"value\": 15,\n \"id\": \"777\",\n \"name\": \"WhiteCat\",\n}];" }, { "code": null, "e": 1385, "s": 1308, "text": "We are required to write a JavaScript function that takes in one such array." }, { "code": null, "e": 1489, "s": 1385, "text": "The function should then merge all those objects together that have the common value for \"id\" property." }, { "code": null, "e": 1551, "s": 1489, "text": "Therefore, for the above array, the output should look like βˆ’" }, { "code": null, "e": 1717, "s": 1551, "text": "const output = [{\n \"value\": 10,\n \"id\": \"111\",\n \"name\": \"BlackCat\",\n \"count\": 2,\n}, {\n \"value\": 15,\n \"id\": \"777\",\n \"name\": \"WhiteCat\",\n \"count\": 1,\n}]" }, { "code": null, "e": 2327, "s": 1717, "text": "const arr = [{\n \"value\": 10,\n \"id\": \"111\",\n \"name\": \"BlackCat\",\n}, {\n \"value\": 10,\n \"id\": \"111\",\n \"name\": \"BlackCat\",\n}, {\n \"value\": 15,\n \"id\": \"777\",\n \"name\": \"WhiteCat\",\n}];\nconst combinedItems = (arr = []) => {\n const res = arr.reduce((acc, obj) => {\n let found = false;\n for (let i = 0; i < acc.length; i++) {\n if (acc[i].id === obj.id) {\n found = true;\n acc[i].count++;\n };\n }\n if (!found) {\n obj.count = 1;\n acc.push(obj);\n }\n return acc;\n }, []);\n return res;\n}\nconsole.log(combinedItems(arr));" }, { "code": null, "e": 2367, "s": 2327, "text": "And the output in the console will be βˆ’" }, { "code": null, "e": 2484, "s": 2367, "text": "[\n { value: 10, id: '111', name: 'BlackCat', count: 2 },\n { value: 15, id: '777', name: 'WhiteCat', count: 1 }\n]" } ]
How to make hollow square marks with Matplotlib in Python?
To make hollow square marks with matplotlib, we can use marker 'ks', markerfacecolor='none', markersize=15, and markeredgecolor=red. Creat x and y data points using numpy. Creat x and y data points using numpy. Create a figure or activate an existing figure, add an axes to the figure as part of a subplot arrangement. Create a figure or activate an existing figure, add an axes to the figure as part of a subplot arrangement. Plot x and y data points using plot() method. To make hollow square marks, we can use marker "ks" and markerfacecolor="none", markersize="15" and markeredge color="red". Plot x and y data points using plot() method. To make hollow square marks, we can use marker "ks" and markerfacecolor="none", markersize="15" and markeredge color="red". To display the figure, use show() method. To display the figure, use show() method. import numpy as np from matplotlib import pyplot as plt plt.rcParams["figure.figsize"] = [7.00, 3.50] plt.rcParams["figure.autolayout"] = True x = np.linspace(-2, 2, 10) y = np.sin(x) fig = plt.figure() ax1 = fig.add_subplot(111) ax1.plot(x, y, 'ks', markerfacecolor='none', ms=15, markeredgecolor='red') plt.show()
[ { "code": null, "e": 1195, "s": 1062, "text": "To make hollow square marks with matplotlib, we can use marker 'ks', markerfacecolor='none', markersize=15, and markeredgecolor=red." }, { "code": null, "e": 1234, "s": 1195, "text": "Creat x and y data points using numpy." }, { "code": null, "e": 1273, "s": 1234, "text": "Creat x and y data points using numpy." }, { "code": null, "e": 1381, "s": 1273, "text": "Create a figure or activate an existing figure, add an axes to the figure as part of a subplot arrangement." }, { "code": null, "e": 1489, "s": 1381, "text": "Create a figure or activate an existing figure, add an axes to the figure as part of a subplot arrangement." }, { "code": null, "e": 1659, "s": 1489, "text": "Plot x and y data points using plot() method. To make hollow square marks, we can use marker \"ks\" and markerfacecolor=\"none\", markersize=\"15\" and markeredge color=\"red\"." }, { "code": null, "e": 1829, "s": 1659, "text": "Plot x and y data points using plot() method. To make hollow square marks, we can use marker \"ks\" and markerfacecolor=\"none\", markersize=\"15\" and markeredge color=\"red\"." }, { "code": null, "e": 1871, "s": 1829, "text": "To display the figure, use show() method." }, { "code": null, "e": 1913, "s": 1871, "text": "To display the figure, use show() method." }, { "code": null, "e": 2229, "s": 1913, "text": "import numpy as np\nfrom matplotlib import pyplot as plt\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\nx = np.linspace(-2, 2, 10)\ny = np.sin(x)\nfig = plt.figure()\nax1 = fig.add_subplot(111)\nax1.plot(x, y, 'ks', markerfacecolor='none', ms=15, markeredgecolor='red')\nplt.show()" } ]
Django - Form Processing
Creating forms in Django, is really similar to creating a model. Here again, we just need to inherit from Django class and the class attributes will be the form fields. Let's add a forms.py file in myapp folder to contain our app forms. We will create a login form. myapp/forms.py #-*- coding: utf-8 -*- from django import forms class LoginForm(forms.Form): user = forms.CharField(max_length = 100) password = forms.CharField(widget = forms.PasswordInput()) As seen above, the field type can take "widget" argument for html rendering; in our case, we want the password to be hidden, not displayed. Many others widget are present in Django: DateInput for dates, CheckboxInput for checkboxes, etc. There are two kinds of HTTP requests, GET and POST. In Django, the request object passed as parameter to your view has an attribute called "method" where the type of the request is set, and all data passed via POST can be accessed via the request.POST dictionary. Let's create a login view in our myapp/views.py βˆ’ #-*- coding: utf-8 -*- from myapp.forms import LoginForm def login(request): username = "not logged in" if request.method == "POST": #Get the posted form MyLoginForm = LoginForm(request.POST) if MyLoginForm.is_valid(): username = MyLoginForm.cleaned_data['username'] else: MyLoginForm = Loginform() return render(request, 'loggedin.html', {"username" : username}) The view will display the result of the login form posted through the loggedin.html. To test it, we will first need the login form template. Let's call it login.html. <html> <body> <form name = "form" action = "{% url "myapp.views.login" %}" method = "POST" >{% csrf_token %} <div style = "max-width:470px;"> <center> <input type = "text" style = "margin-left:20%;" placeholder = "Identifiant" name = "username" /> </center> </div> <br> <div style = "max-width:470px;"> <center> <input type = "password" style = "margin-left:20%;" placeholder = "password" name = "password" /> </center> </div> <br> <div style = "max-width:470px;"> <center> <button style = "border:0px; background-color:#4285F4; margin-top:8%; height:35px; width:80%;margin-left:19%;" type = "submit" value = "Login" > <strong>Login</strong> </button> </center> </div> </form> </body> </html> The template will display a login form and post the result to our login view above. You have probably noticed the tag in the template, which is just to prevent Cross-site Request Forgery (CSRF) attack on your site. {% csrf_token %} Once we have the login template, we need the loggedin.html template that will be rendered after form treatment. <html> <body> You are : <strong>{{username}}</strong> </body> </html> Now, we just need our pair of URLs to get started: myapp/urls.py from django.conf.urls import patterns, url from django.views.generic import TemplateView urlpatterns = patterns('myapp.views', url(r'^connection/',TemplateView.as_view(template_name = 'login.html')), url(r'^login/', 'login', name = 'login')) When accessing "/myapp/connection", we will get the following login.html template rendered βˆ’ On the form post, the form is valid. In our case make sure to fill the two fields and you will get βˆ’ In case your username is polo, and you forgot the password. You will get the following message βˆ’ In the above example, when validating the form βˆ’ MyLoginForm.is_valid() We only used Django self-form validation engine, in our case just making sure the fields are required. Now let’s try to make sure the user trying to login is present in our DB as Dreamreal entry. For this, change the myapp/forms.py to βˆ’ #-*- coding: utf-8 -*- from django import forms from myapp.models import Dreamreal class LoginForm(forms.Form): user = forms.CharField(max_length = 100) password = forms.CharField(widget = forms.PasswordInput()) def clean_message(self): username = self.cleaned_data.get("username") dbuser = Dreamreal.objects.filter(name = username) if not dbuser: raise forms.ValidationError("User does not exist in our db!") return username Now, after calling the "is_valid" method, we will get the correct output, only if the user is in our database. If you want to check a field of your form, just add a method starting by "clean_" then your field name to your form class. Raising a forms.ValidationError is important. 39 Lectures 3.5 hours John Elder 36 Lectures 2.5 hours John Elder 28 Lectures 2 hours John Elder 20 Lectures 1 hours John Elder 35 Lectures 3 hours John Elder 79 Lectures 10 hours Rathan Kumar Print Add Notes Bookmark this page
[ { "code": null, "e": 2311, "s": 2045, "text": "Creating forms in Django, is really similar to creating a model. Here again, we just need to inherit from Django class and the class attributes will be the form fields. Let's add a forms.py file in myapp folder to contain our app forms. We will create a login form." }, { "code": null, "e": 2326, "s": 2311, "text": "myapp/forms.py" }, { "code": null, "e": 2510, "s": 2326, "text": "#-*- coding: utf-8 -*-\nfrom django import forms\n\nclass LoginForm(forms.Form):\n user = forms.CharField(max_length = 100)\n password = forms.CharField(widget = forms.PasswordInput())" }, { "code": null, "e": 2748, "s": 2510, "text": "As seen above, the field type can take \"widget\" argument for html rendering; in our case, we want the password to be hidden, not displayed. Many others widget are present in Django: DateInput for dates, CheckboxInput for checkboxes, etc." }, { "code": null, "e": 3012, "s": 2748, "text": "There are two kinds of HTTP requests, GET and POST. In Django, the request object passed as parameter to your view has an attribute called \"method\" where the type of the request is set, and all data passed via POST can be accessed via the request.POST dictionary." }, { "code": null, "e": 3062, "s": 3012, "text": "Let's create a login view in our myapp/views.py βˆ’" }, { "code": null, "e": 3486, "s": 3062, "text": "#-*- coding: utf-8 -*-\nfrom myapp.forms import LoginForm\n\ndef login(request):\n username = \"not logged in\"\n \n if request.method == \"POST\":\n #Get the posted form\n MyLoginForm = LoginForm(request.POST)\n \n if MyLoginForm.is_valid():\n username = MyLoginForm.cleaned_data['username']\n else:\n MyLoginForm = Loginform()\n\t\t\n return render(request, 'loggedin.html', {\"username\" : username})" }, { "code": null, "e": 3653, "s": 3486, "text": "The view will display the result of the login form posted through the loggedin.html. To test it, we will first need the login form template. Let's call it login.html." }, { "code": null, "e": 4764, "s": 3653, "text": "<html>\n <body>\n \n <form name = \"form\" action = \"{% url \"myapp.views.login\" %}\" \n method = \"POST\" >{% csrf_token %}\n \n <div style = \"max-width:470px;\">\n <center> \n <input type = \"text\" style = \"margin-left:20%;\" \n placeholder = \"Identifiant\" name = \"username\" />\n </center>\n </div>\n\t\t\t\n <br>\n \n <div style = \"max-width:470px;\">\n <center>\n <input type = \"password\" style = \"margin-left:20%;\" \n placeholder = \"password\" name = \"password\" />\n </center>\n </div>\n\t\t\t\n <br>\n \n <div style = \"max-width:470px;\">\n <center> \n \n <button style = \"border:0px; background-color:#4285F4; margin-top:8%;\n height:35px; width:80%;margin-left:19%;\" type = \"submit\" \n value = \"Login\" >\n <strong>Login</strong>\n </button>\n \n </center>\n </div>\n \n </form>\n \n </body>\n</html>" }, { "code": null, "e": 4979, "s": 4764, "text": "The template will display a login form and post the result to our login view above. You have probably noticed the tag in the template, which is just to prevent Cross-site Request Forgery (CSRF) attack on your site." }, { "code": null, "e": 4997, "s": 4979, "text": "{% csrf_token %}\n" }, { "code": null, "e": 5109, "s": 4997, "text": "Once we have the login template, we need the loggedin.html template that will be rendered after form treatment." }, { "code": null, "e": 5199, "s": 5109, "text": "<html>\n \n <body>\n You are : <strong>{{username}}</strong>\n </body>\n \n</html>" }, { "code": null, "e": 5264, "s": 5199, "text": "Now, we just need our pair of URLs to get started: myapp/urls.py" }, { "code": null, "e": 5513, "s": 5264, "text": "from django.conf.urls import patterns, url\nfrom django.views.generic import TemplateView\n\nurlpatterns = patterns('myapp.views',\n url(r'^connection/',TemplateView.as_view(template_name = 'login.html')),\n url(r'^login/', 'login', name = 'login'))" }, { "code": null, "e": 5606, "s": 5513, "text": "When accessing \"/myapp/connection\", we will get the following login.html template rendered βˆ’" }, { "code": null, "e": 5707, "s": 5606, "text": "On the form post, the form is valid. In our case make sure to fill the two fields and you will get βˆ’" }, { "code": null, "e": 5804, "s": 5707, "text": "In case your username is polo, and you forgot the password. You will get the following message βˆ’" }, { "code": null, "e": 5853, "s": 5804, "text": "In the above example, when validating the form βˆ’" }, { "code": null, "e": 5877, "s": 5853, "text": "MyLoginForm.is_valid()\n" }, { "code": null, "e": 6114, "s": 5877, "text": "We only used Django self-form validation engine, in our case just making sure the fields are required. Now let’s try to make sure the user trying to login is present in our DB as Dreamreal entry. For this, change the myapp/forms.py to βˆ’" }, { "code": null, "e": 6591, "s": 6114, "text": "#-*- coding: utf-8 -*-\nfrom django import forms\nfrom myapp.models import Dreamreal\n\nclass LoginForm(forms.Form):\n user = forms.CharField(max_length = 100)\n password = forms.CharField(widget = forms.PasswordInput())\n\n def clean_message(self):\n username = self.cleaned_data.get(\"username\")\n dbuser = Dreamreal.objects.filter(name = username)\n \n if not dbuser:\n raise forms.ValidationError(\"User does not exist in our db!\")\n return username" }, { "code": null, "e": 6871, "s": 6591, "text": "Now, after calling the \"is_valid\" method, we will get the correct output, only if the user is in our database. If you want to check a field of your form, just add a method starting by \"clean_\" then your field name to your form class. Raising a forms.ValidationError is important." }, { "code": null, "e": 6906, "s": 6871, "text": "\n 39 Lectures \n 3.5 hours \n" }, { "code": null, "e": 6918, "s": 6906, "text": " John Elder" }, { "code": null, "e": 6953, "s": 6918, "text": "\n 36 Lectures \n 2.5 hours \n" }, { "code": null, "e": 6965, "s": 6953, "text": " John Elder" }, { "code": null, "e": 6998, "s": 6965, "text": "\n 28 Lectures \n 2 hours \n" }, { "code": null, "e": 7010, "s": 6998, "text": " John Elder" }, { "code": null, "e": 7043, "s": 7010, "text": "\n 20 Lectures \n 1 hours \n" }, { "code": null, "e": 7055, "s": 7043, "text": " John Elder" }, { "code": null, "e": 7088, "s": 7055, "text": "\n 35 Lectures \n 3 hours \n" }, { "code": null, "e": 7100, "s": 7088, "text": " John Elder" }, { "code": null, "e": 7134, "s": 7100, "text": "\n 79 Lectures \n 10 hours \n" }, { "code": null, "e": 7148, "s": 7134, "text": " Rathan Kumar" }, { "code": null, "e": 7155, "s": 7148, "text": " Print" }, { "code": null, "e": 7166, "s": 7155, "text": " Add Notes" } ]
Deep Q reinforcement learning (DQN) | Towards Data Science
Q learning is a method that has already existed for a long time in the reinforcement learning community. However, huge progress in this field was achieved recently by using Neural networks in combination with Q learning. This was the birth of so-called Deep Q learning. The full potential of this method was seen in 2013 when google presented to the world their DQN agent playing atari breakout. For me, this was the first contact with the field and I immediately got interested in it. Other reinforcement learning methods are policy gradient methods and actor critic methods. Actor critic methods are a hybrid between Q Learning and Policy gradient methods. In reinforcement learning, we have an environment, in which an agent is doing actions. The environment then returns a reward and a new state. The reward, the agent receives also depends on the state he is actually in. So he/she should learn to adapt the actions to the actual state. The environment we are going to use is the CartPole-v0 environment, which is authored by OpenAI. We can easily use it in python. It is a pretty simple environment and also very simple to solve for most deep reinforcement learning algorithms. Therefore I use it every time I write a new Reinforcement learning script to test if I implemented everything correctly. We start by importing and testing openai gym. If you haven’t installed it yet, you can install it by typing: pip3 install gym We then write a script to test our gym environment. We let the agent perform random actions, just to see, that everything works. The goal of the agent is to balance the stick for as long as possible. It fails and the episode get’s terminated, if the stick diverges 15 degrees from being upright in both directions. The actions the agent can take to achieve its goal are: move left (0) move right (1) Reward is given in the following way: +1 for every step, that the stick is upright The state/observation is a list of 4 values: Consider the following scenario. Our chicken is hungry. It has two actions it can perform. It can either eat or write. Since it is hungry, the better choice would be to eat and this indeed would give it more reward. But reward is given after an action is performed, so how is it supposed to know. In this scenario, the action value(or Q value) can help us. This Q value depends on the state and and a possible action. Q(s, a) then returns us the value of performing an action, given the state. So the chicken should perform the action, that has the highest q value! The Q value is defined by the following equation: This equation simply means, that for a given state, the value of an action is the immediate reward after the action was performed plus the (discounted) highest Q value of the next state. Gamma (Ξ³) is actually the discount factor and it accounts for the uncertainty in future rewards. Ξ³ is usually above 0.9 and smaller than 1. A low gamma leads to the agent being more focused on immediate reward, while a high gamma leads to the agent being more focused on high future rewards. We have seen the exact definition of the Q value and I also told you, that we are going to use a neural network to approximate it. So we want to bring the approximated Q value of the network as close as possible to the mathematical definition. To achieve this goal, we use the Neural networks ability to minimize a loss function. We call the Q value of the actual time step β€œprediction” and the term including the Q value of the next state target. The loss function we used is simply the mean squared error loss. With temporal difference learning, we can train our agent at every time step. If we would let our agent greedily exploit the strategy, which it thinks has the highest Q value, it is very likely, that there exists a better strategy. The agent will never be able to explore this strategy and therefore never see the high reward associated with it. So in the beginning, we let our do random actions and over time decrease it’s probability of taking random actions. This process is called Epsiolon (Ξ΅) greedy action selection. Deep Q learning does not especially well unless we enhance it by adding experience replay. For this, we build a memory and store all states, actions and rewards in it. When training, we retrieve a random batch from our memory and train on it. This means, that the agent will most likely not be trained on the last time step it took. The following code implements a ReplayBuffer class, which is responsible for storing and giving out random batches of memory. For each timestep we store: (state, action, reward, next_state, done). done is a terminal flag and is 0 during an episode and 1 when the episode ends. Instead of presenting pseudo code, I decided to present you the python code of the main file, because it is easier to understand, if you know python. We can adjust many hyperparameter, which we pass into the constructor of the agent: agent = DQAgent(learning_rate=0.00025, gamma=0.90, batch_size=32, state_len=len(env.reset()), n_actions = env.action_space.n, mem_size = 1000000, min_memory_for_training=1000, epsilon=1,epsilon_dec=0.99, epsilon_min = 0.02) Learning rate: learning rate of the neural network. A high value leads to the agent learning fast, but can also lead to sub-optimal behavior in complex environments. Gamma: Ξ³ is usually above 0.9 and smaller than 1. A low gamma leads to the agent being more focused on immediate reward, while a high gamma leads to the agent being more focused on high future rewards. Batch size: The number of timesteps given to the neural network to perform minibatch gradient descent. High number of batches stabilizes learning, but can also lead to stagnation. Min memory for training: Number of steps, before the learning process begins. A decent number prevents the network from overfitting to the first few training samples. Epsilon: The start value of epsilon. 1 means agent perform only random actions (exploration) in the beginning and 0 means it would start performing no random actions(exploitation). Epsilon dec: The factor by which epsilon is multiplied after each time step to decrease it. It should be bigger than 0.99 and smaller than 1. Epsilon min: The minimal value for epsilon. Epsilon will not get decreased if it would fall below this value. It is very important to have a little exploration at any time, so that the agent can continue to learn. And now the whole code of our agent: Let’s discuss this code line: target = rewards_batch + torch.mul(self.gamma* self.q(new_states_batch).max(axis = 1).values, (1 - dones_batch)) It calculates the TD target. Lets’s assume our batch size is 5. Then the calculation could be looking as follows: We do the max operation, because we want to look at the action with the highest Q value. And Let’s also look at the following code line: prediction = self.q.forward(states_batch).gather(1,actions_batch.unsqueeze(1)).squeeze(1) It calculates the prediction. With a batch size of 5, this could look the following way: We select the q values from the actions, the agent actually took. Now it’s time to actually test our algorithm. We test it with our CartPole-v0 environment. After 100 episodes, the agent has managed to beat the environment and almost always achieves the highest score. To improve our deep Q learning algorithm even further, we can choose to have separate prediction and target values. This is also called double Q learning. The actions will be predicted with the prediction network. Backpropagation only happens in the prediction network. The parameters of the prediction network get copied every few iterations to the target network. How long the parameters of the target network remain β€œfrozen” is also a hyperparameter. We freeze the target network, because then the prediction and the target are less correlated. This helps in the learning process Now we have a little fun and test our algorithm with the openai environment β€œLunarLander-v2”. You can find a list of the hyperparamters which I have used below. Learning rate: 0.001 Gamma: 0.99 Batch size: 64 Min memory for training: 1000000 Epsilon: 1 Epsilon dec: 0.995 Epsilon min: 0.02 Frozen_iterations: 6 The following GIF was taken at episode 729. The agent does very well at landing that lander. And the learning curve looks like this. Note that it was smoothed by a 20 episode moving average. The main file: Code for the agent: towardsdatascience.com towardsdatascience.com towardsdatascience.com Linkedinhttps://www.linkedin.com/in/vincent-m%C3%BCller-6b3542214/Facebookhttps://www.facebook.com/profile.php?id=100072095823739Twitterhttps://twitter.com/Vincent02770108Mediumhttps://medium.com/@Vincent.MuellerBecome medium member and support me (part of your membership fees go directly to me)https://medium.com/@Vincent.Mueller/membership
[ { "code": null, "e": 657, "s": 171, "text": "Q learning is a method that has already existed for a long time in the reinforcement learning community. However, huge progress in this field was achieved recently by using Neural networks in combination with Q learning. This was the birth of so-called Deep Q learning. The full potential of this method was seen in 2013 when google presented to the world their DQN agent playing atari breakout. For me, this was the first contact with the field and I immediately got interested in it." }, { "code": null, "e": 830, "s": 657, "text": "Other reinforcement learning methods are policy gradient methods and actor critic methods. Actor critic methods are a hybrid between Q Learning and Policy gradient methods." }, { "code": null, "e": 1113, "s": 830, "text": "In reinforcement learning, we have an environment, in which an agent is doing actions. The environment then returns a reward and a new state. The reward, the agent receives also depends on the state he is actually in. So he/she should learn to adapt the actions to the actual state." }, { "code": null, "e": 1476, "s": 1113, "text": "The environment we are going to use is the CartPole-v0 environment, which is authored by OpenAI. We can easily use it in python. It is a pretty simple environment and also very simple to solve for most deep reinforcement learning algorithms. Therefore I use it every time I write a new Reinforcement learning script to test if I implemented everything correctly." }, { "code": null, "e": 1585, "s": 1476, "text": "We start by importing and testing openai gym. If you haven’t installed it yet, you can install it by typing:" }, { "code": null, "e": 1602, "s": 1585, "text": "pip3 install gym" }, { "code": null, "e": 1731, "s": 1602, "text": "We then write a script to test our gym environment. We let the agent perform random actions, just to see, that everything works." }, { "code": null, "e": 1917, "s": 1731, "text": "The goal of the agent is to balance the stick for as long as possible. It fails and the episode get’s terminated, if the stick diverges 15 degrees from being upright in both directions." }, { "code": null, "e": 1973, "s": 1917, "text": "The actions the agent can take to achieve its goal are:" }, { "code": null, "e": 1987, "s": 1973, "text": "move left (0)" }, { "code": null, "e": 2002, "s": 1987, "text": "move right (1)" }, { "code": null, "e": 2040, "s": 2002, "text": "Reward is given in the following way:" }, { "code": null, "e": 2085, "s": 2040, "text": "+1 for every step, that the stick is upright" }, { "code": null, "e": 2130, "s": 2085, "text": "The state/observation is a list of 4 values:" }, { "code": null, "e": 2696, "s": 2130, "text": "Consider the following scenario. Our chicken is hungry. It has two actions it can perform. It can either eat or write. Since it is hungry, the better choice would be to eat and this indeed would give it more reward. But reward is given after an action is performed, so how is it supposed to know. In this scenario, the action value(or Q value) can help us. This Q value depends on the state and and a possible action. Q(s, a) then returns us the value of performing an action, given the state. So the chicken should perform the action, that has the highest q value!" }, { "code": null, "e": 2746, "s": 2696, "text": "The Q value is defined by the following equation:" }, { "code": null, "e": 3225, "s": 2746, "text": "This equation simply means, that for a given state, the value of an action is the immediate reward after the action was performed plus the (discounted) highest Q value of the next state. Gamma (Ξ³) is actually the discount factor and it accounts for the uncertainty in future rewards. Ξ³ is usually above 0.9 and smaller than 1. A low gamma leads to the agent being more focused on immediate reward, while a high gamma leads to the agent being more focused on high future rewards." }, { "code": null, "e": 3356, "s": 3225, "text": "We have seen the exact definition of the Q value and I also told you, that we are going to use a neural network to approximate it." }, { "code": null, "e": 3555, "s": 3356, "text": "So we want to bring the approximated Q value of the network as close as possible to the mathematical definition. To achieve this goal, we use the Neural networks ability to minimize a loss function." }, { "code": null, "e": 3673, "s": 3555, "text": "We call the Q value of the actual time step β€œprediction” and the term including the Q value of the next state target." }, { "code": null, "e": 3738, "s": 3673, "text": "The loss function we used is simply the mean squared error loss." }, { "code": null, "e": 3816, "s": 3738, "text": "With temporal difference learning, we can train our agent at every time step." }, { "code": null, "e": 4261, "s": 3816, "text": "If we would let our agent greedily exploit the strategy, which it thinks has the highest Q value, it is very likely, that there exists a better strategy. The agent will never be able to explore this strategy and therefore never see the high reward associated with it. So in the beginning, we let our do random actions and over time decrease it’s probability of taking random actions. This process is called Epsiolon (Ξ΅) greedy action selection." }, { "code": null, "e": 4594, "s": 4261, "text": "Deep Q learning does not especially well unless we enhance it by adding experience replay. For this, we build a memory and store all states, actions and rewards in it. When training, we retrieve a random batch from our memory and train on it. This means, that the agent will most likely not be trained on the last time step it took." }, { "code": null, "e": 4871, "s": 4594, "text": "The following code implements a ReplayBuffer class, which is responsible for storing and giving out random batches of memory. For each timestep we store: (state, action, reward, next_state, done). done is a terminal flag and is 0 during an episode and 1 when the episode ends." }, { "code": null, "e": 5021, "s": 4871, "text": "Instead of presenting pseudo code, I decided to present you the python code of the main file, because it is easier to understand, if you know python." }, { "code": null, "e": 5105, "s": 5021, "text": "We can adjust many hyperparameter, which we pass into the constructor of the agent:" }, { "code": null, "e": 5452, "s": 5105, "text": "agent = DQAgent(learning_rate=0.00025, gamma=0.90, batch_size=32, state_len=len(env.reset()), n_actions = env.action_space.n, mem_size = 1000000, min_memory_for_training=1000, epsilon=1,epsilon_dec=0.99, epsilon_min = 0.02)" }, { "code": null, "e": 5618, "s": 5452, "text": "Learning rate: learning rate of the neural network. A high value leads to the agent learning fast, but can also lead to sub-optimal behavior in complex environments." }, { "code": null, "e": 5820, "s": 5618, "text": "Gamma: Ξ³ is usually above 0.9 and smaller than 1. A low gamma leads to the agent being more focused on immediate reward, while a high gamma leads to the agent being more focused on high future rewards." }, { "code": null, "e": 6000, "s": 5820, "text": "Batch size: The number of timesteps given to the neural network to perform minibatch gradient descent. High number of batches stabilizes learning, but can also lead to stagnation." }, { "code": null, "e": 6167, "s": 6000, "text": "Min memory for training: Number of steps, before the learning process begins. A decent number prevents the network from overfitting to the first few training samples." }, { "code": null, "e": 6348, "s": 6167, "text": "Epsilon: The start value of epsilon. 1 means agent perform only random actions (exploration) in the beginning and 0 means it would start performing no random actions(exploitation)." }, { "code": null, "e": 6490, "s": 6348, "text": "Epsilon dec: The factor by which epsilon is multiplied after each time step to decrease it. It should be bigger than 0.99 and smaller than 1." }, { "code": null, "e": 6704, "s": 6490, "text": "Epsilon min: The minimal value for epsilon. Epsilon will not get decreased if it would fall below this value. It is very important to have a little exploration at any time, so that the agent can continue to learn." }, { "code": null, "e": 6741, "s": 6704, "text": "And now the whole code of our agent:" }, { "code": null, "e": 6771, "s": 6741, "text": "Let’s discuss this code line:" }, { "code": null, "e": 6884, "s": 6771, "text": "target = rewards_batch + torch.mul(self.gamma* self.q(new_states_batch).max(axis = 1).values, (1 - dones_batch))" }, { "code": null, "e": 6948, "s": 6884, "text": "It calculates the TD target. Lets’s assume our batch size is 5." }, { "code": null, "e": 6998, "s": 6948, "text": "Then the calculation could be looking as follows:" }, { "code": null, "e": 7087, "s": 6998, "text": "We do the max operation, because we want to look at the action with the highest Q value." }, { "code": null, "e": 7135, "s": 7087, "text": "And Let’s also look at the following code line:" }, { "code": null, "e": 7225, "s": 7135, "text": "prediction = self.q.forward(states_batch).gather(1,actions_batch.unsqueeze(1)).squeeze(1)" }, { "code": null, "e": 7314, "s": 7225, "text": "It calculates the prediction. With a batch size of 5, this could look the following way:" }, { "code": null, "e": 7380, "s": 7314, "text": "We select the q values from the actions, the agent actually took." }, { "code": null, "e": 7471, "s": 7380, "text": "Now it’s time to actually test our algorithm. We test it with our CartPole-v0 environment." }, { "code": null, "e": 7583, "s": 7471, "text": "After 100 episodes, the agent has managed to beat the environment and almost always achieves the highest score." }, { "code": null, "e": 7738, "s": 7583, "text": "To improve our deep Q learning algorithm even further, we can choose to have separate prediction and target values. This is also called double Q learning." }, { "code": null, "e": 8037, "s": 7738, "text": "The actions will be predicted with the prediction network. Backpropagation only happens in the prediction network. The parameters of the prediction network get copied every few iterations to the target network. How long the parameters of the target network remain β€œfrozen” is also a hyperparameter." }, { "code": null, "e": 8166, "s": 8037, "text": "We freeze the target network, because then the prediction and the target are less correlated. This helps in the learning process" }, { "code": null, "e": 8327, "s": 8166, "text": "Now we have a little fun and test our algorithm with the openai environment β€œLunarLander-v2”. You can find a list of the hyperparamters which I have used below." }, { "code": null, "e": 8348, "s": 8327, "text": "Learning rate: 0.001" }, { "code": null, "e": 8360, "s": 8348, "text": "Gamma: 0.99" }, { "code": null, "e": 8375, "s": 8360, "text": "Batch size: 64" }, { "code": null, "e": 8408, "s": 8375, "text": "Min memory for training: 1000000" }, { "code": null, "e": 8419, "s": 8408, "text": "Epsilon: 1" }, { "code": null, "e": 8438, "s": 8419, "text": "Epsilon dec: 0.995" }, { "code": null, "e": 8456, "s": 8438, "text": "Epsilon min: 0.02" }, { "code": null, "e": 8477, "s": 8456, "text": "Frozen_iterations: 6" }, { "code": null, "e": 8570, "s": 8477, "text": "The following GIF was taken at episode 729. The agent does very well at landing that lander." }, { "code": null, "e": 8610, "s": 8570, "text": "And the learning curve looks like this." }, { "code": null, "e": 8668, "s": 8610, "text": "Note that it was smoothed by a 20 episode moving average." }, { "code": null, "e": 8683, "s": 8668, "text": "The main file:" }, { "code": null, "e": 8703, "s": 8683, "text": "Code for the agent:" }, { "code": null, "e": 8726, "s": 8703, "text": "towardsdatascience.com" }, { "code": null, "e": 8749, "s": 8726, "text": "towardsdatascience.com" }, { "code": null, "e": 8772, "s": 8749, "text": "towardsdatascience.com" } ]
Can QuickSort be implemented in O(nLogn) worst case time complexity? - GeeksforGeeks
08 Jan, 2021 The worst case time complexity of a typical implementation of QuickSort is O(n2). The worst case occurs when the picked pivot is always an extreme (smallest or largest) element. This happens when input array is sorted or reverse sorted and either first or last element is picked as pivot. Although randomized QuickSort works well even when the array is sorted, there is still possible that the randomly picked element is always extreme. Can the worst case be reduced to O(nLogn)? The answer is yes, we can achieve O(nLogn) worst case. The idea is based on the fact that the median element of an unsorted array can be found in linear time. So we find the median first, then partition the array around the median element. Following is C++ implementation based on above idea. Most of the functions in below program are copied from K’th Smallest/Largest Element in Unsorted Array | Set 3 (Worst Case Linear Time) C++ /* A worst case O(nLogn) implementation of quicksort */#include<cstring>#include<iostream>#include<algorithm>#include<climits>using namespace std; // Following functions are taken from http://goo.gl/ih05BFint partition(int arr[], int l, int r, int k);int kthSmallest(int arr[], int l, int r, int k); /* A O(nLogn) time complexity function for sorting arr[l..h] */void quickSort(int arr[], int l, int h){ if (l < h) { // Find size of current subarray int n = h-l+1; // Find median of arr[]. int med = kthSmallest(arr, l, h, n/2); // Partition the array around median int p = partition(arr, l, h, med); // Recur for left and right of partition quickSort(arr, l, p - 1); quickSort(arr, p + 1, h); }} // A simple function to find median of arr[]. This is called// only for an array of size 5 in this program.int findMedian(int arr[], int n){ sort(arr, arr+n); // Sort the array return arr[n/2]; // Return middle element} // Returns k'th smallest element in arr[l..r] in worst case// linear time. ASSUMPTION: ALL ELEMENTS IN ARR[] ARE DISTINCTint kthSmallest(int arr[], int l, int r, int k){ // If k is smaller than number of elements in array if (k > 0 && k <= r - l + 1) { int n = r-l+1; // Number of elements in arr[l..r] // Divide arr[] in groups of size 5, calculate median // of every group and store it in median[] array. int i, median[(n+4)/5]; // There will be floor((n+4)/5) groups; for (i=0; i<n/5; i++) median[i] = findMedian(arr+l+i*5, 5); if (i*5 < n) //For last group with less than 5 elements { median[i] = findMedian(arr+l+i*5, n%5); i++; } // Find median of all medians using recursive call. // If median[] has only one element, then no need // of recursive call int medOfMed = (i == 1)? median[i-1]: kthSmallest(median, 0, i-1, i/2); // Partition the array around a random element and // get position of pivot element in sorted array int pos = partition(arr, l, r, medOfMed); // If position is same as k if (pos-l == k-1) return arr[pos]; if (pos-l > k-1) // If position is more, recur for left return kthSmallest(arr, l, pos-1, k); // Else recur for right subarray return kthSmallest(arr, pos+1, r, k-pos+l-1); } // If k is more than number of elements in array return INT_MAX;} void swap(int *a, int *b){ int temp = *a; *a = *b; *b = temp;} // It searches for x in arr[l..r], and partitions the array// around x.int partition(int arr[], int l, int r, int x){ // Search for x in arr[l..r] and move it to end int i; for (i=l; i<r; i++) if (arr[i] == x) break; swap(&arr[i], &arr[r]); // Standard partition algorithm i = l; for (int j = l; j <= r - 1; j++) { if (arr[j] <= x) { swap(&arr[i], &arr[j]); i++; } } swap(&arr[i], &arr[r]); return i;} /* Function to print an array */void printArray(int arr[], int size){ int i; for (i=0; i < size; i++) cout << arr[i] << " "; cout << endl;} // Driver program to test above functionsint main(){ int arr[] = {1000, 10, 7, 8, 9, 30, 900, 1, 5, 6, 20}; int n = sizeof(arr)/sizeof(arr[0]); quickSort(arr, 0, n-1); cout << "Sorted array is\n"; printArray(arr, n); return 0;} Output: Sorted array is 1 5 6 7 8 9 10 20 30 900 1000 How is QuickSort implemented in practice – is above approach used? Although worst case time complexity of the above approach is O(nLogn), it is never used in practical implementations. The hidden constants in this approach are high compared to normal Quicksort. Following are some techniques used in practical implementations of QuickSort. 1) Randomly picking up to make worst case less likely to occur (Randomized QuickSort) 2) Calling insertion sort for small sized arrays to reduce recursive calls. 3) QuickSort is tail recursive, so tail call optimizations is done. So the approach discussed above is more of a theoretical approach with O(nLogn) worst case time complexity. This article is compiled by Shivam. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above 210manishprajapati Quick Sort Sorting Quiz Sorting Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Quickselect Algorithm Iterative Quick Sort C++ Program for QuickSort Stability in sorting algorithms TimSort In-Place Algorithm 3-way Merge Sort Java Program for QuickSort In-Place Merge Sort Program to check if an array is sorted or not (Iterative and Recursive)
[ { "code": null, "e": 23685, "s": 23657, "text": "\n08 Jan, 2021" }, { "code": null, "e": 23974, "s": 23685, "text": "The worst case time complexity of a typical implementation of QuickSort is O(n2). The worst case occurs when the picked pivot is always an extreme (smallest or largest) element. This happens when input array is sorted or reverse sorted and either first or last element is picked as pivot." }, { "code": null, "e": 24165, "s": 23974, "text": "Although randomized QuickSort works well even when the array is sorted, there is still possible that the randomly picked element is always extreme. Can the worst case be reduced to O(nLogn)?" }, { "code": null, "e": 24594, "s": 24165, "text": "The answer is yes, we can achieve O(nLogn) worst case. The idea is based on the fact that the median element of an unsorted array can be found in linear time. So we find the median first, then partition the array around the median element. Following is C++ implementation based on above idea. Most of the functions in below program are copied from K’th Smallest/Largest Element in Unsorted Array | Set 3 (Worst Case Linear Time)" }, { "code": null, "e": 24598, "s": 24594, "text": "C++" }, { "code": "/* A worst case O(nLogn) implementation of quicksort */#include<cstring>#include<iostream>#include<algorithm>#include<climits>using namespace std; // Following functions are taken from http://goo.gl/ih05BFint partition(int arr[], int l, int r, int k);int kthSmallest(int arr[], int l, int r, int k); /* A O(nLogn) time complexity function for sorting arr[l..h] */void quickSort(int arr[], int l, int h){ if (l < h) { // Find size of current subarray int n = h-l+1; // Find median of arr[]. int med = kthSmallest(arr, l, h, n/2); // Partition the array around median int p = partition(arr, l, h, med); // Recur for left and right of partition quickSort(arr, l, p - 1); quickSort(arr, p + 1, h); }} // A simple function to find median of arr[]. This is called// only for an array of size 5 in this program.int findMedian(int arr[], int n){ sort(arr, arr+n); // Sort the array return arr[n/2]; // Return middle element} // Returns k'th smallest element in arr[l..r] in worst case// linear time. ASSUMPTION: ALL ELEMENTS IN ARR[] ARE DISTINCTint kthSmallest(int arr[], int l, int r, int k){ // If k is smaller than number of elements in array if (k > 0 && k <= r - l + 1) { int n = r-l+1; // Number of elements in arr[l..r] // Divide arr[] in groups of size 5, calculate median // of every group and store it in median[] array. int i, median[(n+4)/5]; // There will be floor((n+4)/5) groups; for (i=0; i<n/5; i++) median[i] = findMedian(arr+l+i*5, 5); if (i*5 < n) //For last group with less than 5 elements { median[i] = findMedian(arr+l+i*5, n%5); i++; } // Find median of all medians using recursive call. // If median[] has only one element, then no need // of recursive call int medOfMed = (i == 1)? median[i-1]: kthSmallest(median, 0, i-1, i/2); // Partition the array around a random element and // get position of pivot element in sorted array int pos = partition(arr, l, r, medOfMed); // If position is same as k if (pos-l == k-1) return arr[pos]; if (pos-l > k-1) // If position is more, recur for left return kthSmallest(arr, l, pos-1, k); // Else recur for right subarray return kthSmallest(arr, pos+1, r, k-pos+l-1); } // If k is more than number of elements in array return INT_MAX;} void swap(int *a, int *b){ int temp = *a; *a = *b; *b = temp;} // It searches for x in arr[l..r], and partitions the array// around x.int partition(int arr[], int l, int r, int x){ // Search for x in arr[l..r] and move it to end int i; for (i=l; i<r; i++) if (arr[i] == x) break; swap(&arr[i], &arr[r]); // Standard partition algorithm i = l; for (int j = l; j <= r - 1; j++) { if (arr[j] <= x) { swap(&arr[i], &arr[j]); i++; } } swap(&arr[i], &arr[r]); return i;} /* Function to print an array */void printArray(int arr[], int size){ int i; for (i=0; i < size; i++) cout << arr[i] << \" \"; cout << endl;} // Driver program to test above functionsint main(){ int arr[] = {1000, 10, 7, 8, 9, 30, 900, 1, 5, 6, 20}; int n = sizeof(arr)/sizeof(arr[0]); quickSort(arr, 0, n-1); cout << \"Sorted array is\\n\"; printArray(arr, n); return 0;}", "e": 28099, "s": 24598, "text": null }, { "code": null, "e": 28108, "s": 28099, "text": "Output: " }, { "code": null, "e": 28154, "s": 28108, "text": "Sorted array is\n1 5 6 7 8 9 10 20 30 900 1000" }, { "code": null, "e": 28724, "s": 28154, "text": "How is QuickSort implemented in practice – is above approach used? Although worst case time complexity of the above approach is O(nLogn), it is never used in practical implementations. The hidden constants in this approach are high compared to normal Quicksort. Following are some techniques used in practical implementations of QuickSort. 1) Randomly picking up to make worst case less likely to occur (Randomized QuickSort) 2) Calling insertion sort for small sized arrays to reduce recursive calls. 3) QuickSort is tail recursive, so tail call optimizations is done." }, { "code": null, "e": 28832, "s": 28724, "text": "So the approach discussed above is more of a theoretical approach with O(nLogn) worst case time complexity." }, { "code": null, "e": 28993, "s": 28832, "text": "This article is compiled by Shivam. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 29012, "s": 28993, "text": "210manishprajapati" }, { "code": null, "e": 29023, "s": 29012, "text": "Quick Sort" }, { "code": null, "e": 29036, "s": 29023, "text": "Sorting Quiz" }, { "code": null, "e": 29044, "s": 29036, "text": "Sorting" }, { "code": null, "e": 29052, "s": 29044, "text": "Sorting" }, { "code": null, "e": 29150, "s": 29052, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29159, "s": 29150, "text": "Comments" }, { "code": null, "e": 29172, "s": 29159, "text": "Old Comments" }, { "code": null, "e": 29194, "s": 29172, "text": "Quickselect Algorithm" }, { "code": null, "e": 29215, "s": 29194, "text": "Iterative Quick Sort" }, { "code": null, "e": 29241, "s": 29215, "text": "C++ Program for QuickSort" }, { "code": null, "e": 29273, "s": 29241, "text": "Stability in sorting algorithms" }, { "code": null, "e": 29281, "s": 29273, "text": "TimSort" }, { "code": null, "e": 29300, "s": 29281, "text": "In-Place Algorithm" }, { "code": null, "e": 29317, "s": 29300, "text": "3-way Merge Sort" }, { "code": null, "e": 29344, "s": 29317, "text": "Java Program for QuickSort" }, { "code": null, "e": 29364, "s": 29344, "text": "In-Place Merge Sort" } ]
Jackson - ObjectMapper Class
ObjectMapper is the main actor class of Jackson library. ObjectMapper class ObjectMapper provides functionality for reading and writing JSON, either to and from basic POJOs (Plain Old Java Objects), or to and from a general-purpose JSON Tree Model (JsonNode), as well as related functionality for performing conversions. It is also highly customizable to work both with different styles of JSON content, and to support more advanced Object concepts such as polymorphism and Object identity. ObjectMapper also acts as a factory for more advanced ObjectReader and ObjectWriter classes. Following is the declaration for com.fasterxml.jackson.databind.ObjectMapper class βˆ’ public class ObjectMapper extends ObjectCodec implements Versioned, Serializable Customized TypeResolverBuilder that provides type resolver builders used with so-called "default typing" (see enableDefaultTyping() for details). Enumeration used with enableDefaultTyping() to specify what kind of types (classes) default typing should be used for. protected DeserializationConfig _deserializationConfig - Configuration object that defines basic global settings for the serialization process. protected DeserializationConfig _deserializationConfig - Configuration object that defines basic global settings for the serialization process. protected DefaultDeserializationContext _deserializationContext - Blueprint context object; stored here to allow custom sub-classes. protected DefaultDeserializationContext _deserializationContext - Blueprint context object; stored here to allow custom sub-classes. protected InjectableValues _injectableValues - Provider for values to inject in deserialized POJOs. protected InjectableValues _injectableValues - Provider for values to inject in deserialized POJOs. protected JsonFactory _jsonFactory - Factory used to create JsonParser and JsonGenerator instances as necessary. protected JsonFactory _jsonFactory - Factory used to create JsonParser and JsonGenerator instances as necessary. protected SimpleMixInResolver _mixIns - Mapping that defines how to apply mix-in annotations: key is the type to received additional annotations, and value is the type that has annotations to "mix in". protected SimpleMixInResolver _mixIns - Mapping that defines how to apply mix-in annotations: key is the type to received additional annotations, and value is the type that has annotations to "mix in". protected ConfigOverrides _propertyOverrides - Currently active per-type configuration overrides, accessed by declared type of property. protected ConfigOverrides _propertyOverrides - Currently active per-type configuration overrides, accessed by declared type of property. protected Set<Object> _registeredModuleTypes - Set of module types (as per Module.getTypeId() that have been registered; kept track of iff MapperFeature.IGNORE_DUPLICATE_MODULE_REGISTRATIONS is enabled, so that duplicate registration calls can be ignored (to avoid adding same handlers multiple times, mostly). protected Set<Object> _registeredModuleTypes - Set of module types (as per Module.getTypeId() that have been registered; kept track of iff MapperFeature.IGNORE_DUPLICATE_MODULE_REGISTRATIONS is enabled, so that duplicate registration calls can be ignored (to avoid adding same handlers multiple times, mostly). protected ConcurrentHashMap<JavaType,JsonDeserializer<Object>> _rootDeserializers - We will use a separate main-level Map for keeping track of root-level deserializers. protected ConcurrentHashMap<JavaType,JsonDeserializer<Object>> _rootDeserializers - We will use a separate main-level Map for keeping track of root-level deserializers. protected SerializationConfig _serializationConfig - Configuration object that defines basic global settings for the serialization process. protected SerializationConfig _serializationConfig - Configuration object that defines basic global settings for the serialization process. protected SerializerFactory _serializerFactory - Serializer factory used for constructing serializers. protected SerializerFactory _serializerFactory - Serializer factory used for constructing serializers. protected DefaultSerializerProvider _serializerProvider - Object that manages access to serializers used for serialization, including caching. protected DefaultSerializerProvider _serializerProvider - Object that manages access to serializers used for serialization, including caching. protected SubtypeResolver _subtypeResolver - Thing used for registering sub-types, resolving them to super/sub-types as needed. protected SubtypeResolver _subtypeResolver - Thing used for registering sub-types, resolving them to super/sub-types as needed. protected TypeFactory _typeFactory - Specific factory used for creating JavaType instances; needed to allow modules to add more custom type handling (mostly to support types of non-Java JVM languages). protected TypeFactory _typeFactory - Specific factory used for creating JavaType instances; needed to allow modules to add more custom type handling (mostly to support types of non-Java JVM languages). protected static AnnotationIntrospector DEFAULT_ANNOTATION_INTROSPECTOR protected static AnnotationIntrospector DEFAULT_ANNOTATION_INTROSPECTOR protected static BaseSettings DEFAULT_BASE - Base settings contain defaults used for all ObjectMapper instances. protected static BaseSettings DEFAULT_BASE - Base settings contain defaults used for all ObjectMapper instances. protected static VisibilityChecker<?> STD_VISIBILITY_CHECKER protected static VisibilityChecker<?> STD_VISIBILITY_CHECKER Default constructor, which will construct the default JsonFactory as necessary, use SerializerProvider as its SerializerProvider, and BeanSerializerFactory as its SerializerFactory. Constructs instance that uses specified JsonFactory for constructing necessary JsonParsers and/or JsonGenerators. Constructs instance that uses specified JsonFactory for constructing necessary JsonParsers and/or JsonGenerators, and uses given providers for accessing serializers and deserializers. Copy-constructor, mostly used to support copy(). This class inherits methods from the following classes: java.lang.Object java.lang.Object Create the following java program using any editor of your choice in say C:/> Jackson_WORKSPACE File: JacksonTester.java import java.io.IOException; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; public class JacksonTester { public static void main(String args[]){ ObjectMapper mapper = new ObjectMapper(); String jsonString = "{\"name\":\"Mahesh\", \"age\":21}"; //map json to student try{ Student student = mapper.readValue(jsonString, Student.class); System.out.println(student); jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(student); System.out.println(jsonString); } catch (JsonParseException e) { e.printStackTrace();} catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } class Student { private String name; private int age; public Student(){} public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String toString(){ return "Student [ name: "+name+", age: "+ age+ " ]"; } } Verify the result Compile the classes using javac compiler as follows: C:\Jackson_WORKSPACE>javac JacksonTester.java Now run the jacksonTester to see the result: C:\Jackson_WORKSPACE>java JacksonTester Verify the Output Student [ name: Mahesh, age: 21 ] { "name" : "Mahesh", "age" : 21 } Print Add Notes Bookmark this page
[ { "code": null, "e": 2337, "s": 1753, "text": "ObjectMapper is the main actor class of Jackson library. ObjectMapper class ObjectMapper provides functionality for reading and writing JSON, either to and from basic POJOs (Plain Old Java Objects), or to and from a general-purpose JSON Tree Model (JsonNode), as well as related functionality for performing conversions. It is also highly customizable to work both with different styles of JSON content, and to support more advanced Object concepts such as polymorphism and Object identity. ObjectMapper also acts as a factory for more advanced ObjectReader and ObjectWriter classes." }, { "code": null, "e": 2422, "s": 2337, "text": "Following is the declaration for com.fasterxml.jackson.databind.ObjectMapper class βˆ’" }, { "code": null, "e": 2512, "s": 2422, "text": "public class ObjectMapper\n extends ObjectCodec\n implements Versioned, Serializable" }, { "code": null, "e": 2658, "s": 2512, "text": "Customized TypeResolverBuilder that provides type resolver builders used with so-called \"default typing\" (see enableDefaultTyping() for details)." }, { "code": null, "e": 2777, "s": 2658, "text": "Enumeration used with enableDefaultTyping() to specify what kind of types (classes) default typing should be used for." }, { "code": null, "e": 2921, "s": 2777, "text": "protected DeserializationConfig _deserializationConfig - Configuration object that defines basic global settings for the serialization process." }, { "code": null, "e": 3065, "s": 2921, "text": "protected DeserializationConfig _deserializationConfig - Configuration object that defines basic global settings for the serialization process." }, { "code": null, "e": 3198, "s": 3065, "text": "protected DefaultDeserializationContext _deserializationContext - Blueprint context object; stored here to allow custom sub-classes." }, { "code": null, "e": 3331, "s": 3198, "text": "protected DefaultDeserializationContext _deserializationContext - Blueprint context object; stored here to allow custom sub-classes." }, { "code": null, "e": 3431, "s": 3331, "text": "protected InjectableValues _injectableValues - Provider for values to inject in deserialized POJOs." }, { "code": null, "e": 3531, "s": 3431, "text": "protected InjectableValues _injectableValues - Provider for values to inject in deserialized POJOs." }, { "code": null, "e": 3644, "s": 3531, "text": "protected JsonFactory _jsonFactory - Factory used to create JsonParser and JsonGenerator instances as necessary." }, { "code": null, "e": 3757, "s": 3644, "text": "protected JsonFactory _jsonFactory - Factory used to create JsonParser and JsonGenerator instances as necessary." }, { "code": null, "e": 3959, "s": 3757, "text": "protected SimpleMixInResolver _mixIns - Mapping that defines how to apply mix-in annotations: key is the type to received additional annotations, and value is the type that has annotations to \"mix in\"." }, { "code": null, "e": 4161, "s": 3959, "text": "protected SimpleMixInResolver _mixIns - Mapping that defines how to apply mix-in annotations: key is the type to received additional annotations, and value is the type that has annotations to \"mix in\"." }, { "code": null, "e": 4298, "s": 4161, "text": "protected ConfigOverrides _propertyOverrides - Currently active per-type configuration overrides, accessed by declared type of property." }, { "code": null, "e": 4435, "s": 4298, "text": "protected ConfigOverrides _propertyOverrides - Currently active per-type configuration overrides, accessed by declared type of property." }, { "code": null, "e": 4746, "s": 4435, "text": "protected Set<Object> _registeredModuleTypes - Set of module types (as per Module.getTypeId() that have been registered; kept track of iff MapperFeature.IGNORE_DUPLICATE_MODULE_REGISTRATIONS is enabled, so that duplicate registration calls can be ignored (to avoid adding same handlers multiple times, mostly)." }, { "code": null, "e": 5057, "s": 4746, "text": "protected Set<Object> _registeredModuleTypes - Set of module types (as per Module.getTypeId() that have been registered; kept track of iff MapperFeature.IGNORE_DUPLICATE_MODULE_REGISTRATIONS is enabled, so that duplicate registration calls can be ignored (to avoid adding same handlers multiple times, mostly)." }, { "code": null, "e": 5226, "s": 5057, "text": "protected ConcurrentHashMap<JavaType,JsonDeserializer<Object>> _rootDeserializers - We will use a separate main-level Map for keeping track of root-level deserializers." }, { "code": null, "e": 5395, "s": 5226, "text": "protected ConcurrentHashMap<JavaType,JsonDeserializer<Object>> _rootDeserializers - We will use a separate main-level Map for keeping track of root-level deserializers." }, { "code": null, "e": 5535, "s": 5395, "text": "protected SerializationConfig _serializationConfig - Configuration object that defines basic global settings for the serialization process." }, { "code": null, "e": 5675, "s": 5535, "text": "protected SerializationConfig _serializationConfig - Configuration object that defines basic global settings for the serialization process." }, { "code": null, "e": 5779, "s": 5675, "text": "protected SerializerFactory _serializerFactory - Serializer factory used for constructing serializers.\n" }, { "code": null, "e": 5883, "s": 5779, "text": "protected SerializerFactory _serializerFactory - Serializer factory used for constructing serializers.\n" }, { "code": null, "e": 6026, "s": 5883, "text": "protected DefaultSerializerProvider _serializerProvider - Object that manages access to serializers used for serialization, including caching." }, { "code": null, "e": 6169, "s": 6026, "text": "protected DefaultSerializerProvider _serializerProvider - Object that manages access to serializers used for serialization, including caching." }, { "code": null, "e": 6297, "s": 6169, "text": "protected SubtypeResolver _subtypeResolver - Thing used for registering sub-types, resolving them to super/sub-types as needed." }, { "code": null, "e": 6425, "s": 6297, "text": "protected SubtypeResolver _subtypeResolver - Thing used for registering sub-types, resolving them to super/sub-types as needed." }, { "code": null, "e": 6627, "s": 6425, "text": "protected TypeFactory _typeFactory - Specific factory used for creating JavaType instances; needed to allow modules to add more custom type handling (mostly to support types of non-Java JVM languages)." }, { "code": null, "e": 6829, "s": 6627, "text": "protected TypeFactory _typeFactory - Specific factory used for creating JavaType instances; needed to allow modules to add more custom type handling (mostly to support types of non-Java JVM languages)." }, { "code": null, "e": 6903, "s": 6829, "text": "protected static AnnotationIntrospector DEFAULT_ANNOTATION_INTROSPECTOR " }, { "code": null, "e": 6977, "s": 6903, "text": "protected static AnnotationIntrospector DEFAULT_ANNOTATION_INTROSPECTOR " }, { "code": null, "e": 7090, "s": 6977, "text": "protected static BaseSettings DEFAULT_BASE - Base settings contain defaults used for all ObjectMapper instances." }, { "code": null, "e": 7203, "s": 7090, "text": "protected static BaseSettings DEFAULT_BASE - Base settings contain defaults used for all ObjectMapper instances." }, { "code": null, "e": 7265, "s": 7203, "text": "protected static VisibilityChecker<?> STD_VISIBILITY_CHECKER " }, { "code": null, "e": 7327, "s": 7265, "text": "protected static VisibilityChecker<?> STD_VISIBILITY_CHECKER " }, { "code": null, "e": 7509, "s": 7327, "text": "Default constructor, which will construct the default JsonFactory as necessary, use SerializerProvider as its SerializerProvider, and BeanSerializerFactory as its SerializerFactory." }, { "code": null, "e": 7623, "s": 7509, "text": "Constructs instance that uses specified JsonFactory for constructing necessary JsonParsers and/or JsonGenerators." }, { "code": null, "e": 7807, "s": 7623, "text": "Constructs instance that uses specified JsonFactory for constructing necessary JsonParsers and/or JsonGenerators, and uses given providers for accessing serializers and deserializers." }, { "code": null, "e": 7856, "s": 7807, "text": "Copy-constructor, mostly used to support copy()." }, { "code": null, "e": 7912, "s": 7856, "text": "This class inherits methods from the following classes:" }, { "code": null, "e": 7929, "s": 7912, "text": "java.lang.Object" }, { "code": null, "e": 7946, "s": 7929, "text": "java.lang.Object" }, { "code": null, "e": 8042, "s": 7946, "text": "Create the following java program using any editor of your choice in say C:/> Jackson_WORKSPACE" }, { "code": null, "e": 8067, "s": 8042, "text": "File: JacksonTester.java" }, { "code": null, "e": 9363, "s": 8067, "text": "import java.io.IOException;\n\nimport com.fasterxml.jackson.core.JsonParseException;\nimport com.fasterxml.jackson.databind.JsonMappingException;\nimport com.fasterxml.jackson.databind.ObjectMapper;\n\npublic class JacksonTester {\n public static void main(String args[]){\n \n ObjectMapper mapper = new ObjectMapper();\n String jsonString = \"{\\\"name\\\":\\\"Mahesh\\\", \\\"age\\\":21}\";\n \n //map json to student\n try{\n Student student = mapper.readValue(jsonString, Student.class);\n \n System.out.println(student);\n \n jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(student);\n \n System.out.println(jsonString);\n }\n catch (JsonParseException e) { e.printStackTrace();}\n catch (JsonMappingException e) { e.printStackTrace(); }\n catch (IOException e) { e.printStackTrace(); }\n }\n}\n\nclass Student {\n private String name;\n private int age;\n public Student(){}\n public String getName() {\n return name;\n }\n public void setName(String name) {\n this.name = name;\n }\n public int getAge() {\n return age;\n }\n public void setAge(int age) {\n this.age = age;\n }\n public String toString(){\n return \"Student [ name: \"+name+\", age: \"+ age+ \" ]\";\n }\n}" }, { "code": null, "e": 9381, "s": 9363, "text": "Verify the result" }, { "code": null, "e": 9434, "s": 9381, "text": "Compile the classes using javac compiler as follows:" }, { "code": null, "e": 9480, "s": 9434, "text": "C:\\Jackson_WORKSPACE>javac JacksonTester.java" }, { "code": null, "e": 9525, "s": 9480, "text": "Now run the jacksonTester to see the result:" }, { "code": null, "e": 9565, "s": 9525, "text": "C:\\Jackson_WORKSPACE>java JacksonTester" }, { "code": null, "e": 9583, "s": 9565, "text": "Verify the Output" }, { "code": null, "e": 9656, "s": 9583, "text": "Student [ name: Mahesh, age: 21 ]\n{\n \"name\" : \"Mahesh\",\n \"age\" : 21\n}\n" }, { "code": null, "e": 9663, "s": 9656, "text": " Print" }, { "code": null, "e": 9674, "s": 9663, "text": " Add Notes" } ]
C# | Uri.EscapeDataString(String) Method - GeeksforGeeks
01 May, 2019 Uri.EscapeDataString(String) Method is used to convert a string to its escaped representation. Syntax: public static string EscapeDataString (string stringToEscape);Here, it takes the string to escape. Return Value: This method returns a string which contains the escaped representation of stringToEscape. Exception: This method throws ArgumentNullException if stringToEscape is null.and UriFormatException if The length of stringToEscape exceeds 32766 characters. Below programs illustrate the use of Uri.EscapeDataString(String) Method: Example 1: // C# program to demonstrate the// Uri.EscapeDataString(String) Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { try { // Declaring and initializing address1 string address1 = "http://www.contoso.com/index.htm#search"; // Converting a string to its // escaped representation // using EscapeDataString() method string value = Uri.EscapeDataString(address1); // Displaying the result Console.WriteLine("Escaped string is : {0}", value); } catch (ArgumentNullException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } }} Escaped string is : http%3A%2F%2Fwww.contoso.com%2Findex.htm%23search Example 2: For ArgumentNullException // C# program to demonstrate the// Uri.EscapeDataString(String) Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { try { // Declaring and initializing address1 string address1 = null; // Converting a string to its // escaped representation // using EscapeDataString() method string value = Uri.EscapeDataString(address1); // Displaying the result Console.WriteLine("Escaped string is : {0}", value); } catch (ArgumentNullException e) { Console.WriteLine("stringToEscape can not be null"); Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } catch (UriFormatException e) { Console.WriteLine("Length of stringToEscape should"+ " not exceed from 32766 characters."); Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } }} stringToEscape can not be null Exception Thrown: System.ArgumentNullException Example 3: For UriFormatException // C# program to demonstrate the// Uri.EscapeDataString(String) Methodusing System;using System.Text;using System.Globalization; class GFG { // Main Method public static void Main() { try { // Declaring and initializing address1 StringBuilder address1 = new StringBuilder("http://www.contoso.com/index.htm#search"); // appending StringBuilder for (int i = 1; i <= 3000; i++) address1.Append("abcedfghijklmnopdjdjdjdjdjjddjjdjdj"); // Converting a string to its // escaped representation // using EscapeDataString() method string value = Uri.EscapeDataString(address1.ToString()); // Displaying the result Console.WriteLine("Escaped string is : {0}", value); } catch (ArgumentNullException e) { Console.WriteLine("stringToEscape can not be null"); Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } catch (UriFormatException e) { Console.WriteLine("Length of stringToEscape should"+ " not exceed from 32766 characters."); Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } }} Length of stringToEscape should not exceed from 32766 characters. Exception Thrown: System.UriFormatException Reference: https://docs.microsoft.com/en-us/dotnet/api/system.uri.escapedatastring?view=netstandard-2.1 CSharp-method CSharp-Uri-Class C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Extension Method in C# HashSet in C# with Examples C# | Inheritance Partial Classes in C# C# | Generics - Introduction Top 50 C# Interview Questions & Answers Switch Statement in C# Convert String to Character Array in C# C# | How to insert an element in an Array? Lambda Expressions in C#
[ { "code": null, "e": 25547, "s": 25519, "text": "\n01 May, 2019" }, { "code": null, "e": 25642, "s": 25547, "text": "Uri.EscapeDataString(String) Method is used to convert a string to its escaped representation." }, { "code": null, "e": 25749, "s": 25642, "text": "Syntax: public static string EscapeDataString (string stringToEscape);Here, it takes the string to escape." }, { "code": null, "e": 25853, "s": 25749, "text": "Return Value: This method returns a string which contains the escaped representation of stringToEscape." }, { "code": null, "e": 26012, "s": 25853, "text": "Exception: This method throws ArgumentNullException if stringToEscape is null.and UriFormatException if The length of stringToEscape exceeds 32766 characters." }, { "code": null, "e": 26086, "s": 26012, "text": "Below programs illustrate the use of Uri.EscapeDataString(String) Method:" }, { "code": null, "e": 26097, "s": 26086, "text": "Example 1:" }, { "code": "// C# program to demonstrate the// Uri.EscapeDataString(String) Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { try { // Declaring and initializing address1 string address1 = \"http://www.contoso.com/index.htm#search\"; // Converting a string to its // escaped representation // using EscapeDataString() method string value = Uri.EscapeDataString(address1); // Displaying the result Console.WriteLine(\"Escaped string is : {0}\", value); } catch (ArgumentNullException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } }}", "e": 26879, "s": 26097, "text": null }, { "code": null, "e": 26950, "s": 26879, "text": "Escaped string is : http%3A%2F%2Fwww.contoso.com%2Findex.htm%23search\n" }, { "code": null, "e": 26987, "s": 26950, "text": "Example 2: For ArgumentNullException" }, { "code": "// C# program to demonstrate the// Uri.EscapeDataString(String) Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { try { // Declaring and initializing address1 string address1 = null; // Converting a string to its // escaped representation // using EscapeDataString() method string value = Uri.EscapeDataString(address1); // Displaying the result Console.WriteLine(\"Escaped string is : {0}\", value); } catch (ArgumentNullException e) { Console.WriteLine(\"stringToEscape can not be null\"); Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } catch (UriFormatException e) { Console.WriteLine(\"Length of stringToEscape should\"+ \" not exceed from 32766 characters.\"); Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } }}", "e": 28088, "s": 26987, "text": null }, { "code": null, "e": 28167, "s": 28088, "text": "stringToEscape can not be null\nException Thrown: System.ArgumentNullException\n" }, { "code": null, "e": 28201, "s": 28167, "text": "Example 3: For UriFormatException" }, { "code": "// C# program to demonstrate the// Uri.EscapeDataString(String) Methodusing System;using System.Text;using System.Globalization; class GFG { // Main Method public static void Main() { try { // Declaring and initializing address1 StringBuilder address1 = new StringBuilder(\"http://www.contoso.com/index.htm#search\"); // appending StringBuilder for (int i = 1; i <= 3000; i++) address1.Append(\"abcedfghijklmnopdjdjdjdjdjjddjjdjdj\"); // Converting a string to its // escaped representation // using EscapeDataString() method string value = Uri.EscapeDataString(address1.ToString()); // Displaying the result Console.WriteLine(\"Escaped string is : {0}\", value); } catch (ArgumentNullException e) { Console.WriteLine(\"stringToEscape can not be null\"); Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } catch (UriFormatException e) { Console.WriteLine(\"Length of stringToEscape should\"+ \" not exceed from 32766 characters.\"); Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } }}", "e": 29543, "s": 28201, "text": null }, { "code": null, "e": 29654, "s": 29543, "text": "Length of stringToEscape should not exceed from 32766 characters.\nException Thrown: System.UriFormatException\n" }, { "code": null, "e": 29665, "s": 29654, "text": "Reference:" }, { "code": null, "e": 29758, "s": 29665, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.uri.escapedatastring?view=netstandard-2.1" }, { "code": null, "e": 29772, "s": 29758, "text": "CSharp-method" }, { "code": null, "e": 29789, "s": 29772, "text": "CSharp-Uri-Class" }, { "code": null, "e": 29792, "s": 29789, "text": "C#" }, { "code": null, "e": 29890, "s": 29792, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29913, "s": 29890, "text": "Extension Method in C#" }, { "code": null, "e": 29941, "s": 29913, "text": "HashSet in C# with Examples" }, { "code": null, "e": 29958, "s": 29941, "text": "C# | Inheritance" }, { "code": null, "e": 29980, "s": 29958, "text": "Partial Classes in C#" }, { "code": null, "e": 30009, "s": 29980, "text": "C# | Generics - Introduction" }, { "code": null, "e": 30049, "s": 30009, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 30072, "s": 30049, "text": "Switch Statement in C#" }, { "code": null, "e": 30112, "s": 30072, "text": "Convert String to Character Array in C#" }, { "code": null, "e": 30155, "s": 30112, "text": "C# | How to insert an element in an Array?" } ]
Laravel - Action URL
Laravel 5.7 introduces a new feature called β€œcallable action URL”. This feature is similar to the one in Laravel 5.6 which accepts string in action method. The main purpose of the new syntax introduced Laravel 5.7 is to directly enable you access the controller. The syntax used in Laravel 5.6 version is as shown βˆ’ <?php $url = action('UserController@profile', ['id' => 1]); The similar action called in Laravel 5.7 is mentioned below βˆ’ <?php $url = action([PostsController::class, 'index']); One advantage with the new callable array syntax format is the feature of ability to navigate to the controller directly if a developer uses a text editor or IDE that supports code navigation. 13 Lectures 3 hours Sebastian Sulinski 35 Lectures 3.5 hours Antonio Papa 7 Lectures 1.5 hours Sebastian Sulinski 42 Lectures 1 hours Skillbakerystudios 165 Lectures 13 hours Paul Carlo Tordecilla 116 Lectures 13 hours Hafizullah Masoudi Print Add Notes Bookmark this page
[ { "code": null, "e": 2735, "s": 2472, "text": "Laravel 5.7 introduces a new feature called β€œcallable action URL”. This feature is similar to the one in Laravel 5.6 which accepts string in action method. The main purpose of the new syntax introduced Laravel 5.7 is to directly enable you access the controller." }, { "code": null, "e": 2788, "s": 2735, "text": "The syntax used in Laravel 5.6 version is as shown βˆ’" }, { "code": null, "e": 2849, "s": 2788, "text": "<?php\n$url = action('UserController@profile', ['id' => 1]);\n" }, { "code": null, "e": 2911, "s": 2849, "text": "The similar action called in Laravel 5.7 is mentioned below βˆ’" }, { "code": null, "e": 2968, "s": 2911, "text": "<?php\n$url = action([PostsController::class, 'index']);\n" }, { "code": null, "e": 3161, "s": 2968, "text": "One advantage with the new callable array syntax format is the feature of ability to navigate to the controller directly if a developer uses a text editor or IDE that supports code navigation." }, { "code": null, "e": 3194, "s": 3161, "text": "\n 13 Lectures \n 3 hours \n" }, { "code": null, "e": 3214, "s": 3194, "text": " Sebastian Sulinski" }, { "code": null, "e": 3249, "s": 3214, "text": "\n 35 Lectures \n 3.5 hours \n" }, { "code": null, "e": 3263, "s": 3249, "text": " Antonio Papa" }, { "code": null, "e": 3297, "s": 3263, "text": "\n 7 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3317, "s": 3297, "text": " Sebastian Sulinski" }, { "code": null, "e": 3350, "s": 3317, "text": "\n 42 Lectures \n 1 hours \n" }, { "code": null, "e": 3370, "s": 3350, "text": " Skillbakerystudios" }, { "code": null, "e": 3405, "s": 3370, "text": "\n 165 Lectures \n 13 hours \n" }, { "code": null, "e": 3428, "s": 3405, "text": " Paul Carlo Tordecilla" }, { "code": null, "e": 3463, "s": 3428, "text": "\n 116 Lectures \n 13 hours \n" }, { "code": null, "e": 3483, "s": 3463, "text": " Hafizullah Masoudi" }, { "code": null, "e": 3490, "s": 3483, "text": " Print" }, { "code": null, "e": 3501, "s": 3490, "text": " Add Notes" } ]
DateTimeOffset.Add() Method in C# - GeeksforGeeks
14 Jan, 2022 This method is used to return a new DateTimeOffset object that adds a specified time interval to the value of this instance. Syntax: public DateTimeOffset Add (TimeSpan timeSpan); Here, it takes a TimeSpan object that represents a positive or a negative time interval.Return Value: This method returns an object whose value is the sum of the date and time represented by the current DateTimeOffset object and the time interval represented by timeSpan.Exception: This method will give ArgumentOutOfRangeException if The resulting DateTimeOffset value is less than MinValue or the resulting DateTimeOffset value is greater than MaxValue. Below programs illustrate the use of DateTimeOffset.Add(TimeSpan) Method:Example 1: csharp // C# program to demonstrate the// DateTimeOffset.Add(TimeSpan)// Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { try { // creating object of DateTimeOffset DateTimeOffset offset = new DateTimeOffset(2007, 6, 1, 7, 55, 0, new TimeSpan(-5, 0, 0)); // creating object of TimeSpan TimeSpan elapsedTime = new TimeSpan(10, 0, 0); // adding a specified time interval // to the value of this instance. // using Add() method; DateTimeOffset value = offset.Add(elapsedTime); // Display the time Console.WriteLine("DateTimeOffset is {0}", value); } catch (ArgumentOutOfRangeException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } }} DateTimeOffset is 06/01/2007 17:55:00 -05:00 Example 2: For ArgumentOutOfRangeException csharp // C# program to demonstrate the// DateTimeOffset.Add(TimeSpan)// Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { try { // creating object of DateTimeOffset DateTimeOffset offset = DateTimeOffset.MaxValue; // creating object of TimeSpan TimeSpan elapsedTime = new TimeSpan(10, 0, 0); // adding a specified time interval // to the value of this instance. // using Add() method; DateTimeOffset value = offset.Add(elapsedTime); // Display the time Console.WriteLine("DateTimeOffset is {0}", value); } catch (ArgumentOutOfRangeException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } }} Exception Thrown: System.ArgumentOutOfRangeException Reference: https://docs.microsoft.com/en-us/dotnet/api/system.datetimeoffset.add?view=netframework-4.7.2 varshagumber28 CSharp-DateTimeOffset-Struct CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# Dictionary with examples C# | Delegates C# | Method Overriding C# | Abstract Classes C# | Replace() Method Extension Method in C# C# | String.IndexOf( ) Method | Set - 1 Difference between Ref and Out keywords in C# Introduction to .NET Framework C# | Arrays
[ { "code": null, "e": 23910, "s": 23882, "text": "\n14 Jan, 2022" }, { "code": null, "e": 24036, "s": 23910, "text": "This method is used to return a new DateTimeOffset object that adds a specified time interval to the value of this instance. " }, { "code": null, "e": 24549, "s": 24036, "text": "Syntax: public DateTimeOffset Add (TimeSpan timeSpan); Here, it takes a TimeSpan object that represents a positive or a negative time interval.Return Value: This method returns an object whose value is the sum of the date and time represented by the current DateTimeOffset object and the time interval represented by timeSpan.Exception: This method will give ArgumentOutOfRangeException if The resulting DateTimeOffset value is less than MinValue or the resulting DateTimeOffset value is greater than MaxValue. " }, { "code": null, "e": 24634, "s": 24549, "text": "Below programs illustrate the use of DateTimeOffset.Add(TimeSpan) Method:Example 1: " }, { "code": null, "e": 24641, "s": 24634, "text": "csharp" }, { "code": "// C# program to demonstrate the// DateTimeOffset.Add(TimeSpan)// Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { try { // creating object of DateTimeOffset DateTimeOffset offset = new DateTimeOffset(2007, 6, 1, 7, 55, 0, new TimeSpan(-5, 0, 0)); // creating object of TimeSpan TimeSpan elapsedTime = new TimeSpan(10, 0, 0); // adding a specified time interval // to the value of this instance. // using Add() method; DateTimeOffset value = offset.Add(elapsedTime); // Display the time Console.WriteLine(\"DateTimeOffset is {0}\", value); } catch (ArgumentOutOfRangeException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } }}", "e": 25623, "s": 24641, "text": null }, { "code": null, "e": 25668, "s": 25623, "text": "DateTimeOffset is 06/01/2007 17:55:00 -05:00" }, { "code": null, "e": 25714, "s": 25670, "text": "Example 2: For ArgumentOutOfRangeException " }, { "code": null, "e": 25721, "s": 25714, "text": "csharp" }, { "code": "// C# program to demonstrate the// DateTimeOffset.Add(TimeSpan)// Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { try { // creating object of DateTimeOffset DateTimeOffset offset = DateTimeOffset.MaxValue; // creating object of TimeSpan TimeSpan elapsedTime = new TimeSpan(10, 0, 0); // adding a specified time interval // to the value of this instance. // using Add() method; DateTimeOffset value = offset.Add(elapsedTime); // Display the time Console.WriteLine(\"DateTimeOffset is {0}\", value); } catch (ArgumentOutOfRangeException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } }}", "e": 26587, "s": 25721, "text": null }, { "code": null, "e": 26640, "s": 26587, "text": "Exception Thrown: System.ArgumentOutOfRangeException" }, { "code": null, "e": 26655, "s": 26642, "text": "Reference: " }, { "code": null, "e": 26749, "s": 26655, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.datetimeoffset.add?view=netframework-4.7.2" }, { "code": null, "e": 26766, "s": 26751, "text": "varshagumber28" }, { "code": null, "e": 26795, "s": 26766, "text": "CSharp-DateTimeOffset-Struct" }, { "code": null, "e": 26809, "s": 26795, "text": "CSharp-method" }, { "code": null, "e": 26812, "s": 26809, "text": "C#" }, { "code": null, "e": 26910, "s": 26812, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26938, "s": 26910, "text": "C# Dictionary with examples" }, { "code": null, "e": 26953, "s": 26938, "text": "C# | Delegates" }, { "code": null, "e": 26976, "s": 26953, "text": "C# | Method Overriding" }, { "code": null, "e": 26998, "s": 26976, "text": "C# | Abstract Classes" }, { "code": null, "e": 27020, "s": 26998, "text": "C# | Replace() Method" }, { "code": null, "e": 27043, "s": 27020, "text": "Extension Method in C#" }, { "code": null, "e": 27083, "s": 27043, "text": "C# | String.IndexOf( ) Method | Set - 1" }, { "code": null, "e": 27129, "s": 27083, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 27160, "s": 27129, "text": "Introduction to .NET Framework" } ]
Python | Assertion Error - GeeksforGeeks
16 Aug, 2021 Assertion Error Assertion is a programming concept used while writing a code where the user declares a condition to be true using assert statement prior to running the module. If the condition is True, the control simply moves to the next line of code. In case if it is False the program stops running and returns AssertionError Exception. The function of assert statement is the same irrespective of the language in which it is implemented, it is a language-independent concept, only the syntax varies with the programming language. Syntax of assertion: assert condition, error_message(optional) Example 1: Assertion error with error_message. Python3 # AssertionError with error_message.x = 1y = 0assert y != 0, "Invalid Operation" # denominator can't be 0print(x / y) Output : Traceback (most recent call last): File "/home/bafc2f900d9791144fbf59f477cd4059.py", line 4, in assert y!=0, "Invalid Operation" # denominator can't be 0 AssertionError: Invalid Operation The default exception handler in python will print the error_message written by the programmer, or else will just handle the error without any message. Both of the ways are valid. Handling AssertionError exception: AssertionError is inherited from Exception class, when this exception occurs and raises AssertionError there are two ways to handle, either the user handles it or the default exception handler. In Example 1 we have seen how the default exception handler does the work. Now let’s dig into handling it manually. Example 2 Python3 # Handling it manuallytry: x = 1 y = 0 assert y != 0, "Invalid Operation" print(x / y) # the errror_message provided by the user gets printedexcept AssertionError as msg: print(msg) Output : Invalid Operation Practical applications. Example 3: Testing a program. Python3 # Roots of a quadratic equationimport mathdef ShridharAcharya(a, b, c): try: assert a != 0, "Not a quadratic equation as coefficient of x ^ 2 can't be 0" D = (b * b - 4 * a*c) assert D>= 0, "Roots are imaginary" r1 = (-b + math.sqrt(D))/(2 * a) r2 = (-b - math.sqrt(D))/(2 * a) print("Roots of the quadratic equation are :", r1, "", r2) except AssertionError as msg: print(msg)ShridharAcharya(-1, 5, -6)ShridharAcharya(1, 1, 6)ShridharAcharya(2, 12, 18) Output : Roots of the quadratic equation are : 2.0 3.0 Roots are imaginary Roots of the quadratic equation are : -3.0 -3.0 This is an example to show how this exception halts the execution of the program as soon as the assert condition is False. Other useful applications : Checking values of parameters. Checking valid input/type. Detecting abuse of an interface by another programmer. Checking output of a function. as5853535 Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary How to Install PIP on Windows ? Different ways to create Pandas Dataframe Enumerate() in Python Python String | replace() Create a Pandas DataFrame from Lists *args and **kwargs in Python Check if element exists in list in Python Convert integer to string in Python How To Convert Python Dictionary To JSON?
[ { "code": null, "e": 24532, "s": 24504, "text": "\n16 Aug, 2021" }, { "code": null, "e": 24873, "s": 24532, "text": "Assertion Error Assertion is a programming concept used while writing a code where the user declares a condition to be true using assert statement prior to running the module. If the condition is True, the control simply moves to the next line of code. In case if it is False the program stops running and returns AssertionError Exception. " }, { "code": null, "e": 25068, "s": 24873, "text": "The function of assert statement is the same irrespective of the language in which it is implemented, it is a language-independent concept, only the syntax varies with the programming language. " }, { "code": null, "e": 25131, "s": 25068, "text": "Syntax of assertion: assert condition, error_message(optional)" }, { "code": null, "e": 25180, "s": 25131, "text": "Example 1: Assertion error with error_message. " }, { "code": null, "e": 25188, "s": 25180, "text": "Python3" }, { "code": "# AssertionError with error_message.x = 1y = 0assert y != 0, \"Invalid Operation\" # denominator can't be 0print(x / y)", "e": 25306, "s": 25188, "text": null }, { "code": null, "e": 25316, "s": 25306, "text": "Output : " }, { "code": null, "e": 25511, "s": 25316, "text": "Traceback (most recent call last):\n File \"/home/bafc2f900d9791144fbf59f477cd4059.py\", line 4, in \n assert y!=0, \"Invalid Operation\" # denominator can't be 0\nAssertionError: Invalid Operation" }, { "code": null, "e": 25691, "s": 25511, "text": "The default exception handler in python will print the error_message written by the programmer, or else will just handle the error without any message. Both of the ways are valid." }, { "code": null, "e": 26036, "s": 25691, "text": "Handling AssertionError exception: AssertionError is inherited from Exception class, when this exception occurs and raises AssertionError there are two ways to handle, either the user handles it or the default exception handler. In Example 1 we have seen how the default exception handler does the work. Now let’s dig into handling it manually." }, { "code": null, "e": 26048, "s": 26036, "text": "Example 2 " }, { "code": null, "e": 26056, "s": 26048, "text": "Python3" }, { "code": "# Handling it manuallytry: x = 1 y = 0 assert y != 0, \"Invalid Operation\" print(x / y) # the errror_message provided by the user gets printedexcept AssertionError as msg: print(msg)", "e": 26253, "s": 26056, "text": null }, { "code": null, "e": 26263, "s": 26253, "text": "Output : " }, { "code": null, "e": 26281, "s": 26263, "text": "Invalid Operation" }, { "code": null, "e": 26336, "s": 26281, "text": "Practical applications. Example 3: Testing a program. " }, { "code": null, "e": 26344, "s": 26336, "text": "Python3" }, { "code": "# Roots of a quadratic equationimport mathdef ShridharAcharya(a, b, c): try: assert a != 0, \"Not a quadratic equation as coefficient of x ^ 2 can't be 0\" D = (b * b - 4 * a*c) assert D>= 0, \"Roots are imaginary\" r1 = (-b + math.sqrt(D))/(2 * a) r2 = (-b - math.sqrt(D))/(2 * a) print(\"Roots of the quadratic equation are :\", r1, \"\", r2) except AssertionError as msg: print(msg)ShridharAcharya(-1, 5, -6)ShridharAcharya(1, 1, 6)ShridharAcharya(2, 12, 18)", "e": 26853, "s": 26344, "text": null }, { "code": null, "e": 26863, "s": 26853, "text": "Output : " }, { "code": null, "e": 26979, "s": 26863, "text": "Roots of the quadratic equation are : 2.0 3.0\nRoots are imaginary\nRoots of the quadratic equation are : -3.0 -3.0" }, { "code": null, "e": 27103, "s": 26979, "text": "This is an example to show how this exception halts the execution of the program as soon as the assert condition is False. " }, { "code": null, "e": 27133, "s": 27103, "text": "Other useful applications : " }, { "code": null, "e": 27164, "s": 27133, "text": "Checking values of parameters." }, { "code": null, "e": 27191, "s": 27164, "text": "Checking valid input/type." }, { "code": null, "e": 27246, "s": 27191, "text": "Detecting abuse of an interface by another programmer." }, { "code": null, "e": 27277, "s": 27246, "text": "Checking output of a function." }, { "code": null, "e": 27289, "s": 27279, "text": "as5853535" }, { "code": null, "e": 27296, "s": 27289, "text": "Python" }, { "code": null, "e": 27394, "s": 27296, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27412, "s": 27394, "text": "Python Dictionary" }, { "code": null, "e": 27444, "s": 27412, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27486, "s": 27444, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27508, "s": 27486, "text": "Enumerate() in Python" }, { "code": null, "e": 27534, "s": 27508, "text": "Python String | replace()" }, { "code": null, "e": 27571, "s": 27534, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 27600, "s": 27571, "text": "*args and **kwargs in Python" }, { "code": null, "e": 27642, "s": 27600, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27678, "s": 27642, "text": "Convert integer to string in Python" } ]
Change the label size and tick label size of colorbar using Matplotlib in Python - GeeksforGeeks
05 Nov, 2021 In this article, we will learn how to change the label size and tick label size of colorbar in Matplotlib using Python. Labels are a kind of assigning name that can be applied to any node in the graph. They are a name only and so labels are either present or absent. To properly label a graph, helps to identify the x-axis and y-axis. Each tick mark represents a specified value of units on a continuous scale or the value of a category on a categorical scale. The X-axis and the Y-axis are noted on the graph. Here we will discuss how to change the label size and tick label size of color-bar, using different examples to make it more clear. Syntax: # Change the label size im.figure.axes[0].tick_params(axis=”both”, labelsize=21) axis = x, y or both. labelsize = int # Change the tick label size of color-bar im.figure.axes[1].tick_params(axis=””, labelsize=21) axis = x, y or both. labelsize = int Example 1: In this example, we are changing the label size in Plotly Express with the help of method im.figure.axes[0].tick_params(axis=”both”, labelsize=21), by passing the parameters axis value as both axis and label size as 21. Python3 # importing librariesimport numpy as npimport matplotlib as mplimport matplotlib.pyplot as plt # setup dataa = np.random.rand(10, 10)im = plt.imshow(a, cmap="bwr")cb = plt.colorbar(im, orientation='horizontal') # change the label sizeim.figure.axes[0].tick_params(axis="both", labelsize=21) plt.show() Output: Example 2: In this Example, we are changing the label size in Plotly Express with the help of method im.figure.axes[0].tick_params(axis=”x”, labelsize=18), by passing the parameter axis value as x and label size as 18. Python3 # importing librariesimport numpy as npimport matplotlib as mplimport matplotlib.pyplot as plt # setup dataa = np.random.rand(10, 10)im = plt.imshow(a, cmap="bwr")cb = plt.colorbar(im, orientation='horizontal') # change the tick label size of colorbarim.figure.axes[1].tick_params(axis="x", labelsize=18) plt.show() Output: Example 3: In this example, we are changing the label size in Plotly Express with the help of method im.figure.axes[0].tick_params(axis=”y”, labelsize=21), bypassing the parameter axis value as y and label size as 21. Python3 # importing librariesimport numpy as npfrom matplotlib import pyplot as plt # setup dataplt.rcParams["figure.figsize"] = [7.00, 3.50]plt.rcParams["figure.autolayout"] = Truedata = np.random.rand(6, 6)im = plt.imshow(data, interpolation="nearest", cmap="Accent")cbar = plt.colorbar(im) # change the label sizeim.figure.axes[0].tick_params(axis="both", labelsize=21) # change the tick label size of colorbarim.figure.axes[1].tick_params(axis="y", labelsize=21) plt.show() Output: Picked Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? Selecting rows in pandas DataFrame based on conditions How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Get unique values from a list Defaultdict in Python Python OOPs Concepts Python | os.path.join() method Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24292, "s": 24264, "text": "\n05 Nov, 2021" }, { "code": null, "e": 24412, "s": 24292, "text": "In this article, we will learn how to change the label size and tick label size of colorbar in Matplotlib using Python." }, { "code": null, "e": 24803, "s": 24412, "text": "Labels are a kind of assigning name that can be applied to any node in the graph. They are a name only and so labels are either present or absent. To properly label a graph, helps to identify the x-axis and y-axis. Each tick mark represents a specified value of units on a continuous scale or the value of a category on a categorical scale. The X-axis and the Y-axis are noted on the graph." }, { "code": null, "e": 24935, "s": 24803, "text": "Here we will discuss how to change the label size and tick label size of color-bar, using different examples to make it more clear." }, { "code": null, "e": 24945, "s": 24935, "text": " Syntax: " }, { "code": null, "e": 24969, "s": 24945, "text": "# Change the label size" }, { "code": null, "e": 25026, "s": 24969, "text": "im.figure.axes[0].tick_params(axis=”both”, labelsize=21)" }, { "code": null, "e": 25047, "s": 25026, "text": "axis = x, y or both." }, { "code": null, "e": 25063, "s": 25047, "text": "labelsize = int" }, { "code": null, "e": 25105, "s": 25063, "text": "# Change the tick label size of color-bar" }, { "code": null, "e": 25158, "s": 25105, "text": "im.figure.axes[1].tick_params(axis=””, labelsize=21)" }, { "code": null, "e": 25179, "s": 25158, "text": "axis = x, y or both." }, { "code": null, "e": 25195, "s": 25179, "text": "labelsize = int" }, { "code": null, "e": 25426, "s": 25195, "text": "Example 1: In this example, we are changing the label size in Plotly Express with the help of method im.figure.axes[0].tick_params(axis=”both”, labelsize=21), by passing the parameters axis value as both axis and label size as 21." }, { "code": null, "e": 25434, "s": 25426, "text": "Python3" }, { "code": "# importing librariesimport numpy as npimport matplotlib as mplimport matplotlib.pyplot as plt # setup dataa = np.random.rand(10, 10)im = plt.imshow(a, cmap=\"bwr\")cb = plt.colorbar(im, orientation='horizontal') # change the label sizeim.figure.axes[0].tick_params(axis=\"both\", labelsize=21) plt.show()", "e": 25739, "s": 25434, "text": null }, { "code": null, "e": 25747, "s": 25739, "text": "Output:" }, { "code": null, "e": 25966, "s": 25747, "text": "Example 2: In this Example, we are changing the label size in Plotly Express with the help of method im.figure.axes[0].tick_params(axis=”x”, labelsize=18), by passing the parameter axis value as x and label size as 18." }, { "code": null, "e": 25974, "s": 25966, "text": "Python3" }, { "code": "# importing librariesimport numpy as npimport matplotlib as mplimport matplotlib.pyplot as plt # setup dataa = np.random.rand(10, 10)im = plt.imshow(a, cmap=\"bwr\")cb = plt.colorbar(im, orientation='horizontal') # change the tick label size of colorbarim.figure.axes[1].tick_params(axis=\"x\", labelsize=18) plt.show()", "e": 26293, "s": 25974, "text": null }, { "code": null, "e": 26301, "s": 26293, "text": "Output:" }, { "code": null, "e": 26519, "s": 26301, "text": "Example 3: In this example, we are changing the label size in Plotly Express with the help of method im.figure.axes[0].tick_params(axis=”y”, labelsize=21), bypassing the parameter axis value as y and label size as 21." }, { "code": null, "e": 26527, "s": 26519, "text": "Python3" }, { "code": "# importing librariesimport numpy as npfrom matplotlib import pyplot as plt # setup dataplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]plt.rcParams[\"figure.autolayout\"] = Truedata = np.random.rand(6, 6)im = plt.imshow(data, interpolation=\"nearest\", cmap=\"Accent\")cbar = plt.colorbar(im) # change the label sizeim.figure.axes[0].tick_params(axis=\"both\", labelsize=21) # change the tick label size of colorbarim.figure.axes[1].tick_params(axis=\"y\", labelsize=21) plt.show()", "e": 27001, "s": 26527, "text": null }, { "code": null, "e": 27009, "s": 27001, "text": "Output:" }, { "code": null, "e": 27016, "s": 27009, "text": "Picked" }, { "code": null, "e": 27034, "s": 27016, "text": "Python-matplotlib" }, { "code": null, "e": 27041, "s": 27034, "text": "Python" }, { "code": null, "e": 27139, "s": 27041, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27148, "s": 27139, "text": "Comments" }, { "code": null, "e": 27161, "s": 27148, "text": "Old Comments" }, { "code": null, "e": 27193, "s": 27161, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27248, "s": 27193, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 27304, "s": 27248, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27346, "s": 27304, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27388, "s": 27346, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27427, "s": 27388, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27449, "s": 27427, "text": "Defaultdict in Python" }, { "code": null, "e": 27470, "s": 27449, "text": "Python OOPs Concepts" }, { "code": null, "e": 27501, "s": 27470, "text": "Python | os.path.join() method" } ]
Guessing the Number Game using Android Studio - GeeksforGeeks
09 Jul, 2020 A Simple Guess the number application in which application generates the random number between 1 to 100 and the user has to guess that Number. It is a simple and basic application that uses basic widgets and libraries.Approach: Step1: Creating a new project Click on File option at topmost corner in left. Then click on new and open a new project and name it (Here it is named Guess the number). Now select the Empty Activity with language as Java. Don’t change any other option.Note: By default, there will be two files activity_main.xml and MainActivity.java. Note: By default, there will be two files activity_main.xml and MainActivity.java. Step2: Designing the UI Add the below code in activity_main.xml file. Here two TextViews , one EditText and a Button is added. TextViews are used to display the message and edittext widget is used by the user to enter the guessed number and the button is required to submit the entered value.activity_main.xmlactivity_main.xml<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <RelativeLayout android:layout_width="409dp" android:layout_height="729dp" android:background="#F3A68E" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="1.0" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent"> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentStart="true" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:layout_marginStart="77dp" android:layout_marginLeft="77dp" android:layout_marginTop="47dp" android:background="#FF9100" android:text="GUESS THE NUMBER" android:textSize="30sp" /> <TextView android:id="@+id/textView2" android:layout_width="391dp" android:layout_height="68dp" android:layout_alignParentStart="true" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:layout_marginStart="21dp" android:layout_marginLeft="21dp" android:layout_marginTop="147dp" android:text="I am thinking a number between 1 to 100. Can you guess what it is ?" android:textSize="24sp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" /> <EditText android:id="@+id/editId" android:layout_width="348dp" android:layout_height="67dp" android:layout_alignParentTop="true" android:layout_alignParentEnd="true" android:layout_alignParentRight="true" android:layout_marginTop="271dp" android:layout_marginEnd="30dp" android:layout_marginRight="30dp" android:ems="10" android:gravity="center" android:hint="ENTER" android:inputType="numberDecimal" /> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentEnd="true" android:layout_alignParentRight="true" android:layout_alignParentBottom="true" android:layout_marginEnd="152dp" android:layout_marginRight="152dp" android:layout_marginBottom="266dp" android:onClick="clickFunction" android:text="GUESS" android:textSize="30sp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" /> </RelativeLayout></androidx.constraintlayout.widget.ConstraintLayout>After adding the above code in activity_main.Xml file, the UI will be like: activity_main.xml <?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <RelativeLayout android:layout_width="409dp" android:layout_height="729dp" android:background="#F3A68E" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="1.0" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent"> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentStart="true" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:layout_marginStart="77dp" android:layout_marginLeft="77dp" android:layout_marginTop="47dp" android:background="#FF9100" android:text="GUESS THE NUMBER" android:textSize="30sp" /> <TextView android:id="@+id/textView2" android:layout_width="391dp" android:layout_height="68dp" android:layout_alignParentStart="true" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:layout_marginStart="21dp" android:layout_marginLeft="21dp" android:layout_marginTop="147dp" android:text="I am thinking a number between 1 to 100. Can you guess what it is ?" android:textSize="24sp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" /> <EditText android:id="@+id/editId" android:layout_width="348dp" android:layout_height="67dp" android:layout_alignParentTop="true" android:layout_alignParentEnd="true" android:layout_alignParentRight="true" android:layout_marginTop="271dp" android:layout_marginEnd="30dp" android:layout_marginRight="30dp" android:ems="10" android:gravity="center" android:hint="ENTER" android:inputType="numberDecimal" /> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentEnd="true" android:layout_alignParentRight="true" android:layout_alignParentBottom="true" android:layout_marginEnd="152dp" android:layout_marginRight="152dp" android:layout_marginBottom="266dp" android:onClick="clickFunction" android:text="GUESS" android:textSize="30sp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" /> </RelativeLayout></androidx.constraintlayout.widget.ConstraintLayout> After adding the above code in activity_main.Xml file, the UI will be like: Step3: Working with Java file Open the MainActivity.java, within the class, add a method getRandomNumber() which will return the random number between 1 to 100. OnCreate() method is invoked when the app is launched therefore getRandomNumber() function is called from inside so that random number is generated. The value from EditText is taken by using below code:EditText variable = (EditText)findViewById(R.id.editId);here editId is id for EditText and variable is a Variable name. EditText variable = (EditText)findViewById(R.id.editId); here editId is id for EditText and variable is a Variable name. In variable, data stored is in the form of String so it is converted into Integer by using code below:userGuessing = Integer.parseInt(variable.getText().toString()); userGuessing = Integer.parseInt(variable.getText().toString()); OnClick function is invoked when the user clicks the button. Here the value entered by the user is taken and if-else conditions are used to find whether the user guesses the right number or not and if the guessed number is wrong, ask the user to try again. In the end, show Toast which will give the hint to the user to guess the correct number. Java code for MainActivity.java is: MainActivity.java package com.example.guessthenumber; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle;import android.view.View;import android.widget.EditText;import android.widget.Toast; public class MainActivity extends AppCompatActivity { int result; static int getRandomNumber(int max, int min) { return (int)((Math.random() * (max - min)) + min); } public void makeToast(String str) { Toast.makeText(MainActivity.this, str, Toast.LENGTH_SHORT).show(); } public void clickFunction(View view) { int userGuessing; EditText variable = (EditText)findViewById(R.id.editId); userGuessing = Integer.parseInt(variable.getText().toString()); if (userGuessing < result) { makeToast("Think of Higher Number, Try Again"); } else if (userGuessing > result) { makeToast("Think of Lower Number, Try Again"); } else { makeToast("Congratulations,"+" You Got the Number"); } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); int min = 1; int max = 100; result = getRandomNumber(min, max); }} Output: If Number guessed is less than Random Number If Number guessed is more than Random Number If Number guessed is equal to Random Number android Java Project Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Stream In Java Interfaces in Java How to iterate any Map in Java SDE SHEET - A Complete Guide for SDE Preparation Working with zip files in Python XML parsing in Python Python | Simple GUI calculator using Tkinter Implementing Web Scraping in Python with BeautifulSoup
[ { "code": null, "e": 25757, "s": 25729, "text": "\n09 Jul, 2020" }, { "code": null, "e": 25985, "s": 25757, "text": "A Simple Guess the number application in which application generates the random number between 1 to 100 and the user has to guess that Number. It is a simple and basic application that uses basic widgets and libraries.Approach:" }, { "code": null, "e": 26015, "s": 25985, "text": "Step1: Creating a new project" }, { "code": null, "e": 26063, "s": 26015, "text": "Click on File option at topmost corner in left." }, { "code": null, "e": 26153, "s": 26063, "text": "Then click on new and open a new project and name it (Here it is named Guess the number)." }, { "code": null, "e": 26319, "s": 26153, "text": "Now select the Empty Activity with language as Java. Don’t change any other option.Note: By default, there will be two files activity_main.xml and MainActivity.java." }, { "code": null, "e": 26402, "s": 26319, "text": "Note: By default, there will be two files activity_main.xml and MainActivity.java." }, { "code": null, "e": 26426, "s": 26402, "text": "Step2: Designing the UI" }, { "code": null, "e": 30058, "s": 26426, "text": "Add the below code in activity_main.xml file. Here two TextViews , one EditText and a Button is added. TextViews are used to display the message and edittext widget is used by the user to enter the guessed number and the button is required to submit the entered value.activity_main.xmlactivity_main.xml<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <RelativeLayout android:layout_width=\"409dp\" android:layout_height=\"729dp\" android:background=\"#F3A68E\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintHorizontal_bias=\"1.0\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\"> <TextView android:id=\"@+id/textView\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_alignParentStart=\"true\" android:layout_alignParentLeft=\"true\" android:layout_alignParentTop=\"true\" android:layout_marginStart=\"77dp\" android:layout_marginLeft=\"77dp\" android:layout_marginTop=\"47dp\" android:background=\"#FF9100\" android:text=\"GUESS THE NUMBER\" android:textSize=\"30sp\" /> <TextView android:id=\"@+id/textView2\" android:layout_width=\"391dp\" android:layout_height=\"68dp\" android:layout_alignParentStart=\"true\" android:layout_alignParentLeft=\"true\" android:layout_alignParentTop=\"true\" android:layout_marginStart=\"21dp\" android:layout_marginLeft=\"21dp\" android:layout_marginTop=\"147dp\" android:text=\"I am thinking a number between 1 to 100. Can you guess what it is ?\" android:textSize=\"24sp\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" /> <EditText android:id=\"@+id/editId\" android:layout_width=\"348dp\" android:layout_height=\"67dp\" android:layout_alignParentTop=\"true\" android:layout_alignParentEnd=\"true\" android:layout_alignParentRight=\"true\" android:layout_marginTop=\"271dp\" android:layout_marginEnd=\"30dp\" android:layout_marginRight=\"30dp\" android:ems=\"10\" android:gravity=\"center\" android:hint=\"ENTER\" android:inputType=\"numberDecimal\" /> <Button android:id=\"@+id/button\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_alignParentEnd=\"true\" android:layout_alignParentRight=\"true\" android:layout_alignParentBottom=\"true\" android:layout_marginEnd=\"152dp\" android:layout_marginRight=\"152dp\" android:layout_marginBottom=\"266dp\" android:onClick=\"clickFunction\" android:text=\"GUESS\" android:textSize=\"30sp\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" /> </RelativeLayout></androidx.constraintlayout.widget.ConstraintLayout>After adding the above code in activity_main.Xml file, the UI will be like:" }, { "code": null, "e": 30076, "s": 30058, "text": "activity_main.xml" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <RelativeLayout android:layout_width=\"409dp\" android:layout_height=\"729dp\" android:background=\"#F3A68E\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintHorizontal_bias=\"1.0\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\"> <TextView android:id=\"@+id/textView\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_alignParentStart=\"true\" android:layout_alignParentLeft=\"true\" android:layout_alignParentTop=\"true\" android:layout_marginStart=\"77dp\" android:layout_marginLeft=\"77dp\" android:layout_marginTop=\"47dp\" android:background=\"#FF9100\" android:text=\"GUESS THE NUMBER\" android:textSize=\"30sp\" /> <TextView android:id=\"@+id/textView2\" android:layout_width=\"391dp\" android:layout_height=\"68dp\" android:layout_alignParentStart=\"true\" android:layout_alignParentLeft=\"true\" android:layout_alignParentTop=\"true\" android:layout_marginStart=\"21dp\" android:layout_marginLeft=\"21dp\" android:layout_marginTop=\"147dp\" android:text=\"I am thinking a number between 1 to 100. Can you guess what it is ?\" android:textSize=\"24sp\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" /> <EditText android:id=\"@+id/editId\" android:layout_width=\"348dp\" android:layout_height=\"67dp\" android:layout_alignParentTop=\"true\" android:layout_alignParentEnd=\"true\" android:layout_alignParentRight=\"true\" android:layout_marginTop=\"271dp\" android:layout_marginEnd=\"30dp\" android:layout_marginRight=\"30dp\" android:ems=\"10\" android:gravity=\"center\" android:hint=\"ENTER\" android:inputType=\"numberDecimal\" /> <Button android:id=\"@+id/button\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_alignParentEnd=\"true\" android:layout_alignParentRight=\"true\" android:layout_alignParentBottom=\"true\" android:layout_marginEnd=\"152dp\" android:layout_marginRight=\"152dp\" android:layout_marginBottom=\"266dp\" android:onClick=\"clickFunction\" android:text=\"GUESS\" android:textSize=\"30sp\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" /> </RelativeLayout></androidx.constraintlayout.widget.ConstraintLayout>", "e": 33331, "s": 30076, "text": null }, { "code": null, "e": 33407, "s": 33331, "text": "After adding the above code in activity_main.Xml file, the UI will be like:" }, { "code": null, "e": 33437, "s": 33407, "text": "Step3: Working with Java file" }, { "code": null, "e": 33568, "s": 33437, "text": "Open the MainActivity.java, within the class, add a method getRandomNumber() which will return the random number between 1 to 100." }, { "code": null, "e": 33717, "s": 33568, "text": "OnCreate() method is invoked when the app is launched therefore getRandomNumber() function is called from inside so that random number is generated." }, { "code": null, "e": 33890, "s": 33717, "text": "The value from EditText is taken by using below code:EditText variable = (EditText)findViewById(R.id.editId);here editId is id for EditText and variable is a Variable name." }, { "code": null, "e": 33947, "s": 33890, "text": "EditText variable = (EditText)findViewById(R.id.editId);" }, { "code": null, "e": 34011, "s": 33947, "text": "here editId is id for EditText and variable is a Variable name." }, { "code": null, "e": 34177, "s": 34011, "text": "In variable, data stored is in the form of String so it is converted into Integer by using code below:userGuessing = Integer.parseInt(variable.getText().toString());" }, { "code": null, "e": 34241, "s": 34177, "text": "userGuessing = Integer.parseInt(variable.getText().toString());" }, { "code": null, "e": 34498, "s": 34241, "text": "OnClick function is invoked when the user clicks the button. Here the value entered by the user is taken and if-else conditions are used to find whether the user guesses the right number or not and if the guessed number is wrong, ask the user to try again." }, { "code": null, "e": 34587, "s": 34498, "text": "In the end, show Toast which will give the hint to the user to guess the correct number." }, { "code": null, "e": 34623, "s": 34587, "text": "Java code for MainActivity.java is:" }, { "code": null, "e": 34641, "s": 34623, "text": "MainActivity.java" }, { "code": "package com.example.guessthenumber; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle;import android.view.View;import android.widget.EditText;import android.widget.Toast; public class MainActivity extends AppCompatActivity { int result; static int getRandomNumber(int max, int min) { return (int)((Math.random() * (max - min)) + min); } public void makeToast(String str) { Toast.makeText(MainActivity.this, str, Toast.LENGTH_SHORT).show(); } public void clickFunction(View view) { int userGuessing; EditText variable = (EditText)findViewById(R.id.editId); userGuessing = Integer.parseInt(variable.getText().toString()); if (userGuessing < result) { makeToast(\"Think of Higher Number, Try Again\"); } else if (userGuessing > result) { makeToast(\"Think of Lower Number, Try Again\"); } else { makeToast(\"Congratulations,\"+\" You Got the Number\"); } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); int min = 1; int max = 100; result = getRandomNumber(min, max); }}", "e": 35917, "s": 34641, "text": null }, { "code": null, "e": 35925, "s": 35917, "text": "Output:" }, { "code": null, "e": 35970, "s": 35925, "text": "If Number guessed is less than Random Number" }, { "code": null, "e": 36015, "s": 35970, "text": "If Number guessed is more than Random Number" }, { "code": null, "e": 36059, "s": 36015, "text": "If Number guessed is equal to Random Number" }, { "code": null, "e": 36067, "s": 36059, "text": "android" }, { "code": null, "e": 36072, "s": 36067, "text": "Java" }, { "code": null, "e": 36080, "s": 36072, "text": "Project" }, { "code": null, "e": 36085, "s": 36080, "text": "Java" }, { "code": null, "e": 36183, "s": 36085, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36234, "s": 36183, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 36264, "s": 36234, "text": "HashMap in Java with Examples" }, { "code": null, "e": 36279, "s": 36264, "text": "Stream In Java" }, { "code": null, "e": 36298, "s": 36279, "text": "Interfaces in Java" }, { "code": null, "e": 36329, "s": 36298, "text": "How to iterate any Map in Java" }, { "code": null, "e": 36378, "s": 36329, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 36411, "s": 36378, "text": "Working with zip files in Python" }, { "code": null, "e": 36433, "s": 36411, "text": "XML parsing in Python" }, { "code": null, "e": 36478, "s": 36433, "text": "Python | Simple GUI calculator using Tkinter" } ]
Neo4j - Max Function
It takes a set of rows and a <property-name> of a node or relationship as an input and finds the maximum value from the given <property-name> column of the given rows. Following is the syntax of the MAX() function. MAX(<property-name>) Following is a sample Cypher query, which demonstrates the usage of the function MAX() in Neo4j. Here we are trying to calculate the maximum salaries of the employees. MATCH (n:employee) RETURN MAX(n.sal) To execute the above query, carry out the following steps βˆ’ Step 1 βˆ’ Open the Neo4j desktop App and start the Neo4j Server. Open the built-in browser app of Neo4j using the URL http://localhost:7474/ as shown in the following screenshot. Step 2 βˆ’ Copy and paste the desired query in the dollar prompt and press the play button (to execute the query) highlighted in the following screenshot. On executing, you will get the following result. Print Add Notes Bookmark this page
[ { "code": null, "e": 2507, "s": 2339, "text": "It takes a set of rows and a <property-name> of a node or relationship as an input and finds the maximum value from the given <property-name> column of the given rows." }, { "code": null, "e": 2554, "s": 2507, "text": "Following is the syntax of the MAX() function." }, { "code": null, "e": 2577, "s": 2554, "text": "MAX(<property-name>) \n" }, { "code": null, "e": 2745, "s": 2577, "text": "Following is a sample Cypher query, which demonstrates the usage of the function MAX() in Neo4j. Here we are trying to calculate the maximum salaries of the employees." }, { "code": null, "e": 2782, "s": 2745, "text": "MATCH (n:employee) RETURN MAX(n.sal)" }, { "code": null, "e": 2842, "s": 2782, "text": "To execute the above query, carry out the following steps βˆ’" }, { "code": null, "e": 3020, "s": 2842, "text": "Step 1 βˆ’ Open the Neo4j desktop App and start the Neo4j Server. Open the built-in browser app of Neo4j using the URL http://localhost:7474/ as shown in the following screenshot." }, { "code": null, "e": 3173, "s": 3020, "text": "Step 2 βˆ’ Copy and paste the desired query in the dollar prompt and press the play button (to execute the query) highlighted in the following screenshot." }, { "code": null, "e": 3222, "s": 3173, "text": "On executing, you will get the following result." }, { "code": null, "e": 3229, "s": 3222, "text": " Print" }, { "code": null, "e": 3240, "s": 3229, "text": " Add Notes" } ]
Ceiling in right side for every element in an array - GeeksforGeeks
04 Feb, 2022 Given an array of integers, find the closest greater element for every element. If there is no greater element then print -1Examples: Input : arr[] = {10, 5, 11, 10, 20, 12} Output : 10 10 12 12 -1 -1Input : arr[] = {50, 20, 200, 100, 30} Output : 100 30 -1 -1 -1 A simple solution is to run two nested loops. We pick an outer element one by one. For every picked element, we traverse right side array and find closest greater or equal element. Time complexity of this solution is O(n*n)A better solution is to use sorting. We sort all elements, then for every element, traverse toward right until we find a greater element (Note that there can be multiple occurrences of an element).An efficient solution is to use Self Balancing BST (Implemented as set in C++ and TreeSet in Java). In a Self Balancing BST, we can do both insert and ceiling operations in O(Log n) time. C++ Java C# // C++ program to find ceiling on right side for// every element.#include <bits/stdc++.h>using namespace std; void closestGreater(int arr[], int n){ set<int> s; vector<int> ceilings; // Find smallest greater or equal element // for every array element for (int i = n - 1; i >= 0; i--) { auto greater = s.lower_bound(arr[i]); if (greater == s.end()) ceilings.push_back(-1); else ceilings.push_back(*greater); s.insert(arr[i]); } for (int i = n - 1; i >= 0; i--) cout << ceilings[i] << " ";} int main(){ int arr[] = { 50, 20, 200, 100, 30 }; closestGreater(arr, 5); return 0;} // Java program to find ceiling on right side for// every element.import java.util.*; class TreeSetDemo { public static void closestGreater(int[] arr) { int n = arr.length; TreeSet<Integer> ts = new TreeSet<Integer>(); ArrayList<Integer> ceilings = new ArrayList<Integer>(n); // Find smallest greater or equal element // for every array element for (int i = n - 1; i >= 0; i--) { Integer greater = ts.ceiling(arr[i]); if (greater == null) ceilings.add(-1); else ceilings.add(greater); ts.add(arr[i]); } for (int i = n - 1; i >= 0; i--) System.out.print(ceilings.get(i) + " "); } public static void main(String[] args) { int[] arr = { 50, 20, 200, 100, 30 }; closestGreater(arr); }} // C# program to find ceiling on right side for// every element.using System;using System.Collections.Generic; public class TreeSetDemo { public static void closestGreater(int[] arr) { int n = arr.Length; SortedSet<int> ts = new SortedSet<int>(); List<int> ceilings = new List<int>(n); // Find smallest greater or equal element // for every array element for (int i = n - 1; i >= 0; i--) { int greater = lower_bound(ts, arr[i]); if (greater == -1) ceilings.Add(-1); else ceilings.Add(greater); ts.Add(arr[i]); } ceilings.Sort((a,b)=>a-b); for (int i = n - 1; i >= 0; i--) Console.Write(ceilings[i] + " "); } public static int lower_bound(SortedSet<int> s, int val) { List<int> temp = new List<int>(); temp.AddRange(s); temp.Sort(); temp.Reverse(); if (temp.IndexOf(val) + 1 == temp.Count) return -1; else if(temp[temp.IndexOf(val) +1]>val) return -1; else return temp[temp.IndexOf(val) +1]; } public static void Main(String[] args) { int[] arr = { 50, 20, 200, 100, 30 }; closestGreater(arr); }} // This code is contributed by Rajput-Ji 100 30 -1 -1 -1 Time Complexity : O(n Log n) Rajput-Ji Java-ArrayList java-treeset Arrays Binary Search Tree Arrays Binary Search Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Chocolate Distribution Problem Window Sliding Technique Reversal algorithm for array rotation Next Greater Element Find duplicates in O(n) time and O(1) extra space | Set 1 Binary Search Tree | Set 1 (Search and Insertion) AVL Tree | Set 1 (Insertion) Binary Search Tree | Set 2 (Delete) A program to check if a binary tree is BST or not Construct BST from given preorder traversal | Set 1
[ { "code": null, "e": 26065, "s": 26037, "text": "\n04 Feb, 2022" }, { "code": null, "e": 26201, "s": 26065, "text": "Given an array of integers, find the closest greater element for every element. If there is no greater element then print -1Examples: " }, { "code": null, "e": 26333, "s": 26201, "text": "Input : arr[] = {10, 5, 11, 10, 20, 12} Output : 10 10 12 12 -1 -1Input : arr[] = {50, 20, 200, 100, 30} Output : 100 30 -1 -1 -1 " }, { "code": null, "e": 26944, "s": 26335, "text": "A simple solution is to run two nested loops. We pick an outer element one by one. For every picked element, we traverse right side array and find closest greater or equal element. Time complexity of this solution is O(n*n)A better solution is to use sorting. We sort all elements, then for every element, traverse toward right until we find a greater element (Note that there can be multiple occurrences of an element).An efficient solution is to use Self Balancing BST (Implemented as set in C++ and TreeSet in Java). In a Self Balancing BST, we can do both insert and ceiling operations in O(Log n) time. " }, { "code": null, "e": 26948, "s": 26944, "text": "C++" }, { "code": null, "e": 26953, "s": 26948, "text": "Java" }, { "code": null, "e": 26956, "s": 26953, "text": "C#" }, { "code": "// C++ program to find ceiling on right side for// every element.#include <bits/stdc++.h>using namespace std; void closestGreater(int arr[], int n){ set<int> s; vector<int> ceilings; // Find smallest greater or equal element // for every array element for (int i = n - 1; i >= 0; i--) { auto greater = s.lower_bound(arr[i]); if (greater == s.end()) ceilings.push_back(-1); else ceilings.push_back(*greater); s.insert(arr[i]); } for (int i = n - 1; i >= 0; i--) cout << ceilings[i] << \" \";} int main(){ int arr[] = { 50, 20, 200, 100, 30 }; closestGreater(arr, 5); return 0;}", "e": 27620, "s": 26956, "text": null }, { "code": "// Java program to find ceiling on right side for// every element.import java.util.*; class TreeSetDemo { public static void closestGreater(int[] arr) { int n = arr.length; TreeSet<Integer> ts = new TreeSet<Integer>(); ArrayList<Integer> ceilings = new ArrayList<Integer>(n); // Find smallest greater or equal element // for every array element for (int i = n - 1; i >= 0; i--) { Integer greater = ts.ceiling(arr[i]); if (greater == null) ceilings.add(-1); else ceilings.add(greater); ts.add(arr[i]); } for (int i = n - 1; i >= 0; i--) System.out.print(ceilings.get(i) + \" \"); } public static void main(String[] args) { int[] arr = { 50, 20, 200, 100, 30 }; closestGreater(arr); }}", "e": 28478, "s": 27620, "text": null }, { "code": "// C# program to find ceiling on right side for// every element.using System;using System.Collections.Generic; public class TreeSetDemo { public static void closestGreater(int[] arr) { int n = arr.Length; SortedSet<int> ts = new SortedSet<int>(); List<int> ceilings = new List<int>(n); // Find smallest greater or equal element // for every array element for (int i = n - 1; i >= 0; i--) { int greater = lower_bound(ts, arr[i]); if (greater == -1) ceilings.Add(-1); else ceilings.Add(greater); ts.Add(arr[i]); } ceilings.Sort((a,b)=>a-b); for (int i = n - 1; i >= 0; i--) Console.Write(ceilings[i] + \" \"); } public static int lower_bound(SortedSet<int> s, int val) { List<int> temp = new List<int>(); temp.AddRange(s); temp.Sort(); temp.Reverse(); if (temp.IndexOf(val) + 1 == temp.Count) return -1; else if(temp[temp.IndexOf(val) +1]>val) return -1; else return temp[temp.IndexOf(val) +1]; } public static void Main(String[] args) { int[] arr = { 50, 20, 200, 100, 30 }; closestGreater(arr); }} // This code is contributed by Rajput-Ji", "e": 29635, "s": 28478, "text": null }, { "code": null, "e": 29651, "s": 29635, "text": "100 30 -1 -1 -1" }, { "code": null, "e": 29683, "s": 29653, "text": "Time Complexity : O(n Log n) " }, { "code": null, "e": 29693, "s": 29683, "text": "Rajput-Ji" }, { "code": null, "e": 29708, "s": 29693, "text": "Java-ArrayList" }, { "code": null, "e": 29721, "s": 29708, "text": "java-treeset" }, { "code": null, "e": 29728, "s": 29721, "text": "Arrays" }, { "code": null, "e": 29747, "s": 29728, "text": "Binary Search Tree" }, { "code": null, "e": 29754, "s": 29747, "text": "Arrays" }, { "code": null, "e": 29773, "s": 29754, "text": "Binary Search Tree" }, { "code": null, "e": 29871, "s": 29773, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29902, "s": 29871, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 29927, "s": 29902, "text": "Window Sliding Technique" }, { "code": null, "e": 29965, "s": 29927, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 29986, "s": 29965, "text": "Next Greater Element" }, { "code": null, "e": 30044, "s": 29986, "text": "Find duplicates in O(n) time and O(1) extra space | Set 1" }, { "code": null, "e": 30094, "s": 30044, "text": "Binary Search Tree | Set 1 (Search and Insertion)" }, { "code": null, "e": 30123, "s": 30094, "text": "AVL Tree | Set 1 (Insertion)" }, { "code": null, "e": 30159, "s": 30123, "text": "Binary Search Tree | Set 2 (Delete)" }, { "code": null, "e": 30209, "s": 30159, "text": "A program to check if a binary tree is BST or not" } ]
How to extract the p-value and F-statistic from aov output in R?
The analysis of variance technique helps us to identify whether there exists a significant mean difference in more than two variables or not. To detect this difference, we either use F-statistic value or p-value. If the F-statistic value is greater than the critical value of F or if p-value is less than the level of significance then we say that at least one of the means is significantly different from the rest. To extract the p-value and F-statistic value, we can make use of summary function of the ANOVA model. Live Demo set.seed(123) Group<-rep(c("G1","G2","G3","G4"),times=5) Response<-runif(20,2,5) df<-data.frame(Group,Response) df Group Response 1 G1 2.862733 2 G2 4.364915 3 G3 3.226931 4 G4 4.649052 5 G1 4.821402 6 G2 2.136669 7 G3 3.584316 8 G4 4.677257 9 G1 3.654305 10 G2 3.369844 11 G3 4.870500 12 G4 3.360002 13 G1 4.032712 14 G2 3.717900 15 G3 2.308774 16 G4 4.699475 17 G1 2.738263 18 G2 2.126179 19 G3 2.983762 20 G4 4.863511 ANOVA<-aov(Response~Group,df) summary(ANOVA) Df Sum Sq Mean Sq F value Pr(F) Group 3 4.813 1.6043 2.141 0.135 Residuals 16 11.990 0.7494 summary(ANOVA)[[1]][1,4:5] F value Pr(F) Group 2.1408 0.1351 If we want to extract only p-value then it can be done as shown below βˆ’ summary(ANOVA)[[1]][1,5] [1] 0.1351315 If we want to extract only F-value then it can be done as shown below βˆ’ summary(ANOVA)[[1]][1,4] [1] 2.140825 Let’s have a look at one more example βˆ’ Live Demo Factor<-rep(c("F1","F2","F3","F4","F5"),each=4) Dependent<-rnorm(20,2) ANOVA_data<-data.frame(Factor,Dependent) ANOVA_data Factor Dependent 1 F1 2.2236414 2 F1 4.0072015 3 F1 3.0119791 4 F1 1.6975408 5 F2 0.9747552 6 F2 1.7326152 7 F2 1.8008943 8 F2 2.1311226 9 F3 2.1457999 10 F3 2.3620647 11 F3 2.6739812 12 F3 4.0720358 13 F4 1.4589714 14 F4 0.9295078 15 F4 1.6275433 16 F4 1.5148586 17 F5 2.2747842 18 F5 1.5204874 19 F5 2.7981053 20 F5 0.9955488 ANOVA_Model<-aov(Dependent~Factor,ANOVA_data) summary(ANOVA_Model) Df Sum Sq Mean Sq F value Pr(F) Factor 4 6.647 1.6617 3.04 0.0508 . Residuals 15 8.200 0.5467 --- Signif. codes: 0 β€˜***’ 0.001 β€˜**’ 0.01 β€˜*’ 0.05 β€˜.’ 0.1 β€˜ ’ 1 summary(ANOVA_Model)[[1]][1,4:5] F value Pr(F) Factor 3.0395 0.05078 . --- Signif. codes: 0 β€˜***’ 0.001 β€˜**’ 0.01 β€˜*’ 0.05 β€˜.’ 0.1 β€˜ ’ 1 summary(ANOVA_Model)[[1]][1,5] [1] 0.05077798 summary(ANOVA_Model)[[1]][1,4] [1] 3.039549
[ { "code": null, "e": 1580, "s": 1062, "text": "The analysis of variance technique helps us to identify whether there exists a significant mean difference in more than two variables or not. To detect this difference, we either use F-statistic value or p-value. If the F-statistic value is greater than the critical value of F or if p-value is less than the level of significance then we say that at least one of the means is significantly different from the rest. To extract the p-value and F-statistic value, we can make use of summary function of the ANOVA model." }, { "code": null, "e": 1591, "s": 1580, "text": " Live Demo" }, { "code": null, "e": 1706, "s": 1591, "text": "set.seed(123)\nGroup<-rep(c(\"G1\",\"G2\",\"G3\",\"G4\"),times=5)\nResponse<-runif(20,2,5)\ndf<-data.frame(Group,Response)\ndf" }, { "code": null, "e": 2210, "s": 1706, "text": "Group Response\n1 G1 2.862733\n2 G2 4.364915\n3 G3 3.226931\n4 G4 4.649052\n5 G1 4.821402\n6 G2 2.136669\n7 G3 3.584316\n8 G4 4.677257\n9 G1 3.654305\n10 G2 3.369844\n11 G3 4.870500\n12 G4 3.360002\n13 G1 4.032712\n14 G2 3.717900\n15 G3 2.308774\n16 G4 4.699475\n17 G1 2.738263\n18 G2 2.126179\n19 G3 2.983762\n20 G4 4.863511\nANOVA<-aov(Response~Group,df)\nsummary(ANOVA)\nDf Sum Sq Mean Sq F value Pr(F)\nGroup 3 4.813 1.6043 2.141 0.135\nResiduals 16 11.990 0.7494\nsummary(ANOVA)[[1]][1,4:5]\nF value Pr(F)\nGroup 2.1408 0.1351" }, { "code": null, "e": 2282, "s": 2210, "text": "If we want to extract only p-value then it can be done as shown below βˆ’" }, { "code": null, "e": 2321, "s": 2282, "text": "summary(ANOVA)[[1]][1,5]\n[1] 0.1351315" }, { "code": null, "e": 2393, "s": 2321, "text": "If we want to extract only F-value then it can be done as shown below βˆ’" }, { "code": null, "e": 2431, "s": 2393, "text": "summary(ANOVA)[[1]][1,4]\n[1] 2.140825" }, { "code": null, "e": 2471, "s": 2431, "text": "Let’s have a look at one more example βˆ’" }, { "code": null, "e": 2482, "s": 2471, "text": " Live Demo" }, { "code": null, "e": 2605, "s": 2482, "text": "Factor<-rep(c(\"F1\",\"F2\",\"F3\",\"F4\",\"F5\"),each=4)\nDependent<-rnorm(20,2)\nANOVA_data<-data.frame(Factor,Dependent)\nANOVA_data" }, { "code": null, "e": 3387, "s": 2605, "text": "Factor Dependent\n1 F1 2.2236414\n2 F1 4.0072015\n3 F1 3.0119791\n4 F1 1.6975408\n5 F2 0.9747552\n6 F2 1.7326152\n7 F2 1.8008943\n8 F2 2.1311226\n9 F3 2.1457999\n10 F3 2.3620647\n11 F3 2.6739812\n12 F3 4.0720358\n13 F4 1.4589714\n14 F4 0.9295078\n15 F4 1.6275433\n16 F4 1.5148586\n17 F5 2.2747842\n18 F5 1.5204874\n19 F5 2.7981053\n20 F5 0.9955488\nANOVA_Model<-aov(Dependent~Factor,ANOVA_data)\nsummary(ANOVA_Model)\nDf Sum Sq Mean Sq F value Pr(F)\nFactor 4 6.647 1.6617 3.04 0.0508 .\nResiduals 15 8.200 0.5467\n---\nSignif. codes: 0 β€˜***’ 0.001 β€˜**’ 0.01 β€˜*’ 0.05 β€˜.’ 0.1 β€˜ ’ 1\nsummary(ANOVA_Model)[[1]][1,4:5]\nF value Pr(F)\nFactor 3.0395 0.05078 .\n---\nSignif. codes: 0 β€˜***’ 0.001 β€˜**’ 0.01 β€˜*’ 0.05 β€˜.’ 0.1 β€˜ ’ 1\nsummary(ANOVA_Model)[[1]][1,5]\n[1] 0.05077798\nsummary(ANOVA_Model)[[1]][1,4]\n[1] 3.039549" } ]
Indexing and Selecting Data with Pandas - GeeksforGeeks
13 Apr, 2022 Indexing in Pandas :Indexing in pandas means simply selecting particular rows and columns of data from a DataFrame. Indexing could mean selecting all the rows and some of the columns, some of the rows and all of the columns, or some of each of the rows and columns. Indexing can also be known as Subset Selection. Let’s see some example of indexing in Pandas. In this article, we are using β€œnba.csv” file to download the CSV, click here. Let’s take a DataFrame with some fake data, now we perform indexing on this DataFrame. In this, we are selecting some rows and some columns from a DataFrame. Dataframe with dataset.Suppose we want to select columns Age, College and Salary for only rows with a labels Amir Johnson and Terry RozierOur final DataFrame would look like this: Let’s say we want to select row Amir Jhonson, Terry Rozier and John Holland with all columns in a dataframe.Our final DataFrame would look like this: Let’s say we want to select columns Age, Height and Salary with all rows in a dataframe.Our final DataFrame would look like this: There are a lot of ways to pull the elements, rows, and columns from a DataFrame. There are some indexing method in Pandas which help in getting an element from a DataFrame. These indexing methods appear very similar but behave very differently. Pandas support four types of Multi-axes indexing they are: Dataframe.[ ] ; This function also known as indexing operator Dataframe.loc[ ] : This function is used for labels. Dataframe.iloc[ ] : This function is used for positions or integer based Dataframe.ix[] : This function is used for both label and integer based Collectively, they are called the indexers. These are by far the most common ways to index data. These are four function which help in getting the elements, rows, and columns from a DataFrame. Indexing a Dataframe using indexing operator [] :Indexing operator is used to refer to the square brackets following an object. The .loc and .iloc indexers also use the indexing operator to make selections. In this indexing operator to refer to df[]. In order to select a single column, we simply put the name of the column in-between the brackets # importing pandas packageimport pandas as pd # making data frame from csv filedata = pd.read_csv("nba.csv", index_col ="Name") # retrieving columns by indexing operatorfirst = data["Age"] print(first) Output: In order to select multiple columns, we have to pass a list of columns in an indexing operator. # importing pandas packageimport pandas as pd # making data frame from csv filedata = pd.read_csv("nba.csv", index_col ="Name") # retrieving multiple columns by indexing operatorfirst = data[["Age", "College", "Salary"]] first Output: Indexing a DataFrame using .loc[ ] :This function selects data by the label of the rows and columns. The df.loc indexer selects data in a different way than just the indexing operator. It can select subsets of rows or columns. It can also simultaneously select subsets of rows and columns. In order to select a single row using .loc[], we put a single row label in a .loc function. # importing pandas packageimport pandas as pd # making data frame from csv filedata = pd.read_csv("nba.csv", index_col ="Name") # retrieving row by loc methodfirst = data.loc["Avery Bradley"]second = data.loc["R.J. Hunter"] print(first, "\n\n\n", second) Output:As shown in the output image, two series were returned since there was only one parameter both of the times. In order to select multiple rows, we put all the row labels in a list and pass that to .loc function. import pandas as pd # making data frame from csv filedata = pd.read_csv("nba.csv", index_col ="Name") # retrieving multiple rows by loc methodfirst = data.loc[["Avery Bradley", "R.J. Hunter"]] print(first) Output: In order to select two rows and three columns, we select a two rows which we want to select and three columns and put it in a separate list like this: Dataframe.loc[["row1", "row2"], ["column1", "column2", "column3"]] import pandas as pd # making data frame from csv filedata = pd.read_csv("nba.csv", index_col ="Name") # retrieving two rows and three columns by loc methodfirst = data.loc[["Avery Bradley", "R.J. Hunter"], ["Team", "Number", "Position"]] print(first) Output: In order to select all of the rows and some columns, we use single colon [:] to select all of rows and list of some columns which we want to select like this: Dataframe.loc[:, ["column1", "column2", "column3"]] import pandas as pd # making data frame from csv filedata = pd.read_csv("nba.csv", index_col ="Name") # retrieving all rows and some columns by loc methodfirst = data.loc[:, ["Team", "Number", "Position"]] print(first) Output: Indexing a DataFrame using .iloc[ ] :This function allows us to retrieve rows and columns by position. In order to do that, we’ll need to specify the positions of the rows that we want, and the positions of the columns that we want as well. The df.iloc indexer is very similar to df.loc but only uses integer locations to make its selections. In order to select a single row using .iloc[], we can pass a single integer to .iloc[] function. import pandas as pd # making data frame from csv filedata = pd.read_csv("nba.csv", index_col ="Name") # retrieving rows by iloc method row2 = data.iloc[3] print(row2) Output: In order to select multiple rows, we can pass a list of integer to .iloc[] function. import pandas as pd # making data frame from csv filedata = pd.read_csv("nba.csv", index_col ="Name") # retrieving multiple rows by iloc method row2 = data.iloc [[3, 5, 7]] row2 Output: In order to select two rows and two columns, we create a list of 2 integer for rows and list of 2 integer for columns then pass to a .iloc[] function. import pandas as pd # making data frame from csv filedata = pd.read_csv("nba.csv", index_col ="Name") # retrieving two rows and two columns by iloc method row2 = data.iloc [[3, 4], [1, 2]] print(row2) Output: In order to select all rows and some columns, we use single colon [:] to select all of rows and for columns we make a list of integer then pass to a .iloc[] function. import pandas as pd # making data frame from csv filedata = pd.read_csv("nba.csv", index_col ="Name") # retrieving all rows and some columns by iloc method row2 = data.iloc [:, [1, 2]] print(row2) Output: Indexing a using Dataframe.ix[ ] :Early in the development of pandas, there existed another indexer, ix. This indexer was capable of selecting both by label and by integer location. While it was versatile, it caused lots of confusion because it’s not explicit. Sometimes integers can also be labels for rows or columns. Thus there were instances where it was ambiguous. Generally, ix is label based and acts just as the .loc indexer. However, .ix also supports integer type selections (as in .iloc) where passed an integer. This only works where the index of the DataFrame is not integer based .ix will accept any of the inputs of .loc and .iloc.Note: The .ix indexer has been deprecated in recent versions of Pandas. In order to select a single row, we put a single row label in a .ix function. This function act similar as .loc[] if we pass a row label as a argument of a function. # importing pandas packageimport pandas as pd # making data frame from csv filedata = pd.read_csv("nba.csv", index_col ="Name") # retrieving row by ix methodfirst = data.ix["Avery Bradley"] print(first) Output: In order to select a single row, we can pass a single integer to .ix[] function. This function similar as a iloc[] function if we pass an integer in a .ix[] function. # importing pandas packageimport pandas as pd # making data frame from csv filedata = pd.read_csv("nba.csv", index_col ="Name") # retrieving row by ix methodfirst = data.ix[1] print(first) Output: shubhamvats1 Python pandas-dataFrame Python pandas-indexing Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace()
[ { "code": null, "e": 42935, "s": 42907, "text": "\n13 Apr, 2022" }, { "code": null, "e": 43249, "s": 42935, "text": "Indexing in Pandas :Indexing in pandas means simply selecting particular rows and columns of data from a DataFrame. Indexing could mean selecting all the rows and some of the columns, some of the rows and all of the columns, or some of each of the rows and columns. Indexing can also be known as Subset Selection." }, { "code": null, "e": 43373, "s": 43249, "text": "Let’s see some example of indexing in Pandas. In this article, we are using β€œnba.csv” file to download the CSV, click here." }, { "code": null, "e": 43711, "s": 43373, "text": "Let’s take a DataFrame with some fake data, now we perform indexing on this DataFrame. In this, we are selecting some rows and some columns from a DataFrame. Dataframe with dataset.Suppose we want to select columns Age, College and Salary for only rows with a labels Amir Johnson and Terry RozierOur final DataFrame would look like this:" }, { "code": null, "e": 43861, "s": 43711, "text": "Let’s say we want to select row Amir Jhonson, Terry Rozier and John Holland with all columns in a dataframe.Our final DataFrame would look like this:" }, { "code": null, "e": 43992, "s": 43861, "text": "Let’s say we want to select columns Age, Height and Salary with all rows in a dataframe.Our final DataFrame would look like this: " }, { "code": null, "e": 44297, "s": 43992, "text": "There are a lot of ways to pull the elements, rows, and columns from a DataFrame. There are some indexing method in Pandas which help in getting an element from a DataFrame. These indexing methods appear very similar but behave very differently. Pandas support four types of Multi-axes indexing they are:" }, { "code": null, "e": 44359, "s": 44297, "text": "Dataframe.[ ] ; This function also known as indexing operator" }, { "code": null, "e": 44412, "s": 44359, "text": "Dataframe.loc[ ] : This function is used for labels." }, { "code": null, "e": 44485, "s": 44412, "text": "Dataframe.iloc[ ] : This function is used for positions or integer based" }, { "code": null, "e": 44557, "s": 44485, "text": "Dataframe.ix[] : This function is used for both label and integer based" }, { "code": null, "e": 45001, "s": 44557, "text": "Collectively, they are called the indexers. These are by far the most common ways to index data. These are four function which help in getting the elements, rows, and columns from a DataFrame. Indexing a Dataframe using indexing operator [] :Indexing operator is used to refer to the square brackets following an object. The .loc and .iloc indexers also use the indexing operator to make selections. In this indexing operator to refer to df[]." }, { "code": null, "e": 45098, "s": 45001, "text": "In order to select a single column, we simply put the name of the column in-between the brackets" }, { "code": "# importing pandas packageimport pandas as pd # making data frame from csv filedata = pd.read_csv(\"nba.csv\", index_col =\"Name\") # retrieving columns by indexing operatorfirst = data[\"Age\"] print(first)", "e": 45307, "s": 45098, "text": null }, { "code": null, "e": 45315, "s": 45307, "text": "Output:" }, { "code": null, "e": 45411, "s": 45315, "text": "In order to select multiple columns, we have to pass a list of columns in an indexing operator." }, { "code": "# importing pandas packageimport pandas as pd # making data frame from csv filedata = pd.read_csv(\"nba.csv\", index_col =\"Name\") # retrieving multiple columns by indexing operatorfirst = data[[\"Age\", \"College\", \"Salary\"]] first", "e": 45645, "s": 45411, "text": null }, { "code": null, "e": 45943, "s": 45645, "text": "Output: Indexing a DataFrame using .loc[ ] :This function selects data by the label of the rows and columns. The df.loc indexer selects data in a different way than just the indexing operator. It can select subsets of rows or columns. It can also simultaneously select subsets of rows and columns." }, { "code": null, "e": 46035, "s": 45943, "text": "In order to select a single row using .loc[], we put a single row label in a .loc function." }, { "code": "# importing pandas packageimport pandas as pd # making data frame from csv filedata = pd.read_csv(\"nba.csv\", index_col =\"Name\") # retrieving row by loc methodfirst = data.loc[\"Avery Bradley\"]second = data.loc[\"R.J. Hunter\"] print(first, \"\\n\\n\\n\", second)", "e": 46295, "s": 46035, "text": null }, { "code": null, "e": 46412, "s": 46295, "text": "Output:As shown in the output image, two series were returned since there was only one parameter both of the times. " }, { "code": null, "e": 46514, "s": 46412, "text": "In order to select multiple rows, we put all the row labels in a list and pass that to .loc function." }, { "code": "import pandas as pd # making data frame from csv filedata = pd.read_csv(\"nba.csv\", index_col =\"Name\") # retrieving multiple rows by loc methodfirst = data.loc[[\"Avery Bradley\", \"R.J. Hunter\"]] print(first)", "e": 46727, "s": 46514, "text": null }, { "code": null, "e": 46736, "s": 46727, "text": "Output: " }, { "code": null, "e": 46887, "s": 46736, "text": "In order to select two rows and three columns, we select a two rows which we want to select and three columns and put it in a separate list like this:" }, { "code": null, "e": 46955, "s": 46887, "text": "Dataframe.loc[[\"row1\", \"row2\"], [\"column1\", \"column2\", \"column3\"]]\n" }, { "code": "import pandas as pd # making data frame from csv filedata = pd.read_csv(\"nba.csv\", index_col =\"Name\") # retrieving two rows and three columns by loc methodfirst = data.loc[[\"Avery Bradley\", \"R.J. Hunter\"], [\"Team\", \"Number\", \"Position\"]] print(first)", "e": 47231, "s": 46955, "text": null }, { "code": null, "e": 47240, "s": 47231, "text": "Output: " }, { "code": null, "e": 47399, "s": 47240, "text": "In order to select all of the rows and some columns, we use single colon [:] to select all of rows and list of some columns which we want to select like this:" }, { "code": null, "e": 47452, "s": 47399, "text": "Dataframe.loc[:, [\"column1\", \"column2\", \"column3\"]]\n" }, { "code": "import pandas as pd # making data frame from csv filedata = pd.read_csv(\"nba.csv\", index_col =\"Name\") # retrieving all rows and some columns by loc methodfirst = data.loc[:, [\"Team\", \"Number\", \"Position\"]] print(first)", "e": 47678, "s": 47452, "text": null }, { "code": null, "e": 48029, "s": 47678, "text": "Output: Indexing a DataFrame using .iloc[ ] :This function allows us to retrieve rows and columns by position. In order to do that, we’ll need to specify the positions of the rows that we want, and the positions of the columns that we want as well. The df.iloc indexer is very similar to df.loc but only uses integer locations to make its selections." }, { "code": null, "e": 48126, "s": 48029, "text": "In order to select a single row using .iloc[], we can pass a single integer to .iloc[] function." }, { "code": "import pandas as pd # making data frame from csv filedata = pd.read_csv(\"nba.csv\", index_col =\"Name\") # retrieving rows by iloc method row2 = data.iloc[3] print(row2)", "e": 48303, "s": 48126, "text": null }, { "code": null, "e": 48312, "s": 48303, "text": "Output: " }, { "code": null, "e": 48397, "s": 48312, "text": "In order to select multiple rows, we can pass a list of integer to .iloc[] function." }, { "code": "import pandas as pd # making data frame from csv filedata = pd.read_csv(\"nba.csv\", index_col =\"Name\") # retrieving multiple rows by iloc method row2 = data.iloc [[3, 5, 7]] row2", "e": 48584, "s": 48397, "text": null }, { "code": null, "e": 48593, "s": 48584, "text": "Output: " }, { "code": null, "e": 48744, "s": 48593, "text": "In order to select two rows and two columns, we create a list of 2 integer for rows and list of 2 integer for columns then pass to a .iloc[] function." }, { "code": "import pandas as pd # making data frame from csv filedata = pd.read_csv(\"nba.csv\", index_col =\"Name\") # retrieving two rows and two columns by iloc method row2 = data.iloc [[3, 4], [1, 2]] print(row2)", "e": 48954, "s": 48744, "text": null }, { "code": null, "e": 48963, "s": 48954, "text": "Output: " }, { "code": null, "e": 49130, "s": 48963, "text": "In order to select all rows and some columns, we use single colon [:] to select all of rows and for columns we make a list of integer then pass to a .iloc[] function." }, { "code": "import pandas as pd # making data frame from csv filedata = pd.read_csv(\"nba.csv\", index_col =\"Name\") # retrieving all rows and some columns by iloc method row2 = data.iloc [:, [1, 2]] print(row2)", "e": 49336, "s": 49130, "text": null }, { "code": null, "e": 50062, "s": 49336, "text": "Output: Indexing a using Dataframe.ix[ ] :Early in the development of pandas, there existed another indexer, ix. This indexer was capable of selecting both by label and by integer location. While it was versatile, it caused lots of confusion because it’s not explicit. Sometimes integers can also be labels for rows or columns. Thus there were instances where it was ambiguous. Generally, ix is label based and acts just as the .loc indexer. However, .ix also supports integer type selections (as in .iloc) where passed an integer. This only works where the index of the DataFrame is not integer based .ix will accept any of the inputs of .loc and .iloc.Note: The .ix indexer has been deprecated in recent versions of Pandas." }, { "code": null, "e": 50228, "s": 50062, "text": "In order to select a single row, we put a single row label in a .ix function. This function act similar as .loc[] if we pass a row label as a argument of a function." }, { "code": "# importing pandas packageimport pandas as pd # making data frame from csv filedata = pd.read_csv(\"nba.csv\", index_col =\"Name\") # retrieving row by ix methodfirst = data.ix[\"Avery Bradley\"] print(first) ", "e": 50444, "s": 50228, "text": null }, { "code": null, "e": 50452, "s": 50444, "text": "Output:" }, { "code": null, "e": 50619, "s": 50452, "text": "In order to select a single row, we can pass a single integer to .ix[] function. This function similar as a iloc[] function if we pass an integer in a .ix[] function." }, { "code": "# importing pandas packageimport pandas as pd # making data frame from csv filedata = pd.read_csv(\"nba.csv\", index_col =\"Name\") # retrieving row by ix methodfirst = data.ix[1] print(first)", "e": 50819, "s": 50619, "text": null }, { "code": null, "e": 50828, "s": 50819, "text": "Output: " }, { "code": null, "e": 50841, "s": 50828, "text": "shubhamvats1" }, { "code": null, "e": 50865, "s": 50841, "text": "Python pandas-dataFrame" }, { "code": null, "e": 50888, "s": 50865, "text": "Python pandas-indexing" }, { "code": null, "e": 50902, "s": 50888, "text": "Python-pandas" }, { "code": null, "e": 50909, "s": 50902, "text": "Python" }, { "code": null, "e": 51007, "s": 50909, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 51035, "s": 51007, "text": "Read JSON file using Python" }, { "code": null, "e": 51085, "s": 51035, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 51107, "s": 51085, "text": "Python map() function" }, { "code": null, "e": 51151, "s": 51107, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 51186, "s": 51151, "text": "Read a file line by line in Python" }, { "code": null, "e": 51218, "s": 51186, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 51240, "s": 51218, "text": "Enumerate() in Python" }, { "code": null, "e": 51282, "s": 51240, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 51312, "s": 51282, "text": "Iterate over a list in Python" } ]
How can Tensorflow be used to evaluate a CNN model using Python?
A convolutional neural network can be evaluated using the β€˜evaluate’ method. This method takes the test data as its parameters. Before this, the data is plotted on the console using β€˜matplotlib’ library and β€˜imshow’ methods. Read More: What is TensorFlow and how Keras work with TensorFlow to create Neural Networks? Convolutional neural networks have been used to produce great results for a specific kind of problems, such as image recognition. We are using the Google Colaboratory to run the below code. Google Colab or Colaboratory helps run Python code over the browser and requires zero configuration and free access to GPUs (Graphical Processing Units). Colaboratory has been built on top of Jupyter Notebook. print("Plotting accuracy versus epoch") plt.plot(history.history['accuracy'], label='accuracy') plt.plot(history.history['val_accuracy'], label = 'val_accuracy') plt.xlabel('Epoch') plt.ylabel('Accuracy') plt.ylim([0.5, 1]) plt.legend(loc='lower right') print("The model is being evaluated") test_loss, test_acc = model.evaluate(test_images,test_labels, verbose=2) print("The accuracy of the model is:") print(test_acc) Code credit: https://www.tensorflow.org/tutorials/images/cnn Plotting accuracy versus epoch The model is being evaluated 313/313 - 3s - loss: 0.8884 - accuracy: 0.7053 The accuracy of the model is: 0.705299973487854 The accuracy versus epoch data is visualized. This is done using matplotlib library. The model is evaluated, and the loss and accuracy are determined.
[ { "code": null, "e": 1287, "s": 1062, "text": "A convolutional neural network can be evaluated using the β€˜evaluate’ method. This method takes the test data as its parameters. Before this, the data is plotted on the console using β€˜matplotlib’ library and β€˜imshow’ methods." }, { "code": null, "e": 1379, "s": 1287, "text": "Read More:\nWhat is TensorFlow and how Keras work with TensorFlow to create Neural Networks?" }, { "code": null, "e": 1511, "s": 1379, "text": "Convolutional neural networks have been used to produce great results for a specific kind of problems, such as image recognition. " }, { "code": null, "e": 1781, "s": 1511, "text": "We are using the Google Colaboratory to run the below code. Google Colab or Colaboratory helps run Python code over the browser and requires zero configuration and free access to GPUs (Graphical Processing Units). Colaboratory has been built on top of Jupyter Notebook." }, { "code": null, "e": 2201, "s": 1781, "text": "print(\"Plotting accuracy versus epoch\")\nplt.plot(history.history['accuracy'], label='accuracy')\nplt.plot(history.history['val_accuracy'], label = 'val_accuracy')\nplt.xlabel('Epoch')\nplt.ylabel('Accuracy')\nplt.ylim([0.5, 1])\nplt.legend(loc='lower right')\nprint(\"The model is being evaluated\")\ntest_loss, test_acc = model.evaluate(test_images,test_labels, verbose=2)\nprint(\"The accuracy of the model is:\")\nprint(test_acc)" }, { "code": null, "e": 2262, "s": 2201, "text": "Code credit: https://www.tensorflow.org/tutorials/images/cnn" }, { "code": null, "e": 2417, "s": 2262, "text": "Plotting accuracy versus epoch\nThe model is being evaluated\n313/313 - 3s - loss: 0.8884 - accuracy: 0.7053\nThe accuracy of the model is:\n0.705299973487854" }, { "code": null, "e": 2463, "s": 2417, "text": "The accuracy versus epoch data is visualized." }, { "code": null, "e": 2502, "s": 2463, "text": "This is done using matplotlib library." }, { "code": null, "e": 2568, "s": 2502, "text": "The model is evaluated, and the loss and accuracy are determined." } ]
Adding Lottie animation in React JS
Lottie is an open source animation file format that’s tiny, high quality, interactive, and can be manipulated at runtime. Let us learn how to implement Lottie animation in React.js. Lottie animations are mainly used for loader screen or as a start screen. It is written and implemented in JSON format in our React projects. Go to the official Lottie animation website and download Lottie JSON. Link to animation the I am going to use βˆ’ https://lottiefiles.com/74546-character-02#/ Name the JSON file "myloader.json" and keep it at the same level as App.js. Now install the react-lottie package βˆ’ npm i --save react-lottie Lottie library will be used to add lottie-animation’s JSON file to your React site. Add the following lines of code in App.js βˆ’ import Lottie from "react-lottie"; // importing lottie animation JSON // note that you can use any variable in place of "animation" import animation from './myloader.json' function App() { const defaultOptions = { loop: true, autoplay: true, // here is where we will declare lottie animation // "animation" is what we imported before animationData: animation, rendererSettings: { preserveAspectRatio: "xMidYMid slice", }, }; return ( <div> <Lottie options={defaultOptions} height={300} width={300} /> </div> ); } export default App; Here in defaultOptions, we simply added some animation properties and linked to our Lottie animation JSON. Then we rendered a lottieView with our default options and link to animation. It will produce the following output βˆ’ Your browser does not support HTML5 video.
[ { "code": null, "e": 1386, "s": 1062, "text": "Lottie is an open source animation file format that’s tiny, high quality,\ninteractive, and can be manipulated at runtime. Let us learn how to\nimplement Lottie animation in React.js. Lottie animations are mainly\nused for loader screen or as a start screen. It is written and\nimplemented in JSON format in our React projects." }, { "code": null, "e": 1456, "s": 1386, "text": "Go to the official Lottie animation website and download Lottie JSON." }, { "code": null, "e": 1498, "s": 1456, "text": "Link to animation the I am going to use βˆ’" }, { "code": null, "e": 1544, "s": 1498, "text": " https://lottiefiles.com/74546-character-02#/" }, { "code": null, "e": 1620, "s": 1544, "text": "Name the JSON file \"myloader.json\" and keep it at the same level as App.js." }, { "code": null, "e": 1659, "s": 1620, "text": "Now install the react-lottie package βˆ’" }, { "code": null, "e": 1685, "s": 1659, "text": "npm i --save react-lottie" }, { "code": null, "e": 1769, "s": 1685, "text": "Lottie library will be used to add lottie-animation’s JSON file to your\nReact site." }, { "code": null, "e": 1813, "s": 1769, "text": "Add the following lines of code in App.js βˆ’" }, { "code": null, "e": 2427, "s": 1813, "text": "import Lottie from \"react-lottie\";\n\n// importing lottie animation JSON\n// note that you can use any variable in place of \"animation\"\nimport animation from './myloader.json'\nfunction App() {\n const defaultOptions = {\n loop: true,\n autoplay: true,\n // here is where we will declare lottie animation\n // \"animation\" is what we imported before animationData: animation,\n rendererSettings: {\n preserveAspectRatio: \"xMidYMid slice\",\n },\n };\n\n return (\n <div>\n <Lottie options={defaultOptions} height={300} width={300} />\n </div>\n );\n}\n\nexport default App;" }, { "code": null, "e": 2612, "s": 2427, "text": "Here in defaultOptions, we simply added some animation properties and linked to our Lottie animation JSON. Then we rendered a lottieView with our default options and link to animation." }, { "code": null, "e": 2651, "s": 2612, "text": "It will produce the following output βˆ’" }, { "code": null, "e": 2694, "s": 2651, "text": "Your browser does not support HTML5 video." } ]
Automated Machine Learning Hyperparameter Tuning in Python | by Will Koehrsen | Towards Data Science
Tuning machine learning hyperparameters is a tedious yet crucial task, as the performance of an algorithm can be highly dependent on the choice of hyperparameters. Manual tuning takes time away from important steps of the machine learning pipeline like feature engineering and interpreting results. Grid and random search are hands-off, but require long run times because they waste time evaluating unpromising areas of the search space. Increasingly, hyperparameter tuning is done by automated methods that aim to find optimal hyperparameters in less time using an informed search with no manual effort necessary beyond the initial set-up. Bayesian optimization, a model-based method for finding the minimum of a function, has recently been applied to machine learning hyperparameter tuning, with results suggesting this approach can achieve better performance on the test set while requiring fewer iterations than random search. Moreover, there are now a number of Python libraries that make implementing Bayesian hyperparameter tuning simple for any machine learning model. In this article, we will walk through a complete example of Bayesian hyperparameter tuning of a gradient boosting machine using the Hyperopt library. In an earlier article I outlined the concepts behind this method, so here we will stick to the implementation. Like with most machine learning topics, it’s not necessary to understand all the details, but knowing the basic idea can help you use the technique more effectively! All the code for this article is available as a Jupyter Notebook on GitHub. Bayesian Optimization Methods Four Parts of Optimization Problem Objective Function Domain Space Optimization Algorithm Result History Optimization Results Visualizing Search Results Evolution of Search Continue Searching Conclusions As a brief primer, Bayesian optimization finds the value that minimizes an objective function by building a surrogate function (probability model) based on past evaluation results of the objective. The surrogate is cheaper to optimize than the objective, so the next input values to evaluate are selected by applying a criterion to the surrogate (often Expected Improvement). Bayesian methods differ from random or grid search in that they use past evaluation results to choose the next values to evaluate. The concept is: limit expensive evaluations of the objective function by choosing the next input values based on those that have done well in the past. In the case of hyperparameter optimization, the objective function is the validation error of a machine learning model using a set of hyperparameters. The aim is to find the hyperparameters that yield the lowest error on the validation set in the hope that these results generalize to the testing set. Evaluating the objective function is expensive because it requires training the machine learning model with a specific set of hyperparameters. Ideally, we want a method that can explore the search space while also limiting evaluations of poor hyperparameter choices. Bayesian hyperparameter tuning uses a continually updated probability model to β€œconcentrate” on promising hyperparameters by reasoning from past results. Python Options There are several Bayesian optimization libraries in Python which differ in the algorithm for the surrogate of the objective function. In this article, we will work with Hyperopt, which uses the Tree Parzen Estimator (TPE) Other Python libraries include Spearmint (Gaussian Process surrogate) and SMAC (Random Forest Regression). There is a lot of interesting work going on in this area, so if you aren’t happy with one library, check out the alternatives! The general structure of a problem (which we will walk through here) translates between the libraries with only minor differences in syntax. For a basic introduction to Hyperopt, see this article. There are four parts to a Bayesian Optimization problem: Objective Function: what we want to minimize, in this case the validation error of a machine learning model with respect to the hyperparametersDomain Space: hyperparameter values to search overOptimization algorithm: method for constructing the surrogate model and choosing the next hyperparameter values to evaluateResult history: stored outcomes from evaluations of the objective function consisting of the hyperparameters and validation loss Objective Function: what we want to minimize, in this case the validation error of a machine learning model with respect to the hyperparameters Domain Space: hyperparameter values to search over Optimization algorithm: method for constructing the surrogate model and choosing the next hyperparameter values to evaluate Result history: stored outcomes from evaluations of the objective function consisting of the hyperparameters and validation loss With those four pieces, we can optimize (find the minimum) of any function that returns a real value. This is a powerful abstraction that lets us solve many problems in addition to tuning machine learning hyperparameters. Dataset For this example, we will use the Caravan Insurance dataset where the objective is to predict whether a customer will purchase an insurance policy. This is a supervised classification problem with 5800 training observations and 4000 testing points. The metric we will use to assess performance is the Receiver Operating Characteristic Area Under the Curve (ROC AUC) because this is an imbalanced classification problem. (A higher ROC AUC is better with a score of 1 indicating a perfect model). The dataset is shown below: Because Hyperopt requires a value to minimize, we will return 1-ROC AUC from the objective function, thereby driving up the ROC AUC. Gradient Boosting Model Detailed knowledge of the gradient boosting machine (GBM) is not necessary for this article and here are the basics we need to understand: The GBM is an ensemble boosting method based on using weak learners (almost always decision trees) trained sequentially to form a strong model. There are many hyperparameters in a GBM controlling both the entire ensemble and individual decision trees. One of the most effective methods for choosing the number of trees (called estimators) is early stopping which we will use. LightGBM provides a fast and simple implementation of the GBM in Python. For more details on the GBM, here’s a high level article and a technical paper. With the necessary background out of the way, let’s go through writing the four parts of a Bayesian optimization problem for hyperparameter tuning. The objective function is what we are trying to minimize. It takes in a set of values β€” in this case hyperparameters for the GBM β€” and outputs a real value to minimize β€” the cross validation loss. Hyperopt treats the objective function as a black box because it only considers what goes in and what comes out. The algorithm does not need to know the internals of the objective function in order to find the input values that minimize the loss! At a very high level (in pseudocode), our objective function should be: def objective(hyperparameters): """Returns validation score from hyperparameters""" model = Classifier(hyperparameters) validation_loss = cross_validation(model, training_data) return validation_loss We need to be careful not to use the loss on the testing set because we can only use the testing set a single time, when we evaluate the final model. Instead, we evaluate the hyperparameters on a validation set. Moreover, rather than separating training data into a distinct validation set, we use KFold cross validation, which, in addition to preserving valuable training data, should give us a less biased estimate of error on the testing set. The basic structure of the objective function for hyperparameter tuning will be the same across models: the function takes in the hyperparameters and returns the cross-validation error using those hyperparameters. Although this example is specific to the GBM, the structure can be applied to other methods. The complete objective function for the Gradient Boosting Machine using 10 fold cross validation with early stopping is shown below. The main line is cv_results = lgb.cv(...) . To implement cross-validation with early stopping , we use the LightGBM function cv which takes in the hyperparameters, a training set, a number of folds to use for cross validation, and several other arguments. We set the number of estimators ( num_boost_round) to 10000, but this number won’t actually be reached because we are using early_stopping_rounds to stop the training when validation scores have not improved for 100 estimators. Early stopping is an effective method for choosing the number of estimators rather than setting this as another hyperparameter that needs to be tuned! Once the cross validation is complete, we get the best score (ROC AUC), and then, because we want a value to minimize, we take 1-best score. This value is then returned as the loss key in the return dictionary. This is objective function is actually a little more complicated than it needs to be because we return a dictionary of values. For the objective function in Hyperopt, we can either return a single value, the loss, or a dict that has at a minimum keys "loss" and "status" . Returning the hyperparameters will let us inspect the loss resulting from each set of hyperparameters. The domain space represents the range of values we want to evaluate for each hyperparameter. Each iteration of the search, the Bayesian optimization algorithm will choose one value for each hyperparameter from the domain space. When we do random or grid search, the domain space is a grid. In Bayesian optimization the idea is the same except this space has probability distributions for each hyperparameter rather than discrete values. Specifying the domain is the trickiest part of a Bayesian optimization problem. If we have experience with a machine learning method, we can use it to inform our choices of hyperparameter distributions by placing greater probability where we think the best values are. However, the optimal model settings will vary between datasets and with a high-dimensionality problem (many hyperparameters) it can be difficult to figure out the interaction between hyperparameters. In cases where we aren’t sure about the best values, we can use wide distributions and let the Bayesian algorithm do the reasoning for us. First, we should look at all the hyperparameters in a GBM: import lgb# Default gradient boosting machine classifiermodel = lgb.LGBMClassifier()modelLGBMClassifier(boosting_type='gbdt', n_estimators=100, class_weight=None, colsample_bytree=1.0, learning_rate=0.1, max_depth=-1, min_child_samples=20, min_child_weight=0.001, min_split_gain=0.0, n_jobs=-1, num_leaves=31, objective=None, random_state=None, reg_alpha=0.0, reg_lambda=0.0, silent=True, subsample=1.0, subsample_for_bin=200000, subsample_freq=1) I’m not sure there’s anyone in the world who knows how all of these interact together! Some of these we don’t have to tune (such as objective and random_state ) and we will use early stopping to find the best n_estimators. However, we still have 10 hyperparameters to optimize! When first tuning a model, I usually create a wide domain space centered around the default values and then refine it in subsequent searches. As an example, let’s define a simple domain in Hyperopt, a discrete uniform distribution for the number of leaves in each tree in the GBM: from hyperopt import hp# Discrete uniform distributionnum_leaves = {'num_leaves': hp.quniform('num_leaves', 30, 150, 1)} This is a discrete uniform distribution because the number of leaves must be an integer (discrete) and each value in the domain is equally likely (uniform). Another choice of distribution is the log uniform which distributes values evenly on a logarithmic scale. We will use a log uniform (from 0.005 to 0.2) for the learning rate because it varies across several orders of magnitude: # Learning rate log uniform distributionlearning_rate = {'learning_rate': hp.loguniform('learning_rate', np.log(0.005), np.log(0.2)} Because this is a log-uniform distribution, the values are drawn between exp(low) and exp(high). The plot on the left below shows the discrete uniform distribution and the plot on the right is the log uniform. These are kernel density estimate plots so the y-axis is density and not a count! Now, let’s define the entire domain: Here we use a number of different domain distribution types: choice : categorical variables quniform : discrete uniform (integers spaced evenly) uniform: continuous uniform (floats spaced evenly) loguniform: continuous log uniform (floats spaced evenly on a log scale) (There are other distributions as well listed in the documentation.) There is one important point to notice when we define the boosting type: Here we are using a conditional domain which means the value of one hyperparameter depends on the value of another. For the boosting type "goss", the gbm cannot use subsampling (selecting only a subsample fraction of the training observations to use on each iteration). Therefore, the subsample ratio is set to 1.0 (no subsampling) if the boosting type is "goss" but is 0.5–1.0 otherwise. This is implemented using a nested domain. Conditional nesting can be useful when we are using different machine learning models with completely separate parameters. A conditional lets us use different sets of hyperparameters depending on the value of a choice. Now that our domain is defined, we can draw one example from it to see what a typical sample looks like. When we sample, because subsample is initially nested, we need to assign it to a top-level key. This is done using the Python dictionary get method with a default value of 1.0. {'boosting_type': 'gbdt', 'class_weight': 'balanced', 'colsample_bytree': 0.8111305579351727, 'learning_rate': 0.16186471096789776, 'min_child_samples': 470.0, 'num_leaves': 88.0, 'reg_alpha': 0.6338327001528129, 'reg_lambda': 0.8554826167886239, 'subsample_for_bin': 280000.0, 'subsample': 0.6318665053932255} (This reassigning of nested keys is necessary because the gradient boosting machine cannot deal with nested hyperparameter dictionaries). Although this is the most conceptually difficult part of Bayesian Optimization, creating the optimization algorithm in Hyperopt is a single line. To use the Tree Parzen Estimator the code is: from hyperopt import tpe# Algorithmtpe_algorithm = tpe.suggest That’s all there is to it! Hyperopt only has the TPE option along with random search, although the GitHub page says other methods may be coming. During optimization, the TPE algorithm constructs the probability model from the past results and decides the next set of hyperparameters to evaluate in the objective function by maximizing the expected improvement. Keeping track of the results is not strictly necessary as Hyperopt will do this internally for the algorithm. However, if we want to find out what is going on behind the scenes, we can use a Trials object which will store basic training information and also the dictionary returned from the objective function (which includes the loss andparams ). Making a trials object is one line: from hyperopt import Trials# Trials object to track progressbayes_trials = Trials() Another option which will allow us to monitor the progress of a long training run is to write a line to a csv file with each search iteration. This also saves all the results to disk in case something catastrophic happens and we lose the trials object (speaking from experience). We can do this using the csv library. Before training we open a new csv file and write the headers: and then within the objective function we can add lines to write to the csv on every iteration (the complete objective function is in the notebook): Writing to a csv means we can check the progress by opening the file while training (although not in Excel because this will cause an error in Python. Use tail out_file.csv from bash to view the last rows of the file). Once we have the four parts in place, optimization is run with fmin : Each iteration, the algorithm chooses new hyperparameter values from the surrogate function which is constructed based on the previous results and evaluates these values in the objective function. This continues for MAX_EVALS evaluations of the objective function with the surrogate function continually updated with each new result. The best object that is returned from fmin contains the hyperparameters that yielded the lowest loss on the objective function: {'boosting_type': 'gbdt', 'class_weight': 'balanced', 'colsample_bytree': 0.7125187075392453, 'learning_rate': 0.022592570862044956, 'min_child_samples': 250, 'num_leaves': 49, 'reg_alpha': 0.2035211643104735, 'reg_lambda': 0.6455131715928091, 'subsample': 0.983566228071919, 'subsample_for_bin': 200000} Once we have these hyperparameters, we can use them to train a model on the full training data and then evaluate on the testing data (remember we can only use the test set once, when we evaluate the final model). For the number of estimators, we can use the number of estimators that returned the lowest loss in cross validation with early stopping. Final results are below: The best model scores 0.72506 AUC ROC on the test set.The best cross validation score was 0.77101 AUC ROC.This was achieved after 413 search iterations. As a reference, 500 iterations of random search returned a model that scored 0.7232 ROC AUC on the test set and 0.76850 in cross validation. A default model with no optimization scored 0.7143 ROC AUC on the test set. There are a few important notes to keep in mind when we look at the results: The optimal hyperparameters are those that do best in cross validation and not necessarily those that do best on the testing data. When we use cross validation, we hope that these results generalize to the testing data.Even using 10-fold cross-validation, the hyperparameter tuning overfits to the training data. The best score from cross-validation is significantly higher than that on the testing data.Random search may return better hyperparameters just by sheer luck (re-running the notebook can change the results). Bayesian optimization is not guaranteed to find better hyperparameters and can get stuck in a local minimum of the objective function. The optimal hyperparameters are those that do best in cross validation and not necessarily those that do best on the testing data. When we use cross validation, we hope that these results generalize to the testing data. Even using 10-fold cross-validation, the hyperparameter tuning overfits to the training data. The best score from cross-validation is significantly higher than that on the testing data. Random search may return better hyperparameters just by sheer luck (re-running the notebook can change the results). Bayesian optimization is not guaranteed to find better hyperparameters and can get stuck in a local minimum of the objective function. Bayesian optimization is effective, but it will not solve all our tuning problems. As the search progresses, the algorithm switches from exploration β€” trying new hyperparameter values β€” to exploitation β€” using hyperparameter values that resulted in the lowest objective function loss. If the algorithm finds a local minimum of the objective function, it might concentrate on hyperparameter values around the local minimum rather than trying different values located far away in the domain space. Random search does not suffer from this issue because it does not concentrate on any values! Another important point is that the benefits of hyperparameter optimization will differ with the dataset. This is a relatively small dataset (~ 6000 training observations) and there is a small payback to tuning the hyperparameters (getting more data would be a better use of time!). With all of those caveats in mind, in this case, with Bayesian optimization we can get: Better performance on the testing set Fewer iterations to tune the hyperparameters Bayesian methods can (although will not always) yield better tuning results than random search. In the next few sections, we will examine the evolution of the Bayesian hyperparameter search and compare to random search to understand how Bayesian Optimization works. Graphing the results is an intuitive way to understand what happens during the hyperparameter search. Moreover, it’s helpful to compare Bayesian Optimization to random search so we can see how the methods differ. To see how the plots are made and random search is implemented, see the notebook, but here we will go through the results. (As a note, the exact results will change across iterations, so if you run the notebook, don’t be surprised if you get different images. All of these plots are made with 500 iterations). First we can make a kernel density estimate plot of the learning_rate sampled in random search and Bayes Optimization. As a reference, we can also show the sampling distribution. The vertical dashed lines show the best values (according to cross validation) for the learning rate. We defined the learning rate as a log-normal between 0.005 and 0.2, and the Bayesian Optimization results look similar to the sampling distribution. This tells us that the distribution we defined looks to be appropriate for the task, although the optimal value is a little higher than where we placed the greatest probability. This could be used to inform the domain for further searches. Another hyperparameter is the boosting type, with the bar plots of each type evaluated during random search and Bayes optimization shown below. Since random search does not pay attention to past results, we would expect each boosting type to be used roughly the same number of times. According to the Bayesian algorithm, the gdbt boosting type is more promising than dart or goss. Again, this could help inform further searches, either Bayesian methods or grid search. If we wanted to do a more informed grid search, we could use these results to define a smaller grid concentrated around the most promising values of the hyperparameters. Since we have them, let’s look at all of the numeric hyperparameters from the reference distribution, random search, and Bayes Optimization. The vertical lines again indicate the best value of the hyperparameter for each search: In most cases (except for the subsample_for_bin ) the Bayesian optimization search tends to concentrate (place more probability) near the hyperparameter values that yield the lowest loss in cross validation. This shows the fundamental idea of hyperparameter tuning using Bayesian methods: spend more time evaluating promising hyperparameter values. There are also some interesting results here that might help us in the future when it comes time to define a domain space to search over. As just one example, it looks like reg_alpha and reg_lambda should complement one another: if one is high (close to 1.0), the other should be lower. There’s no guarantee this will hold across problems, but by studying the results, we can gain insights that might be applied to future machine learning problems! As the optimization progresses, we expect the Bayes method to focus on the more promising values of the hyperparameters: those that yield the lowest error in cross validation. We can plot the values of the hyperparameters versus the iteration to see if there are noticeable trends. The black star indicates the optimal value. The colsample_bytree and learning_rate decrease over time which could guide us in future searches. Finally, if Bayes Optimization is working, we would expect the average validation score to increase over time (conversely the loss decreases): The validation scores from Bayesian hyperparameter optimization increase over time, indicating the method is trying β€œbetter” hyperparameter values (it should be noted that these are only better according to the validation score). Random search does not show an improvement over the iterations. If we are not satisfied with the performance of our model, we can keep searching using Hyperopt from where we left off. We just need to pass in the same trials object and the algorithm will continue searching. As the algorithm progresses, it does more exploitation β€” picking values that have done well in the past β€” and less exploration β€” picking new values. Instead of continuing where the search left off, it might therefore be a good idea to start an entirely different search. If the best hyperparameters from the first search really are β€œoptimal”, we would expect subsequent searches to focus on the same values. Given the high dimensionality of the problem, and the complex interactions between hyperparameters, it’s unlikely that another search would result in a similar set of hyperparameters. After another 500 iterations of training, the final model scores 0.72736 ROC AUCon the test set. (We really should not have evaluated the first model on the test set and instead relied only on validation scores. The test set should ideally be used only once to get a measure of algorithm performance when deployed on new data). Again, this problem may have diminishing returns to further hyperparameter optimization because of the small size of the dataset and there will eventually be a plateau in validation error (there is an inherent limit to the performance of any model on a dataset because of hidden variables that are not measured and noisy data, referred to as Bayes’ Error). Automated hyperparameter tuning of machine learning models can be accomplished using Bayesian optimization. In contrast to random search, Bayesian optimization chooses the next hyperparameters in an informed method to spend more time evaluating promising values. The end outcome can be fewer evaluations of the objective function and better generalization performance on the test set compared to random or grid search. In this article, we walked step-by-step through Bayesian hyperparameter optimization in Python using Hyperopt. We were able to improve the test set performance of a Gradient Boosting Machine beyond both the baseline and random search although we need to be cautious of overfitting to the training data. Furthermore, we saw how random search differs from Bayesian Optimization by examining the resulting graphs which showed that the Bayesian method placed greater probability on the hyperparameter values that resulted in lower cross validation loss. Using the four parts of an optimization problem, we can use Hyperopt to solve a wide variety of problems. The basic parts of Bayesian optimization also apply to a number of libraries in Python that implement different algorithms. Making the switch from manual to random or grid search is one small step, but to take your machine learning to the next level requires some automated form of hyperparameter tuning. Bayesian Optimization is one approach that is both easy to use in Python and can return better results than random search. Hopefully you now feel confident to start using this powerful method for your own machine learning problems! As always, I welcome feedback and constructive criticism. I can be reached on Twitter @koehrsen_will.
[ { "code": null, "e": 812, "s": 171, "text": "Tuning machine learning hyperparameters is a tedious yet crucial task, as the performance of an algorithm can be highly dependent on the choice of hyperparameters. Manual tuning takes time away from important steps of the machine learning pipeline like feature engineering and interpreting results. Grid and random search are hands-off, but require long run times because they waste time evaluating unpromising areas of the search space. Increasingly, hyperparameter tuning is done by automated methods that aim to find optimal hyperparameters in less time using an informed search with no manual effort necessary beyond the initial set-up." }, { "code": null, "e": 1248, "s": 812, "text": "Bayesian optimization, a model-based method for finding the minimum of a function, has recently been applied to machine learning hyperparameter tuning, with results suggesting this approach can achieve better performance on the test set while requiring fewer iterations than random search. Moreover, there are now a number of Python libraries that make implementing Bayesian hyperparameter tuning simple for any machine learning model." }, { "code": null, "e": 1675, "s": 1248, "text": "In this article, we will walk through a complete example of Bayesian hyperparameter tuning of a gradient boosting machine using the Hyperopt library. In an earlier article I outlined the concepts behind this method, so here we will stick to the implementation. Like with most machine learning topics, it’s not necessary to understand all the details, but knowing the basic idea can help you use the technique more effectively!" }, { "code": null, "e": 1751, "s": 1675, "text": "All the code for this article is available as a Jupyter Notebook on GitHub." }, { "code": null, "e": 1781, "s": 1751, "text": "Bayesian Optimization Methods" }, { "code": null, "e": 1816, "s": 1781, "text": "Four Parts of Optimization Problem" }, { "code": null, "e": 1835, "s": 1816, "text": "Objective Function" }, { "code": null, "e": 1848, "s": 1835, "text": "Domain Space" }, { "code": null, "e": 1871, "s": 1848, "text": "Optimization Algorithm" }, { "code": null, "e": 1886, "s": 1871, "text": "Result History" }, { "code": null, "e": 1899, "s": 1886, "text": "Optimization" }, { "code": null, "e": 1907, "s": 1899, "text": "Results" }, { "code": null, "e": 1934, "s": 1907, "text": "Visualizing Search Results" }, { "code": null, "e": 1954, "s": 1934, "text": "Evolution of Search" }, { "code": null, "e": 1973, "s": 1954, "text": "Continue Searching" }, { "code": null, "e": 1985, "s": 1973, "text": "Conclusions" }, { "code": null, "e": 2644, "s": 1985, "text": "As a brief primer, Bayesian optimization finds the value that minimizes an objective function by building a surrogate function (probability model) based on past evaluation results of the objective. The surrogate is cheaper to optimize than the objective, so the next input values to evaluate are selected by applying a criterion to the surrogate (often Expected Improvement). Bayesian methods differ from random or grid search in that they use past evaluation results to choose the next values to evaluate. The concept is: limit expensive evaluations of the objective function by choosing the next input values based on those that have done well in the past." }, { "code": null, "e": 3367, "s": 2644, "text": "In the case of hyperparameter optimization, the objective function is the validation error of a machine learning model using a set of hyperparameters. The aim is to find the hyperparameters that yield the lowest error on the validation set in the hope that these results generalize to the testing set. Evaluating the objective function is expensive because it requires training the machine learning model with a specific set of hyperparameters. Ideally, we want a method that can explore the search space while also limiting evaluations of poor hyperparameter choices. Bayesian hyperparameter tuning uses a continually updated probability model to β€œconcentrate” on promising hyperparameters by reasoning from past results." }, { "code": null, "e": 3382, "s": 3367, "text": "Python Options" }, { "code": null, "e": 4036, "s": 3382, "text": "There are several Bayesian optimization libraries in Python which differ in the algorithm for the surrogate of the objective function. In this article, we will work with Hyperopt, which uses the Tree Parzen Estimator (TPE) Other Python libraries include Spearmint (Gaussian Process surrogate) and SMAC (Random Forest Regression). There is a lot of interesting work going on in this area, so if you aren’t happy with one library, check out the alternatives! The general structure of a problem (which we will walk through here) translates between the libraries with only minor differences in syntax. For a basic introduction to Hyperopt, see this article." }, { "code": null, "e": 4093, "s": 4036, "text": "There are four parts to a Bayesian Optimization problem:" }, { "code": null, "e": 4538, "s": 4093, "text": "Objective Function: what we want to minimize, in this case the validation error of a machine learning model with respect to the hyperparametersDomain Space: hyperparameter values to search overOptimization algorithm: method for constructing the surrogate model and choosing the next hyperparameter values to evaluateResult history: stored outcomes from evaluations of the objective function consisting of the hyperparameters and validation loss" }, { "code": null, "e": 4682, "s": 4538, "text": "Objective Function: what we want to minimize, in this case the validation error of a machine learning model with respect to the hyperparameters" }, { "code": null, "e": 4733, "s": 4682, "text": "Domain Space: hyperparameter values to search over" }, { "code": null, "e": 4857, "s": 4733, "text": "Optimization algorithm: method for constructing the surrogate model and choosing the next hyperparameter values to evaluate" }, { "code": null, "e": 4986, "s": 4857, "text": "Result history: stored outcomes from evaluations of the objective function consisting of the hyperparameters and validation loss" }, { "code": null, "e": 5208, "s": 4986, "text": "With those four pieces, we can optimize (find the minimum) of any function that returns a real value. This is a powerful abstraction that lets us solve many problems in addition to tuning machine learning hyperparameters." }, { "code": null, "e": 5216, "s": 5208, "text": "Dataset" }, { "code": null, "e": 5739, "s": 5216, "text": "For this example, we will use the Caravan Insurance dataset where the objective is to predict whether a customer will purchase an insurance policy. This is a supervised classification problem with 5800 training observations and 4000 testing points. The metric we will use to assess performance is the Receiver Operating Characteristic Area Under the Curve (ROC AUC) because this is an imbalanced classification problem. (A higher ROC AUC is better with a score of 1 indicating a perfect model). The dataset is shown below:" }, { "code": null, "e": 5872, "s": 5739, "text": "Because Hyperopt requires a value to minimize, we will return 1-ROC AUC from the objective function, thereby driving up the ROC AUC." }, { "code": null, "e": 5896, "s": 5872, "text": "Gradient Boosting Model" }, { "code": null, "e": 6484, "s": 5896, "text": "Detailed knowledge of the gradient boosting machine (GBM) is not necessary for this article and here are the basics we need to understand: The GBM is an ensemble boosting method based on using weak learners (almost always decision trees) trained sequentially to form a strong model. There are many hyperparameters in a GBM controlling both the entire ensemble and individual decision trees. One of the most effective methods for choosing the number of trees (called estimators) is early stopping which we will use. LightGBM provides a fast and simple implementation of the GBM in Python." }, { "code": null, "e": 6564, "s": 6484, "text": "For more details on the GBM, here’s a high level article and a technical paper." }, { "code": null, "e": 6712, "s": 6564, "text": "With the necessary background out of the way, let’s go through writing the four parts of a Bayesian optimization problem for hyperparameter tuning." }, { "code": null, "e": 7228, "s": 6712, "text": "The objective function is what we are trying to minimize. It takes in a set of values β€” in this case hyperparameters for the GBM β€” and outputs a real value to minimize β€” the cross validation loss. Hyperopt treats the objective function as a black box because it only considers what goes in and what comes out. The algorithm does not need to know the internals of the objective function in order to find the input values that minimize the loss! At a very high level (in pseudocode), our objective function should be:" }, { "code": null, "e": 7448, "s": 7228, "text": "def objective(hyperparameters): \"\"\"Returns validation score from hyperparameters\"\"\" model = Classifier(hyperparameters) validation_loss = cross_validation(model, training_data) return validation_loss" }, { "code": null, "e": 7894, "s": 7448, "text": "We need to be careful not to use the loss on the testing set because we can only use the testing set a single time, when we evaluate the final model. Instead, we evaluate the hyperparameters on a validation set. Moreover, rather than separating training data into a distinct validation set, we use KFold cross validation, which, in addition to preserving valuable training data, should give us a less biased estimate of error on the testing set." }, { "code": null, "e": 8201, "s": 7894, "text": "The basic structure of the objective function for hyperparameter tuning will be the same across models: the function takes in the hyperparameters and returns the cross-validation error using those hyperparameters. Although this example is specific to the GBM, the structure can be applied to other methods." }, { "code": null, "e": 8334, "s": 8201, "text": "The complete objective function for the Gradient Boosting Machine using 10 fold cross validation with early stopping is shown below." }, { "code": null, "e": 8969, "s": 8334, "text": "The main line is cv_results = lgb.cv(...) . To implement cross-validation with early stopping , we use the LightGBM function cv which takes in the hyperparameters, a training set, a number of folds to use for cross validation, and several other arguments. We set the number of estimators ( num_boost_round) to 10000, but this number won’t actually be reached because we are using early_stopping_rounds to stop the training when validation scores have not improved for 100 estimators. Early stopping is an effective method for choosing the number of estimators rather than setting this as another hyperparameter that needs to be tuned!" }, { "code": null, "e": 9180, "s": 8969, "text": "Once the cross validation is complete, we get the best score (ROC AUC), and then, because we want a value to minimize, we take 1-best score. This value is then returned as the loss key in the return dictionary." }, { "code": null, "e": 9556, "s": 9180, "text": "This is objective function is actually a little more complicated than it needs to be because we return a dictionary of values. For the objective function in Hyperopt, we can either return a single value, the loss, or a dict that has at a minimum keys \"loss\" and \"status\" . Returning the hyperparameters will let us inspect the loss resulting from each set of hyperparameters." }, { "code": null, "e": 9993, "s": 9556, "text": "The domain space represents the range of values we want to evaluate for each hyperparameter. Each iteration of the search, the Bayesian optimization algorithm will choose one value for each hyperparameter from the domain space. When we do random or grid search, the domain space is a grid. In Bayesian optimization the idea is the same except this space has probability distributions for each hyperparameter rather than discrete values." }, { "code": null, "e": 10601, "s": 9993, "text": "Specifying the domain is the trickiest part of a Bayesian optimization problem. If we have experience with a machine learning method, we can use it to inform our choices of hyperparameter distributions by placing greater probability where we think the best values are. However, the optimal model settings will vary between datasets and with a high-dimensionality problem (many hyperparameters) it can be difficult to figure out the interaction between hyperparameters. In cases where we aren’t sure about the best values, we can use wide distributions and let the Bayesian algorithm do the reasoning for us." }, { "code": null, "e": 10660, "s": 10601, "text": "First, we should look at all the hyperparameters in a GBM:" }, { "code": null, "e": 11246, "s": 10660, "text": "import lgb# Default gradient boosting machine classifiermodel = lgb.LGBMClassifier()modelLGBMClassifier(boosting_type='gbdt', n_estimators=100, class_weight=None, colsample_bytree=1.0, learning_rate=0.1, max_depth=-1, min_child_samples=20, min_child_weight=0.001, min_split_gain=0.0, n_jobs=-1, num_leaves=31, objective=None, random_state=None, reg_alpha=0.0, reg_lambda=0.0, silent=True, subsample=1.0, subsample_for_bin=200000, subsample_freq=1)" }, { "code": null, "e": 11666, "s": 11246, "text": "I’m not sure there’s anyone in the world who knows how all of these interact together! Some of these we don’t have to tune (such as objective and random_state ) and we will use early stopping to find the best n_estimators. However, we still have 10 hyperparameters to optimize! When first tuning a model, I usually create a wide domain space centered around the default values and then refine it in subsequent searches." }, { "code": null, "e": 11805, "s": 11666, "text": "As an example, let’s define a simple domain in Hyperopt, a discrete uniform distribution for the number of leaves in each tree in the GBM:" }, { "code": null, "e": 11926, "s": 11805, "text": "from hyperopt import hp# Discrete uniform distributionnum_leaves = {'num_leaves': hp.quniform('num_leaves', 30, 150, 1)}" }, { "code": null, "e": 12083, "s": 11926, "text": "This is a discrete uniform distribution because the number of leaves must be an integer (discrete) and each value in the domain is equally likely (uniform)." }, { "code": null, "e": 12311, "s": 12083, "text": "Another choice of distribution is the log uniform which distributes values evenly on a logarithmic scale. We will use a log uniform (from 0.005 to 0.2) for the learning rate because it varies across several orders of magnitude:" }, { "code": null, "e": 12540, "s": 12311, "text": "# Learning rate log uniform distributionlearning_rate = {'learning_rate': hp.loguniform('learning_rate', np.log(0.005), np.log(0.2)}" }, { "code": null, "e": 12832, "s": 12540, "text": "Because this is a log-uniform distribution, the values are drawn between exp(low) and exp(high). The plot on the left below shows the discrete uniform distribution and the plot on the right is the log uniform. These are kernel density estimate plots so the y-axis is density and not a count!" }, { "code": null, "e": 12869, "s": 12832, "text": "Now, let’s define the entire domain:" }, { "code": null, "e": 12930, "s": 12869, "text": "Here we use a number of different domain distribution types:" }, { "code": null, "e": 12961, "s": 12930, "text": "choice : categorical variables" }, { "code": null, "e": 13014, "s": 12961, "text": "quniform : discrete uniform (integers spaced evenly)" }, { "code": null, "e": 13065, "s": 13014, "text": "uniform: continuous uniform (floats spaced evenly)" }, { "code": null, "e": 13138, "s": 13065, "text": "loguniform: continuous log uniform (floats spaced evenly on a log scale)" }, { "code": null, "e": 13207, "s": 13138, "text": "(There are other distributions as well listed in the documentation.)" }, { "code": null, "e": 13280, "s": 13207, "text": "There is one important point to notice when we define the boosting type:" }, { "code": null, "e": 13712, "s": 13280, "text": "Here we are using a conditional domain which means the value of one hyperparameter depends on the value of another. For the boosting type \"goss\", the gbm cannot use subsampling (selecting only a subsample fraction of the training observations to use on each iteration). Therefore, the subsample ratio is set to 1.0 (no subsampling) if the boosting type is \"goss\" but is 0.5–1.0 otherwise. This is implemented using a nested domain." }, { "code": null, "e": 13931, "s": 13712, "text": "Conditional nesting can be useful when we are using different machine learning models with completely separate parameters. A conditional lets us use different sets of hyperparameters depending on the value of a choice." }, { "code": null, "e": 14213, "s": 13931, "text": "Now that our domain is defined, we can draw one example from it to see what a typical sample looks like. When we sample, because subsample is initially nested, we need to assign it to a top-level key. This is done using the Python dictionary get method with a default value of 1.0." }, { "code": null, "e": 14524, "s": 14213, "text": "{'boosting_type': 'gbdt', 'class_weight': 'balanced', 'colsample_bytree': 0.8111305579351727, 'learning_rate': 0.16186471096789776, 'min_child_samples': 470.0, 'num_leaves': 88.0, 'reg_alpha': 0.6338327001528129, 'reg_lambda': 0.8554826167886239, 'subsample_for_bin': 280000.0, 'subsample': 0.6318665053932255}" }, { "code": null, "e": 14662, "s": 14524, "text": "(This reassigning of nested keys is necessary because the gradient boosting machine cannot deal with nested hyperparameter dictionaries)." }, { "code": null, "e": 14854, "s": 14662, "text": "Although this is the most conceptually difficult part of Bayesian Optimization, creating the optimization algorithm in Hyperopt is a single line. To use the Tree Parzen Estimator the code is:" }, { "code": null, "e": 14917, "s": 14854, "text": "from hyperopt import tpe# Algorithmtpe_algorithm = tpe.suggest" }, { "code": null, "e": 15278, "s": 14917, "text": "That’s all there is to it! Hyperopt only has the TPE option along with random search, although the GitHub page says other methods may be coming. During optimization, the TPE algorithm constructs the probability model from the past results and decides the next set of hyperparameters to evaluate in the objective function by maximizing the expected improvement." }, { "code": null, "e": 15662, "s": 15278, "text": "Keeping track of the results is not strictly necessary as Hyperopt will do this internally for the algorithm. However, if we want to find out what is going on behind the scenes, we can use a Trials object which will store basic training information and also the dictionary returned from the objective function (which includes the loss andparams ). Making a trials object is one line:" }, { "code": null, "e": 15746, "s": 15662, "text": "from hyperopt import Trials# Trials object to track progressbayes_trials = Trials()" }, { "code": null, "e": 16126, "s": 15746, "text": "Another option which will allow us to monitor the progress of a long training run is to write a line to a csv file with each search iteration. This also saves all the results to disk in case something catastrophic happens and we lose the trials object (speaking from experience). We can do this using the csv library. Before training we open a new csv file and write the headers:" }, { "code": null, "e": 16275, "s": 16126, "text": "and then within the objective function we can add lines to write to the csv on every iteration (the complete objective function is in the notebook):" }, { "code": null, "e": 16494, "s": 16275, "text": "Writing to a csv means we can check the progress by opening the file while training (although not in Excel because this will cause an error in Python. Use tail out_file.csv from bash to view the last rows of the file)." }, { "code": null, "e": 16564, "s": 16494, "text": "Once we have the four parts in place, optimization is run with fmin :" }, { "code": null, "e": 16898, "s": 16564, "text": "Each iteration, the algorithm chooses new hyperparameter values from the surrogate function which is constructed based on the previous results and evaluates these values in the objective function. This continues for MAX_EVALS evaluations of the objective function with the surrogate function continually updated with each new result." }, { "code": null, "e": 17026, "s": 16898, "text": "The best object that is returned from fmin contains the hyperparameters that yielded the lowest loss on the objective function:" }, { "code": null, "e": 17349, "s": 17026, "text": "{'boosting_type': 'gbdt', 'class_weight': 'balanced', 'colsample_bytree': 0.7125187075392453, 'learning_rate': 0.022592570862044956, 'min_child_samples': 250, 'num_leaves': 49, 'reg_alpha': 0.2035211643104735, 'reg_lambda': 0.6455131715928091, 'subsample': 0.983566228071919, 'subsample_for_bin': 200000}" }, { "code": null, "e": 17724, "s": 17349, "text": "Once we have these hyperparameters, we can use them to train a model on the full training data and then evaluate on the testing data (remember we can only use the test set once, when we evaluate the final model). For the number of estimators, we can use the number of estimators that returned the lowest loss in cross validation with early stopping. Final results are below:" }, { "code": null, "e": 17877, "s": 17724, "text": "The best model scores 0.72506 AUC ROC on the test set.The best cross validation score was 0.77101 AUC ROC.This was achieved after 413 search iterations." }, { "code": null, "e": 18094, "s": 17877, "text": "As a reference, 500 iterations of random search returned a model that scored 0.7232 ROC AUC on the test set and 0.76850 in cross validation. A default model with no optimization scored 0.7143 ROC AUC on the test set." }, { "code": null, "e": 18171, "s": 18094, "text": "There are a few important notes to keep in mind when we look at the results:" }, { "code": null, "e": 18827, "s": 18171, "text": "The optimal hyperparameters are those that do best in cross validation and not necessarily those that do best on the testing data. When we use cross validation, we hope that these results generalize to the testing data.Even using 10-fold cross-validation, the hyperparameter tuning overfits to the training data. The best score from cross-validation is significantly higher than that on the testing data.Random search may return better hyperparameters just by sheer luck (re-running the notebook can change the results). Bayesian optimization is not guaranteed to find better hyperparameters and can get stuck in a local minimum of the objective function." }, { "code": null, "e": 19047, "s": 18827, "text": "The optimal hyperparameters are those that do best in cross validation and not necessarily those that do best on the testing data. When we use cross validation, we hope that these results generalize to the testing data." }, { "code": null, "e": 19233, "s": 19047, "text": "Even using 10-fold cross-validation, the hyperparameter tuning overfits to the training data. The best score from cross-validation is significantly higher than that on the testing data." }, { "code": null, "e": 19485, "s": 19233, "text": "Random search may return better hyperparameters just by sheer luck (re-running the notebook can change the results). Bayesian optimization is not guaranteed to find better hyperparameters and can get stuck in a local minimum of the objective function." }, { "code": null, "e": 20074, "s": 19485, "text": "Bayesian optimization is effective, but it will not solve all our tuning problems. As the search progresses, the algorithm switches from exploration β€” trying new hyperparameter values β€” to exploitation β€” using hyperparameter values that resulted in the lowest objective function loss. If the algorithm finds a local minimum of the objective function, it might concentrate on hyperparameter values around the local minimum rather than trying different values located far away in the domain space. Random search does not suffer from this issue because it does not concentrate on any values!" }, { "code": null, "e": 20445, "s": 20074, "text": "Another important point is that the benefits of hyperparameter optimization will differ with the dataset. This is a relatively small dataset (~ 6000 training observations) and there is a small payback to tuning the hyperparameters (getting more data would be a better use of time!). With all of those caveats in mind, in this case, with Bayesian optimization we can get:" }, { "code": null, "e": 20483, "s": 20445, "text": "Better performance on the testing set" }, { "code": null, "e": 20528, "s": 20483, "text": "Fewer iterations to tune the hyperparameters" }, { "code": null, "e": 20794, "s": 20528, "text": "Bayesian methods can (although will not always) yield better tuning results than random search. In the next few sections, we will examine the evolution of the Bayesian hyperparameter search and compare to random search to understand how Bayesian Optimization works." }, { "code": null, "e": 21317, "s": 20794, "text": "Graphing the results is an intuitive way to understand what happens during the hyperparameter search. Moreover, it’s helpful to compare Bayesian Optimization to random search so we can see how the methods differ. To see how the plots are made and random search is implemented, see the notebook, but here we will go through the results. (As a note, the exact results will change across iterations, so if you run the notebook, don’t be surprised if you get different images. All of these plots are made with 500 iterations)." }, { "code": null, "e": 21598, "s": 21317, "text": "First we can make a kernel density estimate plot of the learning_rate sampled in random search and Bayes Optimization. As a reference, we can also show the sampling distribution. The vertical dashed lines show the best values (according to cross validation) for the learning rate." }, { "code": null, "e": 21987, "s": 21598, "text": "We defined the learning rate as a log-normal between 0.005 and 0.2, and the Bayesian Optimization results look similar to the sampling distribution. This tells us that the distribution we defined looks to be appropriate for the task, although the optimal value is a little higher than where we placed the greatest probability. This could be used to inform the domain for further searches." }, { "code": null, "e": 22271, "s": 21987, "text": "Another hyperparameter is the boosting type, with the bar plots of each type evaluated during random search and Bayes optimization shown below. Since random search does not pay attention to past results, we would expect each boosting type to be used roughly the same number of times." }, { "code": null, "e": 22626, "s": 22271, "text": "According to the Bayesian algorithm, the gdbt boosting type is more promising than dart or goss. Again, this could help inform further searches, either Bayesian methods or grid search. If we wanted to do a more informed grid search, we could use these results to define a smaller grid concentrated around the most promising values of the hyperparameters." }, { "code": null, "e": 22855, "s": 22626, "text": "Since we have them, let’s look at all of the numeric hyperparameters from the reference distribution, random search, and Bayes Optimization. The vertical lines again indicate the best value of the hyperparameter for each search:" }, { "code": null, "e": 23204, "s": 22855, "text": "In most cases (except for the subsample_for_bin ) the Bayesian optimization search tends to concentrate (place more probability) near the hyperparameter values that yield the lowest loss in cross validation. This shows the fundamental idea of hyperparameter tuning using Bayesian methods: spend more time evaluating promising hyperparameter values." }, { "code": null, "e": 23653, "s": 23204, "text": "There are also some interesting results here that might help us in the future when it comes time to define a domain space to search over. As just one example, it looks like reg_alpha and reg_lambda should complement one another: if one is high (close to 1.0), the other should be lower. There’s no guarantee this will hold across problems, but by studying the results, we can gain insights that might be applied to future machine learning problems!" }, { "code": null, "e": 23935, "s": 23653, "text": "As the optimization progresses, we expect the Bayes method to focus on the more promising values of the hyperparameters: those that yield the lowest error in cross validation. We can plot the values of the hyperparameters versus the iteration to see if there are noticeable trends." }, { "code": null, "e": 24078, "s": 23935, "text": "The black star indicates the optimal value. The colsample_bytree and learning_rate decrease over time which could guide us in future searches." }, { "code": null, "e": 24221, "s": 24078, "text": "Finally, if Bayes Optimization is working, we would expect the average validation score to increase over time (conversely the loss decreases):" }, { "code": null, "e": 24515, "s": 24221, "text": "The validation scores from Bayesian hyperparameter optimization increase over time, indicating the method is trying β€œbetter” hyperparameter values (it should be noted that these are only better according to the validation score). Random search does not show an improvement over the iterations." }, { "code": null, "e": 24725, "s": 24515, "text": "If we are not satisfied with the performance of our model, we can keep searching using Hyperopt from where we left off. We just need to pass in the same trials object and the algorithm will continue searching." }, { "code": null, "e": 25317, "s": 24725, "text": "As the algorithm progresses, it does more exploitation β€” picking values that have done well in the past β€” and less exploration β€” picking new values. Instead of continuing where the search left off, it might therefore be a good idea to start an entirely different search. If the best hyperparameters from the first search really are β€œoptimal”, we would expect subsequent searches to focus on the same values. Given the high dimensionality of the problem, and the complex interactions between hyperparameters, it’s unlikely that another search would result in a similar set of hyperparameters." }, { "code": null, "e": 26002, "s": 25317, "text": "After another 500 iterations of training, the final model scores 0.72736 ROC AUCon the test set. (We really should not have evaluated the first model on the test set and instead relied only on validation scores. The test set should ideally be used only once to get a measure of algorithm performance when deployed on new data). Again, this problem may have diminishing returns to further hyperparameter optimization because of the small size of the dataset and there will eventually be a plateau in validation error (there is an inherent limit to the performance of any model on a dataset because of hidden variables that are not measured and noisy data, referred to as Bayes’ Error)." }, { "code": null, "e": 26421, "s": 26002, "text": "Automated hyperparameter tuning of machine learning models can be accomplished using Bayesian optimization. In contrast to random search, Bayesian optimization chooses the next hyperparameters in an informed method to spend more time evaluating promising values. The end outcome can be fewer evaluations of the objective function and better generalization performance on the test set compared to random or grid search." }, { "code": null, "e": 26971, "s": 26421, "text": "In this article, we walked step-by-step through Bayesian hyperparameter optimization in Python using Hyperopt. We were able to improve the test set performance of a Gradient Boosting Machine beyond both the baseline and random search although we need to be cautious of overfitting to the training data. Furthermore, we saw how random search differs from Bayesian Optimization by examining the resulting graphs which showed that the Bayesian method placed greater probability on the hyperparameter values that resulted in lower cross validation loss." }, { "code": null, "e": 27614, "s": 26971, "text": "Using the four parts of an optimization problem, we can use Hyperopt to solve a wide variety of problems. The basic parts of Bayesian optimization also apply to a number of libraries in Python that implement different algorithms. Making the switch from manual to random or grid search is one small step, but to take your machine learning to the next level requires some automated form of hyperparameter tuning. Bayesian Optimization is one approach that is both easy to use in Python and can return better results than random search. Hopefully you now feel confident to start using this powerful method for your own machine learning problems!" } ]
Find other two sides of a right angle triangle in C++
In this problem, we are given an integer a denoting one side of a right angle triangle. We need to check whether it is possible to have a right angle triangle with side a. If it is possible, then find the other two sides of a right angle triangle. Let’s take an example to understand the problem, a = 5 Sides : 5, 12, 13 The sides of right angle are found as 52 + 122 = 132 A simple solution to the problem is using pythagoras theorem. We know that the sides of a right angled triangle follow pythagoras theorem, which is a2 + b2 = c2 Where a and b are sides of the triangle and c is the hypotenuse of the triangle. Using this, we will calculate values of b and c using a. If a is even, c = (a2 + 4) + 1 b = (a2 + 4) - 1 If a is odd, c = (a2 + 1)/ 2 c = (a2 - 1)/ 2 Program to illustrate the working of our solution, Live Demo #include <bits/stdc++.h> #include <cmath> using namespace std; #define PI 3.1415926535 void printOtherSides(int n) { int b,c; if (n & 1) { if (n == 1) cout << -1 << endl; else{ b = (n*n-1)/2; c = (n*n+1)/2; } } else { if (n == 2) cout << -1 << endl; else{ b = n*n/4-1; c = n*n/4+1; } } cout<<"Sides : a = "<<n<<", b = "<<b<<", c = "<<c<<endl; } int main() { int a = 5; printOtherSides(a); return 0; } Sides : a = 5, b = 12, c = 13
[ { "code": null, "e": 1310, "s": 1062, "text": "In this problem, we are given an integer a denoting one side of a right angle\ntriangle. We need to check whether it is possible to have a right angle triangle with side a. If it is possible, then find the other two sides of a right angle triangle." }, { "code": null, "e": 1359, "s": 1310, "text": "Let’s take an example to understand the problem," }, { "code": null, "e": 1365, "s": 1359, "text": "a = 5" }, { "code": null, "e": 1383, "s": 1365, "text": "Sides : 5, 12, 13" }, { "code": null, "e": 1436, "s": 1383, "text": "The sides of right angle are found as 52 + 122 = 132" }, { "code": null, "e": 1584, "s": 1436, "text": "A simple solution to the problem is using pythagoras theorem. We know that the sides of a right angled triangle follow pythagoras theorem, which is" }, { "code": null, "e": 1597, "s": 1584, "text": "a2 + b2 = c2" }, { "code": null, "e": 1678, "s": 1597, "text": "Where a and b are sides of the triangle and c is the hypotenuse of the triangle." }, { "code": null, "e": 1735, "s": 1678, "text": "Using this, we will calculate values of b and c using a." }, { "code": null, "e": 1783, "s": 1735, "text": "If a is even,\nc = (a2 + 4) + 1\nb = (a2 + 4) - 1" }, { "code": null, "e": 1828, "s": 1783, "text": "If a is odd,\nc = (a2 + 1)/ 2\nc = (a2 - 1)/ 2" }, { "code": null, "e": 1879, "s": 1828, "text": "Program to illustrate the working of our solution," }, { "code": null, "e": 1890, "s": 1879, "text": " Live Demo" }, { "code": null, "e": 2405, "s": 1890, "text": "#include <bits/stdc++.h>\n#include <cmath>\nusing namespace std;\n#define PI 3.1415926535\nvoid printOtherSides(int n) {\n int b,c;\n if (n & 1) {\n if (n == 1)\n cout << -1 << endl;\n else{\n b = (n*n-1)/2;\n c = (n*n+1)/2;\n }\n } else {\n if (n == 2)\n cout << -1 << endl;\n else{\n b = n*n/4-1;\n c = n*n/4+1;\n }\n }\n cout<<\"Sides : a = \"<<n<<\", b = \"<<b<<\", c = \"<<c<<endl;\n}\nint main() {\n int a = 5;\n printOtherSides(a);\n return 0;\n}" }, { "code": null, "e": 2435, "s": 2405, "text": "Sides : a = 5, b = 12, c = 13" } ]
8085 program to convert gray to binary
Now let us see a program of Intel 8085 Microprocessor. This program will convert gray code to binary code. Write an assembly language program for 8085 to convert gray code to binary code. The data is stored at address 8200H & store the result at memory location 8201H. Here we are loading the number from memory and in each step we are performing right shift, and XOR the intermediate result with the previous one. Thus we are getting the result. In the following demonstration you can get the logic. C 1110 1011 (A) (EBH) 07H 0111 0101 (RAR) XOR 1110 1011 (D) 1001 1110 (A = A XOR D) (9EH) 06H 0100 1111 (RAR) XOR 1110 1011 (D) 1010 0100 (A = A XOR D) (A4H) 05H 0101 0010 (RAR) XOR 1110 1011 (D) 1011 1001 (A = A XOR D) (B9H) 04H 0101 1100 (RAR)XOR 1110 1011 (D) 1011 0111 (A = A XOR D) (B7H) 03H 0101 1011 (RAR) XOR 1110 1011 (D) 1011 0000 (A = A XOR D) (B0H) 02H 0101 1000 (RAR) XOR 1110 1011 (D) 1011 0011 (A = A XOR D) (B3H) 01H 0101 1001 (RAR) XOR 1110 1011 (D) 1011 0010 (A = A XOR D) (B2H) XOR 1110 1011 (D)
[ { "code": null, "e": 1169, "s": 1062, "text": "Now let us see a program of Intel 8085 Microprocessor. This program will convert gray code to binary code." }, { "code": null, "e": 1331, "s": 1169, "text": "Write an assembly language program for 8085 to convert gray code to binary code. The data is stored at address 8200H & store the result at memory location 8201H." }, { "code": null, "e": 1563, "s": 1331, "text": "Here we are loading the number from memory and in each step we are performing right shift, and XOR the intermediate result with the previous one. Thus we are getting the result. In the following demonstration you can get the logic." }, { "code": null, "e": 2243, "s": 1563, "text": "C 1110 1011 (A) (EBH)\n07H 0111 0101 (RAR)\nXOR 1110 1011 (D)\n 1001 1110 (A = A XOR D) (9EH)\n06H 0100 1111 (RAR)\nXOR 1110 1011 (D)\n 1010 0100 (A = A XOR D) (A4H)\n05H 0101 0010 (RAR)\nXOR 1110 1011 (D)\n 1011 1001 (A = A XOR D) (B9H)\n04H 0101 1100 (RAR)XOR 1110 1011 (D) 1011 0111 (A = A XOR D) (B7H)\n03H 0101 1011 (RAR)\nXOR 1110 1011 (D)\n 1011 0000 (A = A XOR D) (B0H)\n02H 0101 1000 (RAR)\nXOR 1110 1011 (D)\n 1011 0011 (A = A XOR D) (B3H)\n01H 0101 1001 (RAR)\nXOR 1110 1011 (D)\n 1011 0010 (A = A XOR D) (B2H) " }, { "code": null, "e": 2267, "s": 2243, "text": "XOR 1110 1011 (D)" } ]
C | Advanced Pointer | Question 7 - GeeksforGeeks
28 Jun, 2021 Assume that the size of int is 4. #include <stdio.h>void f(char**);int main(){ char *argv[] = { "ab", "cd", "ef", "gh", "ij", "kl" }; f(argv); return 0;}void f(char **p){ char *t; t = (p += sizeof(int))[-1]; printf("%s\n", t);} (A) ab(B) cd(C) ef(D) ghAnswer: (D)Explanation: The expression (p += sizeof(int))[-1] can be written as (p += 4)[-1] which can be written as (p = p+4)[-] which returns address p+3 which is address of fourth element in argv[].Quiz of this Question Advanced Pointer C-Advanced Pointer C Language C Quiz Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Multidimensional Arrays in C / C++ rand() and srand() in C/C++ Substring in C++ Core Dump (Segmentation fault) in C/C++ Left Shift and Right Shift Operators in C/C++ Compiling a C program:- Behind the Scenes Operator Precedence and Associativity in C C | Loops & Control Structure | Question 8 Output of C programs | Set 64 (Pointers) C | File Handling | Question 1
[ { "code": null, "e": 24466, "s": 24438, "text": "\n28 Jun, 2021" }, { "code": null, "e": 24500, "s": 24466, "text": "Assume that the size of int is 4." }, { "code": "#include <stdio.h>void f(char**);int main(){ char *argv[] = { \"ab\", \"cd\", \"ef\", \"gh\", \"ij\", \"kl\" }; f(argv); return 0;}void f(char **p){ char *t; t = (p += sizeof(int))[-1]; printf(\"%s\\n\", t);}", "e": 24712, "s": 24500, "text": null }, { "code": null, "e": 24959, "s": 24712, "text": "(A) ab(B) cd(C) ef(D) ghAnswer: (D)Explanation: The expression (p += sizeof(int))[-1] can be written as (p += 4)[-1] which can be written as (p = p+4)[-] which returns address p+3 which is address of fourth element in argv[].Quiz of this Question" }, { "code": null, "e": 24976, "s": 24959, "text": "Advanced Pointer" }, { "code": null, "e": 24995, "s": 24976, "text": "C-Advanced Pointer" }, { "code": null, "e": 25006, "s": 24995, "text": "C Language" }, { "code": null, "e": 25013, "s": 25006, "text": "C Quiz" }, { "code": null, "e": 25111, "s": 25013, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25146, "s": 25111, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 25174, "s": 25146, "text": "rand() and srand() in C/C++" }, { "code": null, "e": 25191, "s": 25174, "text": "Substring in C++" }, { "code": null, "e": 25231, "s": 25191, "text": "Core Dump (Segmentation fault) in C/C++" }, { "code": null, "e": 25277, "s": 25231, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 25319, "s": 25277, "text": "Compiling a C program:- Behind the Scenes" }, { "code": null, "e": 25362, "s": 25319, "text": "Operator Precedence and Associativity in C" }, { "code": null, "e": 25405, "s": 25362, "text": "C | Loops & Control Structure | Question 8" }, { "code": null, "e": 25446, "s": 25405, "text": "Output of C programs | Set 64 (Pointers)" } ]
Installing CUDA on Google Cloud Platform in 10 minutes | by Shruti | Towards Data Science
Recently, I spent *quite* some time setting up my CUDA instance on Google Cloud Platform (GCP). After a lot of errors and articles, I figured that it could have been done pretty quick, had I stumbled upon the correct setup process in the first go! So I decided to write this post to get your CUDA enabled instance running in minutes. By the end of this post, you will have CUDA 10.0, cuDNN 7.6.5 and Ubuntu 16.04 installed on GCP. Step 0: Create a free account on Google Cloud Platform (GCP) Create a free account on Google Cloud Platform. Enter your credit card details and verify. You will get 300$ credit. To use GPU, you will need to upgrade to a paid account and increase your GPU quota. If you don’t already have a verified, upgraded account, this step can take some time (usually 1–2 days). Step 1: Set up a VM instance on GCP Choose a project. I selected β€˜My First Project’ Create a VM instance in your project. Click on β€˜Create’. Select the number of CPU cores you need, and the GPU you want. I chose β€˜n1-standard-8' CPU and one β€˜P100 GPU’. Select the OS as Ubuntu 16.04 and the boot disk size. 200 GB is the recommended size. Tick firewall rules, then click on β€˜Management, security, disks, networking, sole tenancy’. Disable boot disk delete option under β€˜Disks’ Click on create at the end, and your instance is ready! Click on SSH to open a terminal. Your instance should be running. Don’t close the terminal. You will install CUDA and cuDNN in this terminal, NOT in your local desktop terminal. ALERT!! Your instance is up and running now. You are being CHARGED. IF your usage exceeds 300$ credit, you will have to pay the balance amount. DON’T forget to stop the instance when not in use. Step 2: Install CUDA I installed CUDA 10.0 for Ubuntu1604. You can install other CUDA versions as well and edit the following code accordingly. You might get libcudnn.so is not symbolic link error at this point. Check at the bottom of this post for the solution Step 3: Install CuDNN You need to create a developer account on Nvidia before proceeding, for free. To verify CUDA 10.0 installation, run the following command. It should print the CUDA version installed. nvcc -V Full code for easy reference. Step 4: Install Tensorflow and other packages You can install Tensorflow and basic python packages like ipython and pip. ALERT!! Don’t forget to STOP the instance! On sudo ldconfig, you might get the following error: /usr/local/cuda/lib64/libcudnn.so.7 is not a symbolic link This is because libcudnn.so.5 and libcudnn.so are not symlinks. You can read the details here. To solve the error, perform the following steps: This concludes our quick post on setting up a CUDA enabled VM instance on Google Cloud Platform. I hope you enjoyed this more technical post!
[ { "code": null, "e": 419, "s": 171, "text": "Recently, I spent *quite* some time setting up my CUDA instance on Google Cloud Platform (GCP). After a lot of errors and articles, I figured that it could have been done pretty quick, had I stumbled upon the correct setup process in the first go!" }, { "code": null, "e": 602, "s": 419, "text": "So I decided to write this post to get your CUDA enabled instance running in minutes. By the end of this post, you will have CUDA 10.0, cuDNN 7.6.5 and Ubuntu 16.04 installed on GCP." }, { "code": null, "e": 663, "s": 602, "text": "Step 0: Create a free account on Google Cloud Platform (GCP)" }, { "code": null, "e": 780, "s": 663, "text": "Create a free account on Google Cloud Platform. Enter your credit card details and verify. You will get 300$ credit." }, { "code": null, "e": 969, "s": 780, "text": "To use GPU, you will need to upgrade to a paid account and increase your GPU quota. If you don’t already have a verified, upgraded account, this step can take some time (usually 1–2 days)." }, { "code": null, "e": 1005, "s": 969, "text": "Step 1: Set up a VM instance on GCP" }, { "code": null, "e": 1053, "s": 1005, "text": "Choose a project. I selected β€˜My First Project’" }, { "code": null, "e": 1110, "s": 1053, "text": "Create a VM instance in your project. Click on β€˜Create’." }, { "code": null, "e": 1221, "s": 1110, "text": "Select the number of CPU cores you need, and the GPU you want. I chose β€˜n1-standard-8' CPU and one β€˜P100 GPU’." }, { "code": null, "e": 1307, "s": 1221, "text": "Select the OS as Ubuntu 16.04 and the boot disk size. 200 GB is the recommended size." }, { "code": null, "e": 1399, "s": 1307, "text": "Tick firewall rules, then click on β€˜Management, security, disks, networking, sole tenancy’." }, { "code": null, "e": 1445, "s": 1399, "text": "Disable boot disk delete option under β€˜Disks’" }, { "code": null, "e": 1501, "s": 1445, "text": "Click on create at the end, and your instance is ready!" }, { "code": null, "e": 1567, "s": 1501, "text": "Click on SSH to open a terminal. Your instance should be running." }, { "code": null, "e": 1679, "s": 1567, "text": "Don’t close the terminal. You will install CUDA and cuDNN in this terminal, NOT in your local desktop terminal." }, { "code": null, "e": 1874, "s": 1679, "text": "ALERT!! Your instance is up and running now. You are being CHARGED. IF your usage exceeds 300$ credit, you will have to pay the balance amount. DON’T forget to stop the instance when not in use." }, { "code": null, "e": 1895, "s": 1874, "text": "Step 2: Install CUDA" }, { "code": null, "e": 2018, "s": 1895, "text": "I installed CUDA 10.0 for Ubuntu1604. You can install other CUDA versions as well and edit the following code accordingly." }, { "code": null, "e": 2136, "s": 2018, "text": "You might get libcudnn.so is not symbolic link error at this point. Check at the bottom of this post for the solution" }, { "code": null, "e": 2158, "s": 2136, "text": "Step 3: Install CuDNN" }, { "code": null, "e": 2236, "s": 2158, "text": "You need to create a developer account on Nvidia before proceeding, for free." }, { "code": null, "e": 2341, "s": 2236, "text": "To verify CUDA 10.0 installation, run the following command. It should print the CUDA version installed." }, { "code": null, "e": 2350, "s": 2341, "text": "nvcc -V " }, { "code": null, "e": 2380, "s": 2350, "text": "Full code for easy reference." }, { "code": null, "e": 2426, "s": 2380, "text": "Step 4: Install Tensorflow and other packages" }, { "code": null, "e": 2501, "s": 2426, "text": "You can install Tensorflow and basic python packages like ipython and pip." }, { "code": null, "e": 2544, "s": 2501, "text": "ALERT!! Don’t forget to STOP the instance!" }, { "code": null, "e": 2597, "s": 2544, "text": "On sudo ldconfig, you might get the following error:" }, { "code": null, "e": 2656, "s": 2597, "text": "/usr/local/cuda/lib64/libcudnn.so.7 is not a symbolic link" }, { "code": null, "e": 2751, "s": 2656, "text": "This is because libcudnn.so.5 and libcudnn.so are not symlinks. You can read the details here." }, { "code": null, "e": 2800, "s": 2751, "text": "To solve the error, perform the following steps:" }, { "code": null, "e": 2897, "s": 2800, "text": "This concludes our quick post on setting up a CUDA enabled VM instance on Google Cloud Platform." } ]
How to generate all permutations of a list in Python?
You can use the itertools package's permutations method to find all permutations of a list in Python. You can use it as follows βˆ’ import itertools perms = list(itertools.permutations([1, 2, 3])) print(perms) This will give the output βˆ’ [(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]
[ { "code": null, "e": 1192, "s": 1062, "text": "You can use the itertools package's permutations method to find all permutations of a list in Python. You can use it as follows βˆ’" }, { "code": null, "e": 1270, "s": 1192, "text": "import itertools\nperms = list(itertools.permutations([1, 2, 3]))\nprint(perms)" }, { "code": null, "e": 1298, "s": 1270, "text": "This will give the output βˆ’" }, { "code": null, "e": 1365, "s": 1298, "text": "[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]" } ]
Add line for average per group using ggplot2 package in R - GeeksforGeeks
03 Dec, 2021 In this article, we will discuss how to add a line for average per group in a scatter plot in the R Programming Language. In the R Language, we can do so by creating a mean vector by using the group_by() and summarise() function. Then we can use that mean vector along with the geom_hline() function of the ggplot2 package to create a line by the mean point colored by the group. To create a mean vector from the data frame, Syntax: mean <- df %>% group_by( <categorical-variable> ) %>% summarise( mean_val = mean( <quantitative-variable> ) Arguments: df: determines the data frame to be used. <categorical-variable>: determines the variable that is used to divide data into groups. <quantitative-variable>: determines the variable whose mean is to be found. This expression creates a vector with two columns i.e. <categorical-variable> and the mean that stores mean by category. Now, we will use this mean vector with the geom_hline() function to add a horizontal line at the mean/average of data colored by categorical variable. Syntax: plot + geom_hline( mean_df, aes( yintercept, col ) Arguments: mean_df: determines the data frame that contains mean information. yintercept: determines the variable mean column in dataframe. col: determines the categorical variable by which line has to be colored. Example 1: Here in this example, we have created a scatter plot colored by a categorical variable. Then we have added a line colored by the same variable that goes through the mean of that category of data. R # load library tidyverselibrary(tidyverse) # create dataframedf <- data.frame( group=factor(rep(c("category1", "category2","category3"), each=100)), y=round(c(rnorm(100, mean=65, sd=5), rnorm(100, mean=85, sd=5), rnorm(100, mean=105, sd=5))), x=rnorm(300)) # create mean by groupmean <- df%>% group_by(group)%>%summarise(mean_val=mean(y)) # create ggplot scatter plot# add horizontal line overlay at mean using geom_hline()ggplot(data = df, aes(x= x, y=y)) +geom_point(aes(colour = group)) +geom_hline(data= mean, aes(yintercept = mean_val,col=group)) Output: Example 2: In this example, we have created a scatter plot colored by a categorical variable. Then we have added a line colored by the same variable that goes through the mean of that category of data. We have also added a facet_grid() to convert this plot into a facet plot to better visualize the data through a categorical variable. R # load library tidyverselibrary(tidyverse) # create dataframedf <- data.frame( group=factor(rep(c("category1", "category2","category3"), each=100)), y=round(c(rnorm(100, mean=65, sd=5), rnorm(100, mean=55, sd=5), rnorm(100, mean=60, sd=5))), x=rnorm(300)) # create mean by groupmean <- df%>% group_by(group)%>%summarise(mean_val=mean(y)) # create ggplot scatter plot# add horizontal line overlay at mean using geom_hline()# divide plot in facet using function facet_grid()ggplot(data = df, aes(x= x, y=y)) +geom_point(aes(colour = group)) +geom_hline(data= mean, aes(yintercept = mean_val,col=group))+facet_grid(~group) Output: surindertarika1234 Picked R-ggplot R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Change Color of Bars in Barchart using ggplot2 in R How to Change Axis Scales in R Plots? Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? Replace Specific Characters in String in R How to filter R dataframe by multiple conditions? R - if statement How to import an Excel File into R ? Time Series Analysis in R
[ { "code": null, "e": 24851, "s": 24823, "text": "\n03 Dec, 2021" }, { "code": null, "e": 24973, "s": 24851, "text": "In this article, we will discuss how to add a line for average per group in a scatter plot in the R Programming Language." }, { "code": null, "e": 25231, "s": 24973, "text": "In the R Language, we can do so by creating a mean vector by using the group_by() and summarise() function. Then we can use that mean vector along with the geom_hline() function of the ggplot2 package to create a line by the mean point colored by the group." }, { "code": null, "e": 25276, "s": 25231, "text": "To create a mean vector from the data frame," }, { "code": null, "e": 25284, "s": 25276, "text": "Syntax:" }, { "code": null, "e": 25394, "s": 25284, "text": "mean <- df %>% \ngroup_by( <categorical-variable> ) %>% \nsummarise( mean_val = mean( <quantitative-variable> )" }, { "code": null, "e": 25405, "s": 25394, "text": "Arguments:" }, { "code": null, "e": 25447, "s": 25405, "text": "df: determines the data frame to be used." }, { "code": null, "e": 25536, "s": 25447, "text": "<categorical-variable>: determines the variable that is used to divide data into groups." }, { "code": null, "e": 25612, "s": 25536, "text": "<quantitative-variable>: determines the variable whose mean is to be found." }, { "code": null, "e": 25884, "s": 25612, "text": "This expression creates a vector with two columns i.e. <categorical-variable> and the mean that stores mean by category. Now, we will use this mean vector with the geom_hline() function to add a horizontal line at the mean/average of data colored by categorical variable." }, { "code": null, "e": 25892, "s": 25884, "text": "Syntax:" }, { "code": null, "e": 25943, "s": 25892, "text": "plot + geom_hline( mean_df, aes( yintercept, col )" }, { "code": null, "e": 25954, "s": 25943, "text": "Arguments:" }, { "code": null, "e": 26021, "s": 25954, "text": "mean_df: determines the data frame that contains mean information." }, { "code": null, "e": 26083, "s": 26021, "text": "yintercept: determines the variable mean column in dataframe." }, { "code": null, "e": 26157, "s": 26083, "text": "col: determines the categorical variable by which line has to be colored." }, { "code": null, "e": 26168, "s": 26157, "text": "Example 1:" }, { "code": null, "e": 26364, "s": 26168, "text": "Here in this example, we have created a scatter plot colored by a categorical variable. Then we have added a line colored by the same variable that goes through the mean of that category of data." }, { "code": null, "e": 26366, "s": 26364, "text": "R" }, { "code": "# load library tidyverselibrary(tidyverse) # create dataframedf <- data.frame( group=factor(rep(c(\"category1\", \"category2\",\"category3\"), each=100)), y=round(c(rnorm(100, mean=65, sd=5), rnorm(100, mean=85, sd=5), rnorm(100, mean=105, sd=5))), x=rnorm(300)) # create mean by groupmean <- df%>% group_by(group)%>%summarise(mean_val=mean(y)) # create ggplot scatter plot# add horizontal line overlay at mean using geom_hline()ggplot(data = df, aes(x= x, y=y)) +geom_point(aes(colour = group)) +geom_hline(data= mean, aes(yintercept = mean_val,col=group))", "e": 26983, "s": 26366, "text": null }, { "code": null, "e": 26991, "s": 26983, "text": "Output:" }, { "code": null, "e": 27004, "s": 26993, "text": "Example 2:" }, { "code": null, "e": 27329, "s": 27004, "text": "In this example, we have created a scatter plot colored by a categorical variable. Then we have added a line colored by the same variable that goes through the mean of that category of data. We have also added a facet_grid() to convert this plot into a facet plot to better visualize the data through a categorical variable." }, { "code": null, "e": 27331, "s": 27329, "text": "R" }, { "code": "# load library tidyverselibrary(tidyverse) # create dataframedf <- data.frame( group=factor(rep(c(\"category1\", \"category2\",\"category3\"), each=100)), y=round(c(rnorm(100, mean=65, sd=5), rnorm(100, mean=55, sd=5), rnorm(100, mean=60, sd=5))), x=rnorm(300)) # create mean by groupmean <- df%>% group_by(group)%>%summarise(mean_val=mean(y)) # create ggplot scatter plot# add horizontal line overlay at mean using geom_hline()# divide plot in facet using function facet_grid()ggplot(data = df, aes(x= x, y=y)) +geom_point(aes(colour = group)) +geom_hline(data= mean, aes(yintercept = mean_val,col=group))+facet_grid(~group)", "e": 28016, "s": 27331, "text": null }, { "code": null, "e": 28024, "s": 28016, "text": "Output:" }, { "code": null, "e": 28043, "s": 28024, "text": "surindertarika1234" }, { "code": null, "e": 28050, "s": 28043, "text": "Picked" }, { "code": null, "e": 28059, "s": 28050, "text": "R-ggplot" }, { "code": null, "e": 28070, "s": 28059, "text": "R Language" }, { "code": null, "e": 28168, "s": 28070, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28177, "s": 28168, "text": "Comments" }, { "code": null, "e": 28190, "s": 28177, "text": "Old Comments" }, { "code": null, "e": 28242, "s": 28190, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 28280, "s": 28242, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 28315, "s": 28280, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 28373, "s": 28315, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 28422, "s": 28373, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 28465, "s": 28422, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 28515, "s": 28465, "text": "How to filter R dataframe by multiple conditions?" }, { "code": null, "e": 28532, "s": 28515, "text": "R - if statement" }, { "code": null, "e": 28569, "s": 28532, "text": "How to import an Excel File into R ?" } ]
Multi-Agent Deep Reinforcement Learning in 13 Lines of Code Using PettingZoo | by J K Terry | Towards Data Science
This tutorial provides a simple introduction to using multi-agent reinforcement learning, assuming a little experience in machine learning and knowledge of Python. Reinforcement stems from using machine learning to optimally control an agent in an environment. It works by learning a policy, a function that maps an observation obtained from its environment to an action. Policy functions are typically deep neural networks, which gives rise to the name β€œdeep reinforcement learning.” The goal of reinforcement learning is to learn an optimal policy, a policy that achieves the maximum expected reward from the environment when acting. The reward is a single dimensionless value that is returned by the environment immediately after an action. The whole process can be visualized like this: This paradigm of reinforcement learning encompasses and incredible variety of scenarios, like a character in a computer game (e.g. Atari where the reward is the change in score), a robot delivering food in a city (where the agent is rewarded positively for successfully completing a trip and penalized for taking too long), or a bot trading stocks (where the reward is money gained). Learning to play multiplayer games represents many of the most profound achievements of artificial intelligence in our lifetimes. These accomplishments include learning to play Go, DOTA 2, and StarCraft 2 to superhuman levels of performance. Using reinforcement learning to control multiple agents, unsurprisingly, is referred to as multi-agent reinforcement learning. In general it’s the same as single agent reinforcement learning, where each agent is trying to learn it’s own policy to optimize its own reward. Using a central policy for all agents is possible, but multiple agents would have to communicate with a central server to compute their actions (which is problematic in most real world scenarios), so in practice decentralized multi-agent reinforcement learning is used. This can be visualized as follows: Multi-agent deep reinforcement learning, what we’ll be doing today, similarly just uses deep neural networks to represent the learned policies in multi-agent reinforcement learning. Gym is a famous library in reinforcement learning developed by OpenAI that provides a standard API for environments so that they can be easily learned with different reinforcement learning codebases, and so that for the same learning code base different environments can be easily tried. PettingZoo is a newer library that’s like a multi-agent version of Gym. It’s basic API usage looks like this: from pettingzoo.butterfly import pistonball_v5env = pistonball_v5.env()env.reset()for agent in env.agent_iter(): observation, reward, done, info = env.last() action = policy(observation, agent) env.step(action) The environment we’ll be learning today is Pistonball, a cooperative environment from PettingZoo: In it, each piston is an agent that can be separately controlled by a policy. The observation is the space above and next to the piston, e.g: The action the policy returns is the amount to raise or lower the piston (from -4 to 4 pixels). The goal is for the pistons to learn how to work together to roll the ball to the left wall as fast as possible. Each piston agent is rewarded negatively if the ball moves right, positively if the ball moves left, and receives a small amount of negative reward at every time step to incentivize moving to the left as fast as possible. A plethora of techniques exist to learn a single agent environment in reinforcement learning. These serve as the basis for algorithms in multi-agent reinforcement learning. The simplest and most popular way to do this is to have a single policy network shared between all agents, so that all agents use the same function to pick an action. Each agent can train this shared network using any single agent method. This is typically referred to as parameter sharing. That’s what we’ll be using today, with the PPO single agent method (one of the best methods for continuous control tasks like this). First we begin with imports: from stable_baselines3.ppo import CnnPolicyfrom stable_baselines3 import PPOfrom pettingzoo.butterfly import pistonball_v5import supersuit as ss PettingZoo we’ve already discussed, but let’s talk about Stable Baselines. A few years back OpenAI released the β€œbaselines” repository which included implementations of most of the major deep reinforcement learning algorithms. This repository was turned into the Stable Baselines library intended for beginners and practitioners of reinforcement learning to easily use to learn Gym environments. The CnnPolicy in it is just a deep convolutional neural network object that Stable Baselines includes which automatically resizes the input and output layers of the neural network to adapt to the observation and action space of the environment. SuperSuit is a package that provides preprocessing functions for both Gym and PettingZoo environments, as we’ll see below. Environments and wrappers are versioned to ensure comparisons are precisely reproducible in academic research. First, we initialize the PettingZoo environment: env = pistonball_v5.parallel_env(n_pistons=20, time_penalty=-0.1, continuous=True, random_drop=True, random_rotate=True, ball_mass=0.75, ball_friction=0.3, ball_elasticity=1.5, max_cycles=125) Each of those arguments control how the environment functions in various ways and is documented here. The alternative parallel_env mode we need to use here is documented here. The first problem we have to deal with is that the environment’s observations are full color images. We don’t need the color information and it’s 3x more computationally expensive for the neural networks to process than grayscale images due to the 3 color channels. We can fix this by wrapping the environment with SuperSuit (remember we imported it as ss above) shown below: env = ss.color_reduction_v0(env, mode=’B’) Note that the B flag actually takes the Blue channel of the image instead of turning all the channels into grayscale to save processing time as this will be done hundreds of thousands of times during training. After this, observations will look like this: Despite the observations for each piston being greyscale, the images are still very large and contain more information than we need. Let’s shrink them down; 84x84 is a popular size for this in reinforcement learning because it was used in a famous paper by DeepMind. Fixing that with SuperSuit looks like this: env = ss.resize_v0(env, x_size=84, y_size=84) After this, the observations will look something like this: The last major thing we want to do is slightly odd at first. Because the ball is on motion, we want to give the policy network an easy way of seeing how fast it’s moving and accelerating. The simplest way to do that is to stack the past few frames together as the channels of each observation. Stacking 3 together gives enough information to compute acceleration, but 4 is more standard. This is how you do that with SuperSuit: env = ss.frame_stack_v1(env, 3) Next, we need to convert the environments API a tiny bit, which will cause Stable Baselines to do parameter sharing of the policy network on a multiagent environment (instead of learning a single-agent environment like normal). The details of this are beyond the scope of this tutorial, but are documented here for those who want to know more. env = ss.pettingzoo_env_to_vec_env_v1(env) Finally, we need to set the environment to run multiple versions of itself in parallel. Playing through the environment multiple times at once makes learning faster and is important to PPOs learning performance. SuperSuit offers many ways to do this and the one we want to use here is this: env = ss.concat_vec_envs_v1(env, 8, num_cpus=4, base_class=’stable_baselines3’) 8 refers to the number of times we’re duplicating the environment, and num_cpus is the number of CPU cores these will be run on. These are hyperparameters and you’re free to play around with these. In our experience running more than 2 environments per thread can get problematically slow, so keep that in mind. Finally, we can get to some actual learning. This can be done pretty easily with Stable Baselines with three more lines of code: model = PPO(CnnPolicy, env, verbose=3, gamma=0.95, n_steps=256, ent_coef=0.0905168, learning_rate=0.00062211, vf_coef=0.042202, max_grad_norm=0.9, gae_lambda=0.99, n_epochs=5, clip_range=0.3, batch_size=256)model.learn(total_timesteps=2000000)model.save(β€œpolicy”) This instantiates the PPO learning object, then trains and saves the policy network to disk. All the arguments are hyperparameters, which you can read about in great detail here (they’ve all been tuned with Optuna). The timesteps argument in the .learn() method refers to actions taken by an individual agent, not the total number of times the game is played. Training will take roughly 2 hours with a modern 8 core CPU and a 1080Ti (like all deep learning this is fairly GPU intensive). If you don’t have a GPU, training this on Google Cloud Platform with a T4 GPU should cost less than $2. Once we’ve trained and save this model, we can load our policy and watch it play. First, let’s reinstantiate the environment, using the normal API this time: env = pistonball_v5.env()env = ss.color_reduction_v0(env, mode=’B’)env = ss.resize_v0(env, x_size=84, y_size=84)env = ss.frame_stack_v1(env, 3) Then, let’s load the policy model = PPO.load(β€œpolicy”) We can them use the policy to render it on your desktop as follows: env.reset()for agent in env.agent_iter(): obs, reward, done, info = env.last() act = model.predict(obs, deterministic=True)[0] if not done else None env.step(act) env.render() That should produce something like this gif: Notice how this is actually better than the gif shown at the beginning. This is because the gif at the beginning was generated with a hand made policy available here, whereas this one was actually learned The full code for this tutorial is available here. If you found this tutorial useful, consider starring the projects involved (PettingZoo, SuperSuit and Stable Baselines3).
[ { "code": null, "e": 336, "s": 172, "text": "This tutorial provides a simple introduction to using multi-agent reinforcement learning, assuming a little experience in machine learning and knowledge of Python." }, { "code": null, "e": 657, "s": 336, "text": "Reinforcement stems from using machine learning to optimally control an agent in an environment. It works by learning a policy, a function that maps an observation obtained from its environment to an action. Policy functions are typically deep neural networks, which gives rise to the name β€œdeep reinforcement learning.”" }, { "code": null, "e": 963, "s": 657, "text": "The goal of reinforcement learning is to learn an optimal policy, a policy that achieves the maximum expected reward from the environment when acting. The reward is a single dimensionless value that is returned by the environment immediately after an action. The whole process can be visualized like this:" }, { "code": null, "e": 1347, "s": 963, "text": "This paradigm of reinforcement learning encompasses and incredible variety of scenarios, like a character in a computer game (e.g. Atari where the reward is the change in score), a robot delivering food in a city (where the agent is rewarded positively for successfully completing a trip and penalized for taking too long), or a bot trading stocks (where the reward is money gained)." }, { "code": null, "e": 2166, "s": 1347, "text": "Learning to play multiplayer games represents many of the most profound achievements of artificial intelligence in our lifetimes. These accomplishments include learning to play Go, DOTA 2, and StarCraft 2 to superhuman levels of performance. Using reinforcement learning to control multiple agents, unsurprisingly, is referred to as multi-agent reinforcement learning. In general it’s the same as single agent reinforcement learning, where each agent is trying to learn it’s own policy to optimize its own reward. Using a central policy for all agents is possible, but multiple agents would have to communicate with a central server to compute their actions (which is problematic in most real world scenarios), so in practice decentralized multi-agent reinforcement learning is used. This can be visualized as follows:" }, { "code": null, "e": 2348, "s": 2166, "text": "Multi-agent deep reinforcement learning, what we’ll be doing today, similarly just uses deep neural networks to represent the learned policies in multi-agent reinforcement learning." }, { "code": null, "e": 2746, "s": 2348, "text": "Gym is a famous library in reinforcement learning developed by OpenAI that provides a standard API for environments so that they can be easily learned with different reinforcement learning codebases, and so that for the same learning code base different environments can be easily tried. PettingZoo is a newer library that’s like a multi-agent version of Gym. It’s basic API usage looks like this:" }, { "code": null, "e": 2966, "s": 2746, "text": "from pettingzoo.butterfly import pistonball_v5env = pistonball_v5.env()env.reset()for agent in env.agent_iter(): observation, reward, done, info = env.last() action = policy(observation, agent) env.step(action)" }, { "code": null, "e": 3064, "s": 2966, "text": "The environment we’ll be learning today is Pistonball, a cooperative environment from PettingZoo:" }, { "code": null, "e": 3206, "s": 3064, "text": "In it, each piston is an agent that can be separately controlled by a policy. The observation is the space above and next to the piston, e.g:" }, { "code": null, "e": 3637, "s": 3206, "text": "The action the policy returns is the amount to raise or lower the piston (from -4 to 4 pixels). The goal is for the pistons to learn how to work together to roll the ball to the left wall as fast as possible. Each piston agent is rewarded negatively if the ball moves right, positively if the ball moves left, and receives a small amount of negative reward at every time step to incentivize moving to the left as fast as possible." }, { "code": null, "e": 4234, "s": 3637, "text": "A plethora of techniques exist to learn a single agent environment in reinforcement learning. These serve as the basis for algorithms in multi-agent reinforcement learning. The simplest and most popular way to do this is to have a single policy network shared between all agents, so that all agents use the same function to pick an action. Each agent can train this shared network using any single agent method. This is typically referred to as parameter sharing. That’s what we’ll be using today, with the PPO single agent method (one of the best methods for continuous control tasks like this)." }, { "code": null, "e": 4263, "s": 4234, "text": "First we begin with imports:" }, { "code": null, "e": 4408, "s": 4263, "text": "from stable_baselines3.ppo import CnnPolicyfrom stable_baselines3 import PPOfrom pettingzoo.butterfly import pistonball_v5import supersuit as ss" }, { "code": null, "e": 5283, "s": 4408, "text": "PettingZoo we’ve already discussed, but let’s talk about Stable Baselines. A few years back OpenAI released the β€œbaselines” repository which included implementations of most of the major deep reinforcement learning algorithms. This repository was turned into the Stable Baselines library intended for beginners and practitioners of reinforcement learning to easily use to learn Gym environments. The CnnPolicy in it is just a deep convolutional neural network object that Stable Baselines includes which automatically resizes the input and output layers of the neural network to adapt to the observation and action space of the environment. SuperSuit is a package that provides preprocessing functions for both Gym and PettingZoo environments, as we’ll see below. Environments and wrappers are versioned to ensure comparisons are precisely reproducible in academic research." }, { "code": null, "e": 5332, "s": 5283, "text": "First, we initialize the PettingZoo environment:" }, { "code": null, "e": 5525, "s": 5332, "text": "env = pistonball_v5.parallel_env(n_pistons=20, time_penalty=-0.1, continuous=True, random_drop=True, random_rotate=True, ball_mass=0.75, ball_friction=0.3, ball_elasticity=1.5, max_cycles=125)" }, { "code": null, "e": 5701, "s": 5525, "text": "Each of those arguments control how the environment functions in various ways and is documented here. The alternative parallel_env mode we need to use here is documented here." }, { "code": null, "e": 6077, "s": 5701, "text": "The first problem we have to deal with is that the environment’s observations are full color images. We don’t need the color information and it’s 3x more computationally expensive for the neural networks to process than grayscale images due to the 3 color channels. We can fix this by wrapping the environment with SuperSuit (remember we imported it as ss above) shown below:" }, { "code": null, "e": 6120, "s": 6077, "text": "env = ss.color_reduction_v0(env, mode=’B’)" }, { "code": null, "e": 6376, "s": 6120, "text": "Note that the B flag actually takes the Blue channel of the image instead of turning all the channels into grayscale to save processing time as this will be done hundreds of thousands of times during training. After this, observations will look like this:" }, { "code": null, "e": 6687, "s": 6376, "text": "Despite the observations for each piston being greyscale, the images are still very large and contain more information than we need. Let’s shrink them down; 84x84 is a popular size for this in reinforcement learning because it was used in a famous paper by DeepMind. Fixing that with SuperSuit looks like this:" }, { "code": null, "e": 6733, "s": 6687, "text": "env = ss.resize_v0(env, x_size=84, y_size=84)" }, { "code": null, "e": 6793, "s": 6733, "text": "After this, the observations will look something like this:" }, { "code": null, "e": 7221, "s": 6793, "text": "The last major thing we want to do is slightly odd at first. Because the ball is on motion, we want to give the policy network an easy way of seeing how fast it’s moving and accelerating. The simplest way to do that is to stack the past few frames together as the channels of each observation. Stacking 3 together gives enough information to compute acceleration, but 4 is more standard. This is how you do that with SuperSuit:" }, { "code": null, "e": 7253, "s": 7221, "text": "env = ss.frame_stack_v1(env, 3)" }, { "code": null, "e": 7597, "s": 7253, "text": "Next, we need to convert the environments API a tiny bit, which will cause Stable Baselines to do parameter sharing of the policy network on a multiagent environment (instead of learning a single-agent environment like normal). The details of this are beyond the scope of this tutorial, but are documented here for those who want to know more." }, { "code": null, "e": 7640, "s": 7597, "text": "env = ss.pettingzoo_env_to_vec_env_v1(env)" }, { "code": null, "e": 7931, "s": 7640, "text": "Finally, we need to set the environment to run multiple versions of itself in parallel. Playing through the environment multiple times at once makes learning faster and is important to PPOs learning performance. SuperSuit offers many ways to do this and the one we want to use here is this:" }, { "code": null, "e": 8011, "s": 7931, "text": "env = ss.concat_vec_envs_v1(env, 8, num_cpus=4, base_class=’stable_baselines3’)" }, { "code": null, "e": 8323, "s": 8011, "text": "8 refers to the number of times we’re duplicating the environment, and num_cpus is the number of CPU cores these will be run on. These are hyperparameters and you’re free to play around with these. In our experience running more than 2 environments per thread can get problematically slow, so keep that in mind." }, { "code": null, "e": 8452, "s": 8323, "text": "Finally, we can get to some actual learning. This can be done pretty easily with Stable Baselines with three more lines of code:" }, { "code": null, "e": 8716, "s": 8452, "text": "model = PPO(CnnPolicy, env, verbose=3, gamma=0.95, n_steps=256, ent_coef=0.0905168, learning_rate=0.00062211, vf_coef=0.042202, max_grad_norm=0.9, gae_lambda=0.99, n_epochs=5, clip_range=0.3, batch_size=256)model.learn(total_timesteps=2000000)model.save(β€œpolicy”)" }, { "code": null, "e": 9076, "s": 8716, "text": "This instantiates the PPO learning object, then trains and saves the policy network to disk. All the arguments are hyperparameters, which you can read about in great detail here (they’ve all been tuned with Optuna). The timesteps argument in the .learn() method refers to actions taken by an individual agent, not the total number of times the game is played." }, { "code": null, "e": 9308, "s": 9076, "text": "Training will take roughly 2 hours with a modern 8 core CPU and a 1080Ti (like all deep learning this is fairly GPU intensive). If you don’t have a GPU, training this on Google Cloud Platform with a T4 GPU should cost less than $2." }, { "code": null, "e": 9466, "s": 9308, "text": "Once we’ve trained and save this model, we can load our policy and watch it play. First, let’s reinstantiate the environment, using the normal API this time:" }, { "code": null, "e": 9610, "s": 9466, "text": "env = pistonball_v5.env()env = ss.color_reduction_v0(env, mode=’B’)env = ss.resize_v0(env, x_size=84, y_size=84)env = ss.frame_stack_v1(env, 3)" }, { "code": null, "e": 9638, "s": 9610, "text": "Then, let’s load the policy" }, { "code": null, "e": 9665, "s": 9638, "text": "model = PPO.load(β€œpolicy”)" }, { "code": null, "e": 9733, "s": 9665, "text": "We can them use the policy to render it on your desktop as follows:" }, { "code": null, "e": 9917, "s": 9733, "text": "env.reset()for agent in env.agent_iter(): obs, reward, done, info = env.last() act = model.predict(obs, deterministic=True)[0] if not done else None env.step(act) env.render()" }, { "code": null, "e": 9962, "s": 9917, "text": "That should produce something like this gif:" }, { "code": null, "e": 10167, "s": 9962, "text": "Notice how this is actually better than the gif shown at the beginning. This is because the gif at the beginning was generated with a hand made policy available here, whereas this one was actually learned" } ]
Accessing HTML source code using Python Selenium.
We can access HTML source code with Selenium webdriver. We can take the help of the page_source method and print the value obtained from it in the console. src = driver.page_source We can also access the HTML source code with the help of Javascript commands in Selenium. We shall take the help of execute_script method and pass the command return document.body.innerHTML as a parameter to the method. h = driver.execute_script("return document.body.innerHTML;") Code Implementation. from selenium import webdriver driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe") driver.implicitly_wait(0.5) driver.get("https://www.tutorialspoint.com/index.htm") # access HTML source code with page_source method s = driver.page_source print(s) Code Implementation with Javascript Executor. from selenium import webdriver driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe") driver.implicitly_wait(0.5) driver.get("https://www.tutorialspoint.com/index.htm") # access HTML source code with Javascript command h = driver.execute_script("return document.body.innerHTML") print(h)
[ { "code": null, "e": 1218, "s": 1062, "text": "We can access HTML source code with Selenium webdriver. We can take the help of the page_source method and print the value obtained from it in the console." }, { "code": null, "e": 1243, "s": 1218, "text": "src = driver.page_source" }, { "code": null, "e": 1463, "s": 1243, "text": "We can also access the HTML source code with the help of Javascript commands in Selenium. We shall take the help of execute_script method and pass the command return document.body.innerHTML as a parameter to the method." }, { "code": null, "e": 1524, "s": 1463, "text": "h = driver.execute_script(\"return document.body.innerHTML;\")" }, { "code": null, "e": 1545, "s": 1524, "text": "Code Implementation." }, { "code": null, "e": 1807, "s": 1545, "text": "from selenium import webdriver\ndriver = webdriver.Chrome(executable_path=\"C:\\\\chromedriver.exe\")\ndriver.implicitly_wait(0.5)\ndriver.get(\"https://www.tutorialspoint.com/index.htm\")\n# access HTML source code with page_source method\ns = driver.page_source\nprint(s)" }, { "code": null, "e": 1853, "s": 1807, "text": "Code Implementation with Javascript Executor." }, { "code": null, "e": 2152, "s": 1853, "text": "from selenium import webdriver\ndriver = webdriver.Chrome(executable_path=\"C:\\\\chromedriver.exe\")\ndriver.implicitly_wait(0.5)\ndriver.get(\"https://www.tutorialspoint.com/index.htm\")\n# access HTML source code with Javascript command\nh = driver.execute_script(\"return document.body.innerHTML\")\nprint(h)" } ]
How to Convert CSV to JSON file and vice-versa in JavaScript ? - GeeksforGeeks
22 Apr, 2021 CSV files are a common file format used to store data in a table-like manner. They can be particularly useful when a user intends to download structured information in a way that they can easily open and read on their local machine. CSV files are ideal for this because of their portability and universality. In this article, we will explain how to convert JavaScript objects JSON to the CSV file format and vice-versa. This code does not use any external libraries, and thus it works on both the browser and Node.js. To convert from JSON to CSV, we first need to identify the headers of the CSV file. To do this, let’s get a list of keys present in each of the JavaScript objects that has been passed in. To get this list of keys, use the `Object.keys()` method. Javascript <script> const JSONToCSV = (objArray, keys) => { let csv = keys.join(','); objArray.forEach((row) => { let values = []; keys.forEach((key) => { values.push(row[key] || ''); }); csv += '\n' + values.join(','); }); return csv; }; const exampleJSON = [ { "date": 20210307, "positives": 28756184, "fatalities": 515148 }, { "date": 20210306, "positives": 28714654, "fatalities": 514309 }, { "date": 20210305, "positives": 28654639, "fatalities": 512629 }, { "date": 20210304, "positives": 28585852, "fatalities": 510408 }, { "date": 20210303, "positives": 28520365, "fatalities": 508665 }, { "date": 20210302, "positives": 28453529, "fatalities": 506216 }, { "date": 20210301, "positives": 28399281, "fatalities": 504488 } ]; console.log(JSONToCSV(exampleJSON, ['date', 'positives', 'fatalities']));</script> This code can be simplified to: Javascript <script> const JSONToCSV = (objArray, keys) => [ keys.join(','), ...objArray.map( row => keys.map(k => row[k] || '') .join(','))].join('\n'); const exampleJSON = [ { "date": 20210307, "positives": 28756184, "fatalities": 515148 }, { "date": 20210306, "positives": 28714654, "fatalities": 514309 }, { "date": 20210305, "positives": 28654639, "fatalities": 512629 }, { "date": 20210304, "positives": 28585852, "fatalities": 510408 }, { "date": 20210303, "positives": 28520365, "fatalities": 508665 }, { "date": 20210302, "positives": 28453529, "fatalities": 506216 }, { "date": 20210301, "positives": 28399281, "fatalities": 504488 } ]; console.log(JSONToCSV(exampleJSON, ['date', 'positives', 'fatalities']));</script> Output: date, positives, fatalities 20210307, 28756184, 515148 20210306, 28714654, 514309 20210305, 28654639, 512629 20210304, 28585852, 510408 20210303, 28520365, 508665 20210302, 28453529, 506216 20210301, 28399281, 504488 To convert from CSV to JSON, first identify a list of keys for each JavaScript object by parsing the CSV headers, then add each key and value to a new object for each CSV row. Javascript <script> const CSVToJSON = csv => { const lines = csv.split('\n'); const keys = lines[0].split(','); return lines.slice(1).map(line => { return line.split(',').reduce((acc, cur, i) => { const toAdd = {}; toAdd[keys[i]] = cur; return { ...acc, ...toAdd }; }, {}); }); }; const exampleCSV = ` date,positives,fatalities 20210307,28756184,515148 20210306,28714654,514309 20210305,28654639,512629 20210304,28585852,510408 20210303,28520365,508665 20210302,28453529,506216 20210301,28399281,504488`; console.log(CSVToJSON(exampleCSV));</script> Output: CSV JavaScript-Methods JavaScript-Questions JSON JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Convert a string to an integer in JavaScript How to calculate the number of days between two dates in javascript? Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React File uploading in React.js Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 37915, "s": 37887, "text": "\n22 Apr, 2021" }, { "code": null, "e": 38224, "s": 37915, "text": "CSV files are a common file format used to store data in a table-like manner. They can be particularly useful when a user intends to download structured information in a way that they can easily open and read on their local machine. CSV files are ideal for this because of their portability and universality." }, { "code": null, "e": 38433, "s": 38224, "text": "In this article, we will explain how to convert JavaScript objects JSON to the CSV file format and vice-versa. This code does not use any external libraries, and thus it works on both the browser and Node.js." }, { "code": null, "e": 38679, "s": 38433, "text": "To convert from JSON to CSV, we first need to identify the headers of the CSV file. To do this, let’s get a list of keys present in each of the JavaScript objects that has been passed in. To get this list of keys, use the `Object.keys()` method." }, { "code": null, "e": 38690, "s": 38679, "text": "Javascript" }, { "code": "<script> const JSONToCSV = (objArray, keys) => { let csv = keys.join(','); objArray.forEach((row) => { let values = []; keys.forEach((key) => { values.push(row[key] || ''); }); csv += '\\n' + values.join(','); }); return csv; }; const exampleJSON = [ { \"date\": 20210307, \"positives\": 28756184, \"fatalities\": 515148 }, { \"date\": 20210306, \"positives\": 28714654, \"fatalities\": 514309 }, { \"date\": 20210305, \"positives\": 28654639, \"fatalities\": 512629 }, { \"date\": 20210304, \"positives\": 28585852, \"fatalities\": 510408 }, { \"date\": 20210303, \"positives\": 28520365, \"fatalities\": 508665 }, { \"date\": 20210302, \"positives\": 28453529, \"fatalities\": 506216 }, { \"date\": 20210301, \"positives\": 28399281, \"fatalities\": 504488 } ]; console.log(JSONToCSV(exampleJSON, ['date', 'positives', 'fatalities']));</script>", "e": 39963, "s": 38690, "text": null }, { "code": null, "e": 39995, "s": 39963, "text": "This code can be simplified to:" }, { "code": null, "e": 40006, "s": 39995, "text": "Javascript" }, { "code": "<script> const JSONToCSV = (objArray, keys) => [ keys.join(','), ...objArray.map( row => keys.map(k => row[k] || '') .join(','))].join('\\n'); const exampleJSON = [ { \"date\": 20210307, \"positives\": 28756184, \"fatalities\": 515148 }, { \"date\": 20210306, \"positives\": 28714654, \"fatalities\": 514309 }, { \"date\": 20210305, \"positives\": 28654639, \"fatalities\": 512629 }, { \"date\": 20210304, \"positives\": 28585852, \"fatalities\": 510408 }, { \"date\": 20210303, \"positives\": 28520365, \"fatalities\": 508665 }, { \"date\": 20210302, \"positives\": 28453529, \"fatalities\": 506216 }, { \"date\": 20210301, \"positives\": 28399281, \"fatalities\": 504488 } ]; console.log(JSONToCSV(exampleJSON, ['date', 'positives', 'fatalities']));</script>", "e": 41107, "s": 40006, "text": null }, { "code": null, "e": 41115, "s": 41107, "text": "Output:" }, { "code": null, "e": 41332, "s": 41115, "text": "date, positives, fatalities\n20210307, 28756184, 515148\n20210306, 28714654, 514309\n20210305, 28654639, 512629\n20210304, 28585852, 510408\n20210303, 28520365, 508665\n20210302, 28453529, 506216\n20210301, 28399281, 504488" }, { "code": null, "e": 41508, "s": 41332, "text": "To convert from CSV to JSON, first identify a list of keys for each JavaScript object by parsing the CSV headers, then add each key and value to a new object for each CSV row." }, { "code": null, "e": 41519, "s": 41508, "text": "Javascript" }, { "code": "<script> const CSVToJSON = csv => { const lines = csv.split('\\n'); const keys = lines[0].split(','); return lines.slice(1).map(line => { return line.split(',').reduce((acc, cur, i) => { const toAdd = {}; toAdd[keys[i]] = cur; return { ...acc, ...toAdd }; }, {}); }); }; const exampleCSV = ` date,positives,fatalities 20210307,28756184,515148 20210306,28714654,514309 20210305,28654639,512629 20210304,28585852,510408 20210303,28520365,508665 20210302,28453529,506216 20210301,28399281,504488`; console.log(CSVToJSON(exampleCSV));</script>", "e": 42255, "s": 41519, "text": null }, { "code": null, "e": 42263, "s": 42255, "text": "Output:" }, { "code": null, "e": 42267, "s": 42263, "text": "CSV" }, { "code": null, "e": 42286, "s": 42267, "text": "JavaScript-Methods" }, { "code": null, "e": 42307, "s": 42286, "text": "JavaScript-Questions" }, { "code": null, "e": 42312, "s": 42307, "text": "JSON" }, { "code": null, "e": 42323, "s": 42312, "text": "JavaScript" }, { "code": null, "e": 42340, "s": 42323, "text": "Web Technologies" }, { "code": null, "e": 42438, "s": 42340, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 42447, "s": 42438, "text": "Comments" }, { "code": null, "e": 42460, "s": 42447, "text": "Old Comments" }, { "code": null, "e": 42505, "s": 42460, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 42574, "s": 42505, "text": "How to calculate the number of days between two dates in javascript?" }, { "code": null, "e": 42635, "s": 42574, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 42707, "s": 42635, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 42734, "s": 42707, "text": "File uploading in React.js" }, { "code": null, "e": 42776, "s": 42734, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 42809, "s": 42776, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 42852, "s": 42809, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 42914, "s": 42852, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
4 pre-commit Plugins to Automate Code Reviewing and Formatting in Python | by Khuyen Tran | Towards Data Science
When committing your Python code to Git, you need to make sure your code: looks nice is organized conforms to the PEP 8 style guide includes docstrings However, it can be overwhelming to check all of these criteria before committing your code. Wouldn’t it be nice if you can automatically check and format your code every time you commit new code like below? That is when pre-commit comes in handy. In this article, you will learn what pre-commit is and which plugins you can add to a pre-commit pipeline. pre-commit is a framework that allows you to identify simple issues in your code before committing it. You can add different plugins to your pre-commit pipeline. Once your files are committed, they will be checked by these plugins. Unless all checks pass, no code will be committed. To install pre-commit, type: pip install pre-commit Cool! Now let’s add some useful plugins to our pre-commit pipeline. black is a code formatter in Python. To install black, type: pip install black Now to see what black can do, we’ll write a very long function like below. Since there are more than 79 characters in the first line of code, this violates PEP 8. Let’s try to format the code using black: $ black long_function.py And the code is automatically formatted like below! To add black to a pre-commit pipeline, create a file named .pre-commit-config.yaml and insert the following code to the file: flake8 is a python tool that checks the style and quality of your Python code. It checks for various issues not covered by black. To install flake8, type: pip install flake8 To see what flake8 does, let’s write code that violates some guidelines in PEP 8. Next, check the code using flake8: $ flake8 flake_example.py Aha! flake8 detects 3 PEP 8 formatting errors. We can use these errors as the guidelines to fix the code. The code looks much better now! To add flake8 to the pre-commit pipeline, insert the following code to the .pre-commit-config.yaml file: isort is a Python library that automatically sorts imported libraries alphabetically and separates them into sections and types. To install isort, type: pip install isort Let’s try to use isort to sort messy imports like below: $ isort isort_example.py Output: Cool! The imports are much more organized now. To add isort to the pre-commit pipeline, add the following code to the .pre-commit-config.yaml file: interrogate checks your codebase for missing docstrings. To install interrogate, type: pip install interrogate Sometimes, we might forget to write docstrings for classes and functions like below: Instead of manually looking at all our functions and classes for missing docstrings, we can run interrogate instead: $ interrogate -vv interrogate_example.py Output: Cool! From the terminal output, we know which files, classes, and functions don’t have docstrings. Since we know the locations of missing docstrings, adding them is easy. $ interrogate -vv interrogate_example.py The docstring for the __init__ method is missing, but it is not necessary. We can tell interrogate to ignore the __init__ method by adding -i to the argument: $ interrogate -vv -i interrogate_example.py Cool! To add interrogate to the pre-commit pipeline, insert the following code to the .pre-commit-config.yaml file: The final code in your .pre-commit-config.yaml file should look like below: To add pre-commit to git hooks, type: $ pre-commit install Output: pre-commit installed at .git/hooks/pre-commit Now we’re ready to commit the new code! $ git commit -m 'add pre-commit examples' And you should see something like below: To prevent pre-commit from checking a certain commit, add --no-verify to git commit : $ git commit -m 'add pre-commit examples' --no-verify To choose which files to include and exclude when running black, create a file named pyproject.toml and add the following code to the pyproject.toml file: To choose which errors to ignore or to edit other configurations, create a file named .flake8 and add the following code to the .flake8 file: To edit interrogate’s default configurations, insert the following code to thepyproject.toml file: Congratulations! You have just learned how to use pre-commit to automatically check and edit your code before committing it. I hope this article will make it effortless for you to review and format your code. Your coworkers will also be happy when your code follows the common standards. Feel free to play and fork the source code of this article here: github.com I like to write about basic data science concepts and play with different algorithms and data science tools. You could connect with me on LinkedIn and Twitter. Star this repo if you want to check out the codes for all of the articles I have written. Follow me on Medium to stay informed with my latest data science articles like these: towardsdatascience.com towardsdatascience.com towardsdatascience.com towardsdatascience.com Lj Miranda. (2018, June 20). Automate Python workflow using pre-commits: black and flake8. Lj Miranda. https://ljvmiranda921.github.io/notebook/2018/06/21/precommits-using-black-and-flake8/.
[ { "code": null, "e": 246, "s": 172, "text": "When committing your Python code to Git, you need to make sure your code:" }, { "code": null, "e": 257, "s": 246, "text": "looks nice" }, { "code": null, "e": 270, "s": 257, "text": "is organized" }, { "code": null, "e": 304, "s": 270, "text": "conforms to the PEP 8 style guide" }, { "code": null, "e": 324, "s": 304, "text": "includes docstrings" }, { "code": null, "e": 531, "s": 324, "text": "However, it can be overwhelming to check all of these criteria before committing your code. Wouldn’t it be nice if you can automatically check and format your code every time you commit new code like below?" }, { "code": null, "e": 678, "s": 531, "text": "That is when pre-commit comes in handy. In this article, you will learn what pre-commit is and which plugins you can add to a pre-commit pipeline." }, { "code": null, "e": 781, "s": 678, "text": "pre-commit is a framework that allows you to identify simple issues in your code before committing it." }, { "code": null, "e": 961, "s": 781, "text": "You can add different plugins to your pre-commit pipeline. Once your files are committed, they will be checked by these plugins. Unless all checks pass, no code will be committed." }, { "code": null, "e": 990, "s": 961, "text": "To install pre-commit, type:" }, { "code": null, "e": 1013, "s": 990, "text": "pip install pre-commit" }, { "code": null, "e": 1081, "s": 1013, "text": "Cool! Now let’s add some useful plugins to our pre-commit pipeline." }, { "code": null, "e": 1118, "s": 1081, "text": "black is a code formatter in Python." }, { "code": null, "e": 1142, "s": 1118, "text": "To install black, type:" }, { "code": null, "e": 1160, "s": 1142, "text": "pip install black" }, { "code": null, "e": 1323, "s": 1160, "text": "Now to see what black can do, we’ll write a very long function like below. Since there are more than 79 characters in the first line of code, this violates PEP 8." }, { "code": null, "e": 1365, "s": 1323, "text": "Let’s try to format the code using black:" }, { "code": null, "e": 1390, "s": 1365, "text": "$ black long_function.py" }, { "code": null, "e": 1442, "s": 1390, "text": "And the code is automatically formatted like below!" }, { "code": null, "e": 1568, "s": 1442, "text": "To add black to a pre-commit pipeline, create a file named .pre-commit-config.yaml and insert the following code to the file:" }, { "code": null, "e": 1698, "s": 1568, "text": "flake8 is a python tool that checks the style and quality of your Python code. It checks for various issues not covered by black." }, { "code": null, "e": 1723, "s": 1698, "text": "To install flake8, type:" }, { "code": null, "e": 1742, "s": 1723, "text": "pip install flake8" }, { "code": null, "e": 1824, "s": 1742, "text": "To see what flake8 does, let’s write code that violates some guidelines in PEP 8." }, { "code": null, "e": 1859, "s": 1824, "text": "Next, check the code using flake8:" }, { "code": null, "e": 1885, "s": 1859, "text": "$ flake8 flake_example.py" }, { "code": null, "e": 1991, "s": 1885, "text": "Aha! flake8 detects 3 PEP 8 formatting errors. We can use these errors as the guidelines to fix the code." }, { "code": null, "e": 2023, "s": 1991, "text": "The code looks much better now!" }, { "code": null, "e": 2128, "s": 2023, "text": "To add flake8 to the pre-commit pipeline, insert the following code to the .pre-commit-config.yaml file:" }, { "code": null, "e": 2257, "s": 2128, "text": "isort is a Python library that automatically sorts imported libraries alphabetically and separates them into sections and types." }, { "code": null, "e": 2281, "s": 2257, "text": "To install isort, type:" }, { "code": null, "e": 2299, "s": 2281, "text": "pip install isort" }, { "code": null, "e": 2356, "s": 2299, "text": "Let’s try to use isort to sort messy imports like below:" }, { "code": null, "e": 2381, "s": 2356, "text": "$ isort isort_example.py" }, { "code": null, "e": 2389, "s": 2381, "text": "Output:" }, { "code": null, "e": 2436, "s": 2389, "text": "Cool! The imports are much more organized now." }, { "code": null, "e": 2537, "s": 2436, "text": "To add isort to the pre-commit pipeline, add the following code to the .pre-commit-config.yaml file:" }, { "code": null, "e": 2594, "s": 2537, "text": "interrogate checks your codebase for missing docstrings." }, { "code": null, "e": 2624, "s": 2594, "text": "To install interrogate, type:" }, { "code": null, "e": 2648, "s": 2624, "text": "pip install interrogate" }, { "code": null, "e": 2733, "s": 2648, "text": "Sometimes, we might forget to write docstrings for classes and functions like below:" }, { "code": null, "e": 2850, "s": 2733, "text": "Instead of manually looking at all our functions and classes for missing docstrings, we can run interrogate instead:" }, { "code": null, "e": 2891, "s": 2850, "text": "$ interrogate -vv interrogate_example.py" }, { "code": null, "e": 2899, "s": 2891, "text": "Output:" }, { "code": null, "e": 3070, "s": 2899, "text": "Cool! From the terminal output, we know which files, classes, and functions don’t have docstrings. Since we know the locations of missing docstrings, adding them is easy." }, { "code": null, "e": 3111, "s": 3070, "text": "$ interrogate -vv interrogate_example.py" }, { "code": null, "e": 3270, "s": 3111, "text": "The docstring for the __init__ method is missing, but it is not necessary. We can tell interrogate to ignore the __init__ method by adding -i to the argument:" }, { "code": null, "e": 3314, "s": 3270, "text": "$ interrogate -vv -i interrogate_example.py" }, { "code": null, "e": 3430, "s": 3314, "text": "Cool! To add interrogate to the pre-commit pipeline, insert the following code to the .pre-commit-config.yaml file:" }, { "code": null, "e": 3506, "s": 3430, "text": "The final code in your .pre-commit-config.yaml file should look like below:" }, { "code": null, "e": 3544, "s": 3506, "text": "To add pre-commit to git hooks, type:" }, { "code": null, "e": 3565, "s": 3544, "text": "$ pre-commit install" }, { "code": null, "e": 3573, "s": 3565, "text": "Output:" }, { "code": null, "e": 3619, "s": 3573, "text": "pre-commit installed at .git/hooks/pre-commit" }, { "code": null, "e": 3659, "s": 3619, "text": "Now we’re ready to commit the new code!" }, { "code": null, "e": 3701, "s": 3659, "text": "$ git commit -m 'add pre-commit examples'" }, { "code": null, "e": 3742, "s": 3701, "text": "And you should see something like below:" }, { "code": null, "e": 3828, "s": 3742, "text": "To prevent pre-commit from checking a certain commit, add --no-verify to git commit :" }, { "code": null, "e": 3882, "s": 3828, "text": "$ git commit -m 'add pre-commit examples' --no-verify" }, { "code": null, "e": 4037, "s": 3882, "text": "To choose which files to include and exclude when running black, create a file named pyproject.toml and add the following code to the pyproject.toml file:" }, { "code": null, "e": 4179, "s": 4037, "text": "To choose which errors to ignore or to edit other configurations, create a file named .flake8 and add the following code to the .flake8 file:" }, { "code": null, "e": 4278, "s": 4179, "text": "To edit interrogate’s default configurations, insert the following code to thepyproject.toml file:" }, { "code": null, "e": 4487, "s": 4278, "text": "Congratulations! You have just learned how to use pre-commit to automatically check and edit your code before committing it. I hope this article will make it effortless for you to review and format your code." }, { "code": null, "e": 4566, "s": 4487, "text": "Your coworkers will also be happy when your code follows the common standards." }, { "code": null, "e": 4631, "s": 4566, "text": "Feel free to play and fork the source code of this article here:" }, { "code": null, "e": 4642, "s": 4631, "text": "github.com" }, { "code": null, "e": 4802, "s": 4642, "text": "I like to write about basic data science concepts and play with different algorithms and data science tools. You could connect with me on LinkedIn and Twitter." }, { "code": null, "e": 4978, "s": 4802, "text": "Star this repo if you want to check out the codes for all of the articles I have written. Follow me on Medium to stay informed with my latest data science articles like these:" }, { "code": null, "e": 5001, "s": 4978, "text": "towardsdatascience.com" }, { "code": null, "e": 5024, "s": 5001, "text": "towardsdatascience.com" }, { "code": null, "e": 5047, "s": 5024, "text": "towardsdatascience.com" }, { "code": null, "e": 5070, "s": 5047, "text": "towardsdatascience.com" } ]
Linux Admin - more and less Command
Both more and less commands allow pagination of large text files. When perusing large files, it is not always possible to use grep unless we know an exact string to search. So we would want to use either more or less. Typically, less is the preferred choice, as it allows both forward and backward perusal of paginated text. However, less may not be available on default installations of older Linux distributions and even some modern Unix operating systems. [root@centosLocal Documents]# grep "192.168" ./pfirewall.log | more 2016-01-07 15:36:34 DROP UDP 192.168.0.1 255.255.255.255 68 67 328 - - - - - - RECEIVE 2016-01-07 15:36:38 DROP UDP 192.168.0.21 255.255.255.255 68 67 328 - - - - -- - RECEIVE 2016-01-07 15:36:45 DROP ICMP 192.168.0.24 224.0.0.1 - - -- - - - - -- - - - - RECEIVE 2016-01-07 15:37:07 DROP UDP 192.168.0.21 255.255.255.255 68 67 328 - - - - - - RECEIVE 2016-01-07 15:37:52 DROP UDP 192.168.0.78 255.255.255.255 68 67 328 - - - - - - RECEIVE 2016-01-07 15:37:52 ALLOW UDP 192.168.0.78 255.255.255.255 67 68 0 - - - - -- - RECEIVE 2016-01-07 15:37:53 ALLOW UDP 192.168.0.78 224.0.0.252 51571 5355 0 - - - - - - RECEIVE Usually less is preferred, because less really offers more than more. 2016-01-07 15:43:53 DROP UDP 192.168.1.73 255.255.255.255 68 67 328 - - - - - - RECEIVE 2016-01-07 15:44:17 ALLOW UDP 192.168.1.18 224.0.0.252 54526 5355 0 - - - - - - RECEIVE 2016-01-07 15:44:23 DROP UDP 192.168.1.57 255.255.255.255 68 67 328 - - - - - - RECEIVE 2016-01-07 15:44:33 DROP UDP 192.168.1.88 255.255.255.255 68 67 328 - - - - - - RECEIVE 2016-01-07 15:44:33 ALLOW UDP 192.168.1.4 255.255.255.255 67 68 0 - - - - - - - RECEIVE 2016-01-07 15:44:41 DROP UDP 192.168.1.126 255.255.255.255 68 67 328 - - - - - - RECEIVE 2016-01-07 15:44:43 DROP UDP 192.168.1.112 255.255.255.255 68 67 328 - - - - - - RECEIVE 2016-01-07 15:44:56 DROP ICMP 192.168.1.240 224.0.0.1 - - 36 - - - - 9 0 - RECEIVE 2016-01-07 15:45:57 ALLOW UDP 192.168.1.47 192.168.1.255 138 138 0 - - - - - - SEND 2016-01-07 15:49:13 DROP ICMP 192.168.1.241 224.0.0.1 - - 36 - - - - 9 0 - RECEIVE 2016-01-07 15:49:38 DROP UDP 192.168.1.68 255.255.255.255 68 67 328 - - - - - - RECEIVE 2016-01-07 15:49:38 ALLOW UDP 192.168.1.4 255.255.255.255 67 68 0 - - - - - - RECEIVE 2016-01-07 15:49:39 DROP UDP 192.168.1.93 255.255.255.255 68 67 328 - - - - - RECEIVE : As shown above, when invoked less opens into a new buffer separate from the shell prompt. When trying less, it sometimes may give an error as follows βˆ’ bash: less: command not found... Either use more or install less from the source of the package manager. But less should be included on all modern Linux Distributions and even ported to Unix platforms. Some will even symlink more to less. 57 Lectures 7.5 hours Mamta Tripathi 25 Lectures 3 hours Lets Kode It 14 Lectures 1.5 hours Abhilash Nelson 58 Lectures 2.5 hours Frahaan Hussain 129 Lectures 23 hours Eduonix Learning Solutions 23 Lectures 5 hours Pranjal Srivastava, Harshit Srivastava Print Add Notes Bookmark this page
[ { "code": null, "e": 2475, "s": 2257, "text": "Both more and less commands allow pagination of large text files. When perusing large files, it is not always possible to use grep unless we know an exact string to search. So we would want to use either more or less." }, { "code": null, "e": 2716, "s": 2475, "text": "Typically, less is the preferred choice, as it allows both forward and backward perusal of paginated text. However, less may not be available on default installations of older Linux distributions and even some modern Unix operating systems." }, { "code": null, "e": 3415, "s": 2716, "text": "[root@centosLocal Documents]# grep \"192.168\" ./pfirewall.log | more \n2016-01-07 15:36:34 DROP UDP 192.168.0.1 255.255.255.255 68 67 328 - - - - - - RECEIVE \n2016-01-07 15:36:38 DROP UDP 192.168.0.21 255.255.255.255 68 67 328 - - - - -- - RECEIVE \n2016-01-07 15:36:45 DROP ICMP 192.168.0.24 224.0.0.1 - - -- - - - - -- - - - - RECEIVE \n2016-01-07 15:37:07 DROP UDP 192.168.0.21 255.255.255.255 68 67 328 - - - - - - RECEIVE \n2016-01-07 15:37:52 DROP UDP 192.168.0.78 255.255.255.255 68 67 328 - - - - - - RECEIVE \n2016-01-07 15:37:52 ALLOW UDP 192.168.0.78 255.255.255.255 67 68 0 - - - - -- - RECEIVE \n2016-01-07 15:37:53 ALLOW UDP 192.168.0.78 224.0.0.252 51571 5355 0 - - - - - - RECEIVE\n" }, { "code": null, "e": 3485, "s": 3415, "text": "Usually less is preferred, because less really offers more than more." }, { "code": null, "e": 4658, "s": 3485, "text": "2016-01-07 15:43:53 DROP UDP 192.168.1.73 255.255.255.255 68 67 328 - - - - - - RECEIVE \n2016-01-07 15:44:17 ALLOW UDP 192.168.1.18 224.0.0.252 54526 5355 0 - - - - - - RECEIVE \n2016-01-07 15:44:23 DROP UDP 192.168.1.57 255.255.255.255 68 67 328 - - - - - - RECEIVE \n2016-01-07 15:44:33 DROP UDP 192.168.1.88 255.255.255.255 68 67 328 - - - - - - RECEIVE \n2016-01-07 15:44:33 ALLOW UDP 192.168.1.4 255.255.255.255 67 68 0 - - - - - - - RECEIVE \n2016-01-07 15:44:41 DROP UDP 192.168.1.126 255.255.255.255 68 67 328 - - - - - - RECEIVE \n2016-01-07 15:44:43 DROP UDP 192.168.1.112 255.255.255.255 68 67 328 - - - - - - RECEIVE \n2016-01-07 15:44:56 DROP ICMP 192.168.1.240 224.0.0.1 - - 36 - - - - 9 0 - RECEIVE \n2016-01-07 15:45:57 ALLOW UDP 192.168.1.47 192.168.1.255 138 138 0 - - - - - - SEND \n2016-01-07 15:49:13 DROP ICMP 192.168.1.241 224.0.0.1 - - 36 - - - - 9 0 - RECEIVE \n2016-01-07 15:49:38 DROP UDP 192.168.1.68 255.255.255.255 68 67 328 - - - - - - RECEIVE \n2016-01-07 15:49:38 ALLOW UDP 192.168.1.4 255.255.255.255 67 68 0 - - - - - - RECEIVE \n2016-01-07 15:49:39 DROP UDP 192.168.1.93 255.255.255.255 68 67 328 - - - - - RECEIVE \n:\n" }, { "code": null, "e": 4810, "s": 4658, "text": "As shown above, when invoked less opens into a new buffer separate from the shell prompt. When trying less, it sometimes may give an error as follows βˆ’" }, { "code": null, "e": 4844, "s": 4810, "text": "bash: less: command not found...\n" }, { "code": null, "e": 5050, "s": 4844, "text": "Either use more or install less from the source of the package manager. But less should be included on all modern Linux Distributions and even ported to Unix platforms. Some will even symlink more to less." }, { "code": null, "e": 5085, "s": 5050, "text": "\n 57 Lectures \n 7.5 hours \n" }, { "code": null, "e": 5101, "s": 5085, "text": " Mamta Tripathi" }, { "code": null, "e": 5134, "s": 5101, "text": "\n 25 Lectures \n 3 hours \n" }, { "code": null, "e": 5148, "s": 5134, "text": " Lets Kode It" }, { "code": null, "e": 5183, "s": 5148, "text": "\n 14 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5200, "s": 5183, "text": " Abhilash Nelson" }, { "code": null, "e": 5235, "s": 5200, "text": "\n 58 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5252, "s": 5235, "text": " Frahaan Hussain" }, { "code": null, "e": 5287, "s": 5252, "text": "\n 129 Lectures \n 23 hours \n" }, { "code": null, "e": 5315, "s": 5287, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 5348, "s": 5315, "text": "\n 23 Lectures \n 5 hours \n" }, { "code": null, "e": 5388, "s": 5348, "text": " Pranjal Srivastava, Harshit Srivastava" }, { "code": null, "e": 5395, "s": 5388, "text": " Print" }, { "code": null, "e": 5406, "s": 5395, "text": " Add Notes" } ]
How to Install Pandas-Profiling on Windows? - GeeksforGeeks
09 Sep, 2021 In this article, we will look into ways of installing the Pandas Profiling package in Python. Python PIP or Conda (Depending upon preference) Pip users can just open up the command prompt and use the below command to install the Pandas profiling package in python: pip install pandas-profiling The following message will be shown once the installation is completed: Conda users can open up the Anaconda Power Shell Prompt and use the below command to install the pandas profiling package in python: conda install -c anaconda pandas-profiling The following message will be shown once the installation is completed: You can use the below code to verify your installation. Make sure to add a sample .csv file having some data to check the installation and replace the Geeks.csv file in the below code. Python3 #import the packagesimport pandas as pdimport pandas_profiling # read the filedf = pd.read_csv('Geeks.csv') # run the profile reportprofile = df.profile_report(title='Pandas Profiling Report') Output: Blogathon-2021 how-to-install Picked Python pandas-basics Blogathon How To Installation Guide Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install Tkinter in Windows? How to Import JSON Data into SQL Server? How to configure ESLint for React Projects ? How to pass data into table from a form using React Components SQL Query to Create Table With a Primary Key How to Install PIP on Windows ? How to Find the Wi-Fi Password Using CMD in Windows? How to Align Text in HTML? Java Tutorial How to Install FFmpeg on Windows?
[ { "code": null, "e": 24732, "s": 24704, "text": "\n09 Sep, 2021" }, { "code": null, "e": 24826, "s": 24732, "text": "In this article, we will look into ways of installing the Pandas Profiling package in Python." }, { "code": null, "e": 24833, "s": 24826, "text": "Python" }, { "code": null, "e": 24874, "s": 24833, "text": "PIP or Conda (Depending upon preference)" }, { "code": null, "e": 24997, "s": 24874, "text": "Pip users can just open up the command prompt and use the below command to install the Pandas profiling package in python:" }, { "code": null, "e": 25026, "s": 24997, "text": "pip install pandas-profiling" }, { "code": null, "e": 25098, "s": 25026, "text": "The following message will be shown once the installation is completed:" }, { "code": null, "e": 25231, "s": 25098, "text": "Conda users can open up the Anaconda Power Shell Prompt and use the below command to install the pandas profiling package in python:" }, { "code": null, "e": 25275, "s": 25231, "text": "conda install -c anaconda pandas-profiling " }, { "code": null, "e": 25347, "s": 25275, "text": "The following message will be shown once the installation is completed:" }, { "code": null, "e": 25532, "s": 25347, "text": "You can use the below code to verify your installation. Make sure to add a sample .csv file having some data to check the installation and replace the Geeks.csv file in the below code." }, { "code": null, "e": 25540, "s": 25532, "text": "Python3" }, { "code": "#import the packagesimport pandas as pdimport pandas_profiling # read the filedf = pd.read_csv('Geeks.csv') # run the profile reportprofile = df.profile_report(title='Pandas Profiling Report')", "e": 25735, "s": 25540, "text": null }, { "code": null, "e": 25743, "s": 25735, "text": "Output:" }, { "code": null, "e": 25758, "s": 25743, "text": "Blogathon-2021" }, { "code": null, "e": 25773, "s": 25758, "text": "how-to-install" }, { "code": null, "e": 25780, "s": 25773, "text": "Picked" }, { "code": null, "e": 25801, "s": 25780, "text": "Python pandas-basics" }, { "code": null, "e": 25811, "s": 25801, "text": "Blogathon" }, { "code": null, "e": 25818, "s": 25811, "text": "How To" }, { "code": null, "e": 25837, "s": 25818, "text": "Installation Guide" }, { "code": null, "e": 25844, "s": 25837, "text": "Python" }, { "code": null, "e": 25942, "s": 25844, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25951, "s": 25942, "text": "Comments" }, { "code": null, "e": 25964, "s": 25951, "text": "Old Comments" }, { "code": null, "e": 25999, "s": 25964, "text": "How to Install Tkinter in Windows?" }, { "code": null, "e": 26040, "s": 25999, "text": "How to Import JSON Data into SQL Server?" }, { "code": null, "e": 26085, "s": 26040, "text": "How to configure ESLint for React Projects ?" }, { "code": null, "e": 26148, "s": 26085, "text": "How to pass data into table from a form using React Components" }, { "code": null, "e": 26193, "s": 26148, "text": "SQL Query to Create Table With a Primary Key" }, { "code": null, "e": 26225, "s": 26193, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26278, "s": 26225, "text": "How to Find the Wi-Fi Password Using CMD in Windows?" }, { "code": null, "e": 26305, "s": 26278, "text": "How to Align Text in HTML?" }, { "code": null, "e": 26319, "s": 26305, "text": "Java Tutorial" } ]
How to Calculate Poker Probabilities in Python | by Thársis Souza, PhD | Towards Data Science
In this article, we show how to represent basic poker elements in Python, e.g., Hands and Combos, and how to calculate poker odds, i.e., likelihood of win/tie/lose in No-Limit Texas Hold’em. We provide a practical analysis based on a real story in a Night at the Venetian in Las Vegas. We will use the package poker to represent hands, combos and ranges. I have extended the poker odds calculator from Kevin Tseng, so it is able to calculate poker probabilities based on ranges (set of possible hands) in addition to individual hands. The final code is available in my repo. I was dealt with King of Spades and Jack of Clubs (K β™ J ♣). I will use the Class Combo from poker.hand to construct my hand. I do not remember exactly what happened pre-flop and what my position was. However, I do remember there was a raise pre-flop and only two players were left post-flop: myself and the villain. We are now heads-up. The flop comes Queen of Clubs, Ten of Hearts and Nine of Spades. Yes, I flopped a Straight! Let’s calculate my odds post-flop assuming no prior knowledge about the villain's cards, i.e., we will compute how likely my hand is to win against a random pair of hole cards given the flop. The function calculate_odds_villan from holdem_calc calculates the probability that a certain Texas Hold’em hand will win. This probability is approximated by running a Monte Carlo method or calculated exactly by simulating the set of all possible hands. Calculating exact odds post-flop is fast so we won’t need Monte Carlo approximations here. Here’s our odds: {'tie': 0.04138424018164999, 'win': 0.9308440557284221, 'lose': 0.027771704089927955} At this point I’m feeling pretty good. Against a random hand, I only have a 2.77% chance to lose and over 93% chance to win. However, that’s optimistic. Given that there was a raise pre-flop and only myself and the villain were left post-flop, it’s likely the villain has something, right? We call this likely set of hands a range. This is an inference we make based on several factors including villain's behavior, position, bet size etc. This inference leads to a set of combos of hands we assume the villain might have. At this point, I was thinking the villain had: A pair of sevens or better Ace / Ten or better King / Jack or better We can represent this range using the Class Range as below: This brings our villain's hand combos down to 144 combinations from a total of 51*52–1 = 2651 possible hands. Let’s calculate my odds now assuming ranges for the villain. {'tie': 0.11423324150596878, 'win': 0.8030711151923272, 'lose': 0.08269564330170391} Given the assumed ranges, my winning odds dropped from a 93% to 80%. However, I still have a very low probability of losing of 8.2%. At this point, I’m pretty comfortable. But should I bet? I definitively want the villain to continue playing and not fold yet. But how likely is he of having a good hand post-flop? Let’s see what are the odds of him making a hand if we continued playing until the end. High Card: 0.06978879706152433 Pair: 0.3662891541679421 Two Pair: 0.23085399449035812 Three of a Kind: 0.09733700642791548 Straight: 0.18498112437506367 Flush: 0.0040608101214161816 Full House: 0.04205693296602388 Four of a Kind: 0.004560759106213652 Straight Flush: 2.0406081012141617e-05 Royal Flush: 5.101520253035404e-05 If we continue playing until the river, the villain has a good chance of making a Pair (36%) or even Two Pair (23%). He has a nice probability of hitting a Straight (18%) or even making a Set (9.7%) or a Full House (4%). As the villain has a good chance of having a reasonable hand, I then decide to bet high, about 2/3 of the pot. The villain tanks and finally calls. The turn comes and it’s a deuce of diamonds (2 ♦). Basically, it’s a blank card, i.e., it does not change much our game. {'tie': 0.0233201581027668, 'win': 0.9677206851119895, 'lose': 0.008959156785243741} Assuming random cards for the villain, I am now with 96% odds of winning. However, considering my assumed ranges for the villain, my winning odds are now 86% up from 80% in the flop. I bet high again, the villain calls and here comes the river. {'tie': 0.10123966942148759, 'win': 0.8615702479338843, 'lose': 0.0371900826446281} King of Clubs is the river (K ♣). A King in the river makes a Straight much more likely for the villain to hold. So this is bad news for me. {'tie': 0.11818181818181818, 'win': 0.8696969696969697, 'lose': 0.012121212121212121} Now, my winning odds dropped from 96% to about 87% against random cards. But I’m still losing only with a very low probability of 1.2%. OK, the bad river is not that bad, right? Well, there is one additional factor. The villain called my big bets both in the flop and in the river. He might have something better than I thought... right? I should then adjust my assumed ranges. Now, I’m thinking the villain no longer has 77’s or 88’s combos, otherwise he would not go that far given my high bets. I am thinking he might have a pair of 99’s or better to make sets with 99’s, 10’s or QQ’s. He might also have JJ’s for a mid-pair and straight-draw. Or KK’s and AA’s which would be top pairs until the turn. I decided to keep the Ace Ten or better and the King Jack or better combos because of something called implied odds. Implied odds is an estimation on how much money you can win from the bet if you hit one of your outs. So the villain might be sticky waiting to hit a draw (which he might have just hit now??). Hence, I define my villain's updated range as follows: Now the villain's combos are 132 down from 144. Let’s calculate the updated odds. {'tie': 0.12, 'win': 0.72, 'lose': 0.16} I now have a 72% chance to win (down from 86%) and my chances or losing have increased from 3.7% to 16% compared to our range analysis during the turn. I decide to check and the villain goes all-in, betting roughly 70% of the pot. A basic and standard river strategy tells you the following: Use your absolute weakest holdings as river bluffsUse your strongest holdings as value-betsCheck hands with mid-strength showdown-value in the hope of reaching showdown Use your absolute weakest holdings as river bluffs Use your strongest holdings as value-bets Check hands with mid-strength showdown-value in the hope of reaching showdown High Card: 0.0 Pair: 0.5066666666666667 Two Pair: 0.08 Three of a Kind: 0.13333333333333333 Straight: 0.28 Flush: 0.0 Full House: 0.0 Four of a Kind: 0.0 Straight Flush: 0.0 Royal Flush: 0.0 From the odds histogram, we can group the villain's possible hands in 3 types: Bluff: He is holding {High Card, Pair} with 60.66% chanceMid-strength hand: He is holding {Two Pair} with 0.8% chanceValue-bet (strongest holdings): He is holding {Three of a Kind, Straight} with 41.33% chance Bluff: He is holding {High Card, Pair} with 60.66% chance Mid-strength hand: He is holding {Two Pair} with 0.8% chance Value-bet (strongest holdings): He is holding {Three of a Kind, Straight} with 41.33% chance The villain's all-in makes sense, his mid-strength hand probability is too low to check. So here I’m thinking he is either bluffing, for instance due to a missed draw, or he has the nuts, and this is a value bet. This basic strategy of either bluffing if you have your weakest holdings or value-betting if you have a strong holding is sometimes called a polarized bet. That’s what the villain is doing here. Looking back at the probabilities per type (bluff, mid-strength hand, value-bet), I basically should win at least 60.66% of the time and this is a conservative measure as the villain might be value betting a three of a kind. But should I call? Here comes another concept called pot odds. Pot odds refers to the price of calling a bet relative to the size of the pot. In summary, I should call if my probability of winning the pot is higher than the ratio between the price to call and the size of the pot after my call. Let’s do some math: Chance to win β‰₯ 60.66% (conservatively)Price to call = 0.7 * pot sizePot size post-call = (1 + 0.7 + 0.7) * pot sizePot odds = Price to call / Pot size post-call = 29% Chance to win β‰₯ 60.66% (conservatively) Price to call = 0.7 * pot size Pot size post-call = (1 + 0.7 + 0.7) * pot size Pot odds = Price to call / Pot size post-call = 29% My chance to win is at least double the pot odds. Hence, I proceed to call. The result? The villain turns his cards. The table once quiet makes a collective β€˜wow’ while staring at the Ace Jack on the table making a Straight over Straight situation and leaving the villain with all of my chips. In this article, I showed how to represent basic poker elements (e.g. Hands and Combos) and how to calculate poker odds assuming random hands as well as ranges in Python while telling a true history of a night at the Venetian. We showed how exciting (and probabilistically interesting) poker can be. Below, I show how my winning odds changed from flop to turn and then river assuming random cards for the villain as well as inferring ranges. We observe that I was a major favorite of winning this heads-up hand even though the final result was not in my favor. That’s why poker players say you should focus on the decisions you make not on the results you have. Of course, all the analysis in this article assumed some ranges and basic poker strategies that formed my mental model at the time of playing and here implemented in Python. I’m no Poker Pro and there are many ways to go about this hand. I believe I have made several mistakes, for instance, underestimating the chances of the villain holding AJ given the pre-flop raise. I would be very curious how others would have analyzed this hand using the Python framework utilized here. Feel free to go ahead and fork the repo.
[ { "code": null, "e": 362, "s": 171, "text": "In this article, we show how to represent basic poker elements in Python, e.g., Hands and Combos, and how to calculate poker odds, i.e., likelihood of win/tie/lose in No-Limit Texas Hold’em." }, { "code": null, "e": 457, "s": 362, "text": "We provide a practical analysis based on a real story in a Night at the Venetian in Las Vegas." }, { "code": null, "e": 746, "s": 457, "text": "We will use the package poker to represent hands, combos and ranges. I have extended the poker odds calculator from Kevin Tseng, so it is able to calculate poker probabilities based on ranges (set of possible hands) in addition to individual hands. The final code is available in my repo." }, { "code": null, "e": 871, "s": 746, "text": "I was dealt with King of Spades and Jack of Clubs (K β™ J ♣). I will use the Class Combo from poker.hand to construct my hand." }, { "code": null, "e": 1062, "s": 871, "text": "I do not remember exactly what happened pre-flop and what my position was. However, I do remember there was a raise pre-flop and only two players were left post-flop: myself and the villain." }, { "code": null, "e": 1175, "s": 1062, "text": "We are now heads-up. The flop comes Queen of Clubs, Ten of Hearts and Nine of Spades. Yes, I flopped a Straight!" }, { "code": null, "e": 1367, "s": 1175, "text": "Let’s calculate my odds post-flop assuming no prior knowledge about the villain's cards, i.e., we will compute how likely my hand is to win against a random pair of hole cards given the flop." }, { "code": null, "e": 1730, "s": 1367, "text": "The function calculate_odds_villan from holdem_calc calculates the probability that a certain Texas Hold’em hand will win. This probability is approximated by running a Monte Carlo method or calculated exactly by simulating the set of all possible hands. Calculating exact odds post-flop is fast so we won’t need Monte Carlo approximations here. Here’s our odds:" }, { "code": null, "e": 1816, "s": 1730, "text": "{'tie': 0.04138424018164999, 'win': 0.9308440557284221, 'lose': 0.027771704089927955}" }, { "code": null, "e": 1969, "s": 1816, "text": "At this point I’m feeling pretty good. Against a random hand, I only have a 2.77% chance to lose and over 93% chance to win. However, that’s optimistic." }, { "code": null, "e": 2386, "s": 1969, "text": "Given that there was a raise pre-flop and only myself and the villain were left post-flop, it’s likely the villain has something, right? We call this likely set of hands a range. This is an inference we make based on several factors including villain's behavior, position, bet size etc. This inference leads to a set of combos of hands we assume the villain might have. At this point, I was thinking the villain had:" }, { "code": null, "e": 2413, "s": 2386, "text": "A pair of sevens or better" }, { "code": null, "e": 2433, "s": 2413, "text": "Ace / Ten or better" }, { "code": null, "e": 2455, "s": 2433, "text": "King / Jack or better" }, { "code": null, "e": 2515, "s": 2455, "text": "We can represent this range using the Class Range as below:" }, { "code": null, "e": 2686, "s": 2515, "text": "This brings our villain's hand combos down to 144 combinations from a total of 51*52–1 = 2651 possible hands. Let’s calculate my odds now assuming ranges for the villain." }, { "code": null, "e": 2771, "s": 2686, "text": "{'tie': 0.11423324150596878, 'win': 0.8030711151923272, 'lose': 0.08269564330170391}" }, { "code": null, "e": 3173, "s": 2771, "text": "Given the assumed ranges, my winning odds dropped from a 93% to 80%. However, I still have a very low probability of losing of 8.2%. At this point, I’m pretty comfortable. But should I bet? I definitively want the villain to continue playing and not fold yet. But how likely is he of having a good hand post-flop? Let’s see what are the odds of him making a hand if we continued playing until the end." }, { "code": null, "e": 3499, "s": 3173, "text": "High Card: 0.06978879706152433 Pair: 0.3662891541679421 Two Pair: 0.23085399449035812 Three of a Kind: 0.09733700642791548 Straight: 0.18498112437506367 Flush: 0.0040608101214161816 Full House: 0.04205693296602388 Four of a Kind: 0.004560759106213652 Straight Flush: 2.0406081012141617e-05 Royal Flush: 5.101520253035404e-05 " }, { "code": null, "e": 3868, "s": 3499, "text": "If we continue playing until the river, the villain has a good chance of making a Pair (36%) or even Two Pair (23%). He has a nice probability of hitting a Straight (18%) or even making a Set (9.7%) or a Full House (4%). As the villain has a good chance of having a reasonable hand, I then decide to bet high, about 2/3 of the pot. The villain tanks and finally calls." }, { "code": null, "e": 3989, "s": 3868, "text": "The turn comes and it’s a deuce of diamonds (2 ♦). Basically, it’s a blank card, i.e., it does not change much our game." }, { "code": null, "e": 4074, "s": 3989, "text": "{'tie': 0.0233201581027668, 'win': 0.9677206851119895, 'lose': 0.008959156785243741}" }, { "code": null, "e": 4148, "s": 4074, "text": "Assuming random cards for the villain, I am now with 96% odds of winning." }, { "code": null, "e": 4319, "s": 4148, "text": "However, considering my assumed ranges for the villain, my winning odds are now 86% up from 80% in the flop. I bet high again, the villain calls and here comes the river." }, { "code": null, "e": 4403, "s": 4319, "text": "{'tie': 0.10123966942148759, 'win': 0.8615702479338843, 'lose': 0.0371900826446281}" }, { "code": null, "e": 4544, "s": 4403, "text": "King of Clubs is the river (K ♣). A King in the river makes a Straight much more likely for the villain to hold. So this is bad news for me." }, { "code": null, "e": 4630, "s": 4544, "text": "{'tie': 0.11818181818181818, 'win': 0.8696969696969697, 'lose': 0.012121212121212121}" }, { "code": null, "e": 4808, "s": 4630, "text": "Now, my winning odds dropped from 96% to about 87% against random cards. But I’m still losing only with a very low probability of 1.2%. OK, the bad river is not that bad, right?" }, { "code": null, "e": 5008, "s": 4808, "text": "Well, there is one additional factor. The villain called my big bets both in the flop and in the river. He might have something better than I thought... right? I should then adjust my assumed ranges." }, { "code": null, "e": 5700, "s": 5008, "text": "Now, I’m thinking the villain no longer has 77’s or 88’s combos, otherwise he would not go that far given my high bets. I am thinking he might have a pair of 99’s or better to make sets with 99’s, 10’s or QQ’s. He might also have JJ’s for a mid-pair and straight-draw. Or KK’s and AA’s which would be top pairs until the turn. I decided to keep the Ace Ten or better and the King Jack or better combos because of something called implied odds. Implied odds is an estimation on how much money you can win from the bet if you hit one of your outs. So the villain might be sticky waiting to hit a draw (which he might have just hit now??). Hence, I define my villain's updated range as follows:" }, { "code": null, "e": 5782, "s": 5700, "text": "Now the villain's combos are 132 down from 144. Let’s calculate the updated odds." }, { "code": null, "e": 5823, "s": 5782, "text": "{'tie': 0.12, 'win': 0.72, 'lose': 0.16}" }, { "code": null, "e": 6054, "s": 5823, "text": "I now have a 72% chance to win (down from 86%) and my chances or losing have increased from 3.7% to 16% compared to our range analysis during the turn. I decide to check and the villain goes all-in, betting roughly 70% of the pot." }, { "code": null, "e": 6115, "s": 6054, "text": "A basic and standard river strategy tells you the following:" }, { "code": null, "e": 6284, "s": 6115, "text": "Use your absolute weakest holdings as river bluffsUse your strongest holdings as value-betsCheck hands with mid-strength showdown-value in the hope of reaching showdown" }, { "code": null, "e": 6335, "s": 6284, "text": "Use your absolute weakest holdings as river bluffs" }, { "code": null, "e": 6377, "s": 6335, "text": "Use your strongest holdings as value-bets" }, { "code": null, "e": 6455, "s": 6377, "text": "Check hands with mid-strength showdown-value in the hope of reaching showdown" }, { "code": null, "e": 6646, "s": 6455, "text": "High Card: 0.0 Pair: 0.5066666666666667 Two Pair: 0.08 Three of a Kind: 0.13333333333333333 Straight: 0.28 Flush: 0.0 Full House: 0.0 Four of a Kind: 0.0 Straight Flush: 0.0 Royal Flush: 0.0" }, { "code": null, "e": 6725, "s": 6646, "text": "From the odds histogram, we can group the villain's possible hands in 3 types:" }, { "code": null, "e": 6935, "s": 6725, "text": "Bluff: He is holding {High Card, Pair} with 60.66% chanceMid-strength hand: He is holding {Two Pair} with 0.8% chanceValue-bet (strongest holdings): He is holding {Three of a Kind, Straight} with 41.33% chance" }, { "code": null, "e": 6993, "s": 6935, "text": "Bluff: He is holding {High Card, Pair} with 60.66% chance" }, { "code": null, "e": 7054, "s": 6993, "text": "Mid-strength hand: He is holding {Two Pair} with 0.8% chance" }, { "code": null, "e": 7147, "s": 7054, "text": "Value-bet (strongest holdings): He is holding {Three of a Kind, Straight} with 41.33% chance" }, { "code": null, "e": 7555, "s": 7147, "text": "The villain's all-in makes sense, his mid-strength hand probability is too low to check. So here I’m thinking he is either bluffing, for instance due to a missed draw, or he has the nuts, and this is a value bet. This basic strategy of either bluffing if you have your weakest holdings or value-betting if you have a strong holding is sometimes called a polarized bet. That’s what the villain is doing here." }, { "code": null, "e": 7799, "s": 7555, "text": "Looking back at the probabilities per type (bluff, mid-strength hand, value-bet), I basically should win at least 60.66% of the time and this is a conservative measure as the villain might be value betting a three of a kind. But should I call?" }, { "code": null, "e": 8095, "s": 7799, "text": "Here comes another concept called pot odds. Pot odds refers to the price of calling a bet relative to the size of the pot. In summary, I should call if my probability of winning the pot is higher than the ratio between the price to call and the size of the pot after my call. Let’s do some math:" }, { "code": null, "e": 8263, "s": 8095, "text": "Chance to win β‰₯ 60.66% (conservatively)Price to call = 0.7 * pot sizePot size post-call = (1 + 0.7 + 0.7) * pot sizePot odds = Price to call / Pot size post-call = 29%" }, { "code": null, "e": 8303, "s": 8263, "text": "Chance to win β‰₯ 60.66% (conservatively)" }, { "code": null, "e": 8334, "s": 8303, "text": "Price to call = 0.7 * pot size" }, { "code": null, "e": 8382, "s": 8334, "text": "Pot size post-call = (1 + 0.7 + 0.7) * pot size" }, { "code": null, "e": 8434, "s": 8382, "text": "Pot odds = Price to call / Pot size post-call = 29%" }, { "code": null, "e": 8728, "s": 8434, "text": "My chance to win is at least double the pot odds. Hence, I proceed to call. The result? The villain turns his cards. The table once quiet makes a collective β€˜wow’ while staring at the Ace Jack on the table making a Straight over Straight situation and leaving the villain with all of my chips." }, { "code": null, "e": 8955, "s": 8728, "text": "In this article, I showed how to represent basic poker elements (e.g. Hands and Combos) and how to calculate poker odds assuming random hands as well as ranges in Python while telling a true history of a night at the Venetian." }, { "code": null, "e": 9170, "s": 8955, "text": "We showed how exciting (and probabilistically interesting) poker can be. Below, I show how my winning odds changed from flop to turn and then river assuming random cards for the villain as well as inferring ranges." }, { "code": null, "e": 9318, "s": 9170, "text": "We observe that I was a major favorite of winning this heads-up hand even though the final result was not in my favor. That’s why poker players say" }, { "code": null, "e": 9390, "s": 9318, "text": "you should focus on the decisions you make not on the results you have." }, { "code": null, "e": 9762, "s": 9390, "text": "Of course, all the analysis in this article assumed some ranges and basic poker strategies that formed my mental model at the time of playing and here implemented in Python. I’m no Poker Pro and there are many ways to go about this hand. I believe I have made several mistakes, for instance, underestimating the chances of the villain holding AJ given the pre-flop raise." } ]
How to convert List to Map in Java 8 | Java 8 List to Map | Online Tutorialspoint
PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC EXCEPTIONS COLLECTIONS SWING JDBC JAVA 8 SPRING SPRING BOOT HIBERNATE PYTHON PHP JQUERY PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws In this tutorial, we are going to learn about the conversion of List to Map in Java 8. We can convert the Java List<?> of objects into Map<k,v> in Java 8 via the Collectors class. The Collectors class provides a method called toMap() to convert List to Map. Collectors.toMap() : toMap() is a static method. It returns the Collector instance containing results (Map) of provided mapping functions as input parameters. class Department { private int deptId; private String deptName; public Department(int deptId, String deptName) { super(); this.deptId = deptId; this.deptName = deptName; } public int getDeptId() { return deptId; } public String getDeptName() { return deptName; } } Here we are going to convert a list of Department objects into Map. package com.onlinetutorialspoint.java8; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class Java8_ListToMap { public static void main(String[] args) { List<Department> deptList = new ArrayList<Department>(); deptList.add(new Department(1, "IT")); deptList.add(new Department(2, "HR")); deptList.add(new Department(3, "Management")); deptList.add(new Department(4, "Development")); deptList.add(new Department(5, "Recruitment")); Map<Integer, String> deptMap = deptList.stream().collect( Collectors.toMap(Department::getDeptId, Department::getDeptName)); deptMap.forEach((k,v)->System.out.println("DeptId (" + k + ") Name :" + v)); } } Output : DeptId (1) Name :IT DeptId (2) Name :HR DeptId (3) Name :Management DeptId (4) Name :Development DeptId (5) Name :Recruitment The above example runs well if the map doesn’t contain any null key or values. If anyone of the entry is null, the toMap() method throws NullPointerException. List<Department> deptList = new ArrayList<Department>(); deptList.add(new Department(1, "IT")); deptList.add(new Department(2, "HR")); deptList.add(new Department(3, null)); deptList.add(new Department(4, "Development")); deptList.add(new Department(5, "Recruitment")); Map<Integer, String> deptMap = deptList.stream().collect(Collectors.toMap(Department::getDeptId, Department::getDeptName)); deptMap.forEach((k,v)->System.out.println("DeptId (" + k + ") Name :" + v)); The above code will generate NullPointerException like below: Exception in thread "main" java.lang.NullPointerException at java.util.stream.Collectors.lambda$toMap$58(Unknown Source) at java.util.stream.ReduceOps$3ReducingSink.accept(Unknown Source) at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(Unknown Source) at java.util.stream.AbstractPipeline.copyInto(Unknown Source) You can also referto know how to resolve NullPointerException in Collectors.toMap(). Happy Learning πŸ™‚ Resolve NullPointerException in Collectors.toMap Java 8 how to remove duplicates from list Java 8 groupingBy Example How to Filter a Map in Java 8 Java 8 How to convert Stream to List How to calculate Employees Salaries Java 8 summingInt Java 8 How to Convert List to String comma separated values How to Filter null values from Java8 Stream How to convert Java Map to JSON Java 8 Stream Filter Example with Objects How to convert JSON to Java Map Object How to sort a Map using Java8 Java how to convert ArrayList to Array Example Spring Collection Map Dependency Example How to Convert Iterable to Stream Java 8 Resolve NullPointerException in Collectors.toMap Java 8 how to remove duplicates from list Java 8 groupingBy Example How to Filter a Map in Java 8 Java 8 How to convert Stream to List How to calculate Employees Salaries Java 8 summingInt Java 8 How to Convert List to String comma separated values How to Filter null values from Java8 Stream How to convert Java Map to JSON Java 8 Stream Filter Example with Objects How to convert JSON to Java Map Object How to sort a Map using Java8 Java how to convert ArrayList to Array Example Spring Collection Map Dependency Example How to Convert Iterable to Stream Java 8 Ξ” Java8 – Install Windows Java8 – foreach Java8 – forEach with index Java8 – Stream Filter Objects Java8 – Comparator Userdefined Java8 – GroupingBy Java8 – SummingInt Java8 – walk ReadFiles Java8 – JAVA_HOME on Windows Howto – Install Java on Mac OS Howto – Convert Iterable to Stream Howto – Get common elements from two Lists Howto – Convert List to String Howto – Concatenate Arrays using Stream Howto – Remove duplicates from List Howto – Filter null values from Stream Howto – Convert List to Map Howto – Convert Stream to List Howto – Sort a Map Howto – Filter a Map Howto – Get Current UTC Time Howto – Verify an Array contains a specific value Howto – Convert ArrayList to Array Howto – Read File Line By Line Howto – Convert Date to LocalDate Howto – Merge Streams Howto – Resolve NullPointerException in toMap Howto -Get Stream count Howto – Get Min and Max values in a Stream Howto – Convert InputStream to String
[ { "code": null, "e": 158, "s": 123, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 172, "s": 158, "text": "Java Examples" }, { "code": null, "e": 183, "s": 172, "text": "C Examples" }, { "code": null, "e": 195, "s": 183, "text": "C Tutorials" }, { "code": null, "e": 199, "s": 195, "text": "aws" }, { "code": null, "e": 234, "s": 199, "text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC" }, { "code": null, "e": 245, "s": 234, "text": "EXCEPTIONS" }, { "code": null, "e": 257, "s": 245, "text": "COLLECTIONS" }, { "code": null, "e": 263, "s": 257, "text": "SWING" }, { "code": null, "e": 268, "s": 263, "text": "JDBC" }, { "code": null, "e": 275, "s": 268, "text": "JAVA 8" }, { "code": null, "e": 282, "s": 275, "text": "SPRING" }, { "code": null, "e": 294, "s": 282, "text": "SPRING BOOT" }, { "code": null, "e": 304, "s": 294, "text": "HIBERNATE" }, { "code": null, "e": 311, "s": 304, "text": "PYTHON" }, { "code": null, "e": 315, "s": 311, "text": "PHP" }, { "code": null, "e": 322, "s": 315, "text": "JQUERY" }, { "code": null, "e": 357, "s": 322, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 371, "s": 357, "text": "Java Examples" }, { "code": null, "e": 382, "s": 371, "text": "C Examples" }, { "code": null, "e": 394, "s": 382, "text": "C Tutorials" }, { "code": null, "e": 398, "s": 394, "text": "aws" }, { "code": null, "e": 485, "s": 398, "text": "In this tutorial, we are going to learn about the conversion of List to Map in Java 8." }, { "code": null, "e": 656, "s": 485, "text": "We can convert the Java List<?> of objects into Map<k,v> in Java 8 via the Collectors class. The Collectors class provides a method called toMap() to convert List to Map." }, { "code": null, "e": 677, "s": 656, "text": "Collectors.toMap() :" }, { "code": null, "e": 815, "s": 677, "text": "toMap() is a static method. It returns the Collector instance containing results (Map) of provided mapping functions as input parameters." }, { "code": null, "e": 1155, "s": 815, "text": "class Department {\n private int deptId;\n private String deptName;\n\n public Department(int deptId, String deptName) {\n super();\n this.deptId = deptId;\n this.deptName = deptName;\n }\n\n public int getDeptId() {\n return deptId;\n }\n public String getDeptName() {\n return deptName;\n }\n\n}" }, { "code": null, "e": 1223, "s": 1155, "text": "Here we are going to convert a list of Department objects into Map." }, { "code": null, "e": 2036, "s": 1223, "text": "package com.onlinetutorialspoint.java8;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.stream.Collectors;\n\npublic class Java8_ListToMap {\n\n public static void main(String[] args) {\n List<Department> deptList = new ArrayList<Department>(); \n deptList.add(new Department(1, \"IT\"));\n deptList.add(new Department(2, \"HR\"));\n deptList.add(new Department(3, \"Management\"));\n deptList.add(new Department(4, \"Development\"));\n deptList.add(new Department(5, \"Recruitment\"));\n Map<Integer, String> deptMap = deptList.stream().collect(\n Collectors.toMap(Department::getDeptId, Department::getDeptName));\n \n deptMap.forEach((k,v)->System.out.println(\"DeptId (\" + k + \") Name :\" + v));\n }\n \n}" }, { "code": null, "e": 2045, "s": 2036, "text": "Output :" }, { "code": null, "e": 2171, "s": 2045, "text": "DeptId (1) Name :IT\nDeptId (2) Name :HR\nDeptId (3) Name :Management\nDeptId (4) Name :Development\nDeptId (5) Name :Recruitment" }, { "code": null, "e": 2330, "s": 2171, "text": "The above example runs well if the map doesn’t contain any null key or values. If anyone of the entry is null, the toMap() method throws NullPointerException." }, { "code": null, "e": 2862, "s": 2330, "text": "List<Department> deptList = new ArrayList<Department>(); \n deptList.add(new Department(1, \"IT\"));\n deptList.add(new Department(2, \"HR\"));\n deptList.add(new Department(3, null));\n deptList.add(new Department(4, \"Development\"));\n deptList.add(new Department(5, \"Recruitment\"));\n Map<Integer, String> deptMap = deptList.stream().collect(Collectors.toMap(Department::getDeptId, Department::getDeptName));\n deptMap.forEach((k,v)->System.out.println(\"DeptId (\" + k + \") Name :\" + v));\n" }, { "code": null, "e": 2924, "s": 2862, "text": "The above code will generate NullPointerException like below:" }, { "code": null, "e": 3252, "s": 2924, "text": "Exception in thread \"main\" java.lang.NullPointerException\nat java.util.stream.Collectors.lambda$toMap$58(Unknown Source)\nat java.util.stream.ReduceOps$3ReducingSink.accept(Unknown Source)\nat java.util.ArrayList$ArrayListSpliterator.forEachRemaining(Unknown Source)\nat java.util.stream.AbstractPipeline.copyInto(Unknown Source)\n" }, { "code": null, "e": 3337, "s": 3252, "text": "You can also referto know how to resolve NullPointerException in Collectors.toMap()." }, { "code": null, "e": 3354, "s": 3337, "text": "Happy Learning πŸ™‚" }, { "code": null, "e": 3970, "s": 3354, "text": "\nResolve NullPointerException in Collectors.toMap\nJava 8 how to remove duplicates from list\nJava 8 groupingBy Example\nHow to Filter a Map in Java 8\nJava 8 How to convert Stream to List\nHow to calculate Employees Salaries Java 8 summingInt\nJava 8 How to Convert List to String comma separated values\nHow to Filter null values from Java8 Stream\nHow to convert Java Map to JSON\nJava 8 Stream Filter Example with Objects\nHow to convert JSON to Java Map Object\nHow to sort a Map using Java8\nJava how to convert ArrayList to Array Example\nSpring Collection Map Dependency Example\nHow to Convert Iterable to Stream Java 8\n" }, { "code": null, "e": 4019, "s": 3970, "text": "Resolve NullPointerException in Collectors.toMap" }, { "code": null, "e": 4061, "s": 4019, "text": "Java 8 how to remove duplicates from list" }, { "code": null, "e": 4087, "s": 4061, "text": "Java 8 groupingBy Example" }, { "code": null, "e": 4117, "s": 4087, "text": "How to Filter a Map in Java 8" }, { "code": null, "e": 4154, "s": 4117, "text": "Java 8 How to convert Stream to List" }, { "code": null, "e": 4208, "s": 4154, "text": "How to calculate Employees Salaries Java 8 summingInt" }, { "code": null, "e": 4268, "s": 4208, "text": "Java 8 How to Convert List to String comma separated values" }, { "code": null, "e": 4312, "s": 4268, "text": "How to Filter null values from Java8 Stream" }, { "code": null, "e": 4344, "s": 4312, "text": "How to convert Java Map to JSON" }, { "code": null, "e": 4386, "s": 4344, "text": "Java 8 Stream Filter Example with Objects" }, { "code": null, "e": 4425, "s": 4386, "text": "How to convert JSON to Java Map Object" }, { "code": null, "e": 4455, "s": 4425, "text": "How to sort a Map using Java8" }, { "code": null, "e": 4502, "s": 4455, "text": "Java how to convert ArrayList to Array Example" }, { "code": null, "e": 4543, "s": 4502, "text": "Spring Collection Map Dependency Example" }, { "code": null, "e": 4584, "s": 4543, "text": "How to Convert Iterable to Stream Java 8" }, { "code": null, "e": 4590, "s": 4588, "text": "Ξ”" }, { "code": null, "e": 4615, "s": 4590, "text": " Java8 – Install Windows" }, { "code": null, "e": 4632, "s": 4615, "text": " Java8 – foreach" }, { "code": null, "e": 4660, "s": 4632, "text": " Java8 – forEach with index" }, { "code": null, "e": 4691, "s": 4660, "text": " Java8 – Stream Filter Objects" }, { "code": null, "e": 4723, "s": 4691, "text": " Java8 – Comparator Userdefined" }, { "code": null, "e": 4743, "s": 4723, "text": " Java8 – GroupingBy" }, { "code": null, "e": 4763, "s": 4743, "text": " Java8 – SummingInt" }, { "code": null, "e": 4787, "s": 4763, "text": " Java8 – walk ReadFiles" }, { "code": null, "e": 4817, "s": 4787, "text": " Java8 – JAVA_HOME on Windows" }, { "code": null, "e": 4849, "s": 4817, "text": " Howto – Install Java on Mac OS" }, { "code": null, "e": 4885, "s": 4849, "text": " Howto – Convert Iterable to Stream" }, { "code": null, "e": 4929, "s": 4885, "text": " Howto – Get common elements from two Lists" }, { "code": null, "e": 4961, "s": 4929, "text": " Howto – Convert List to String" }, { "code": null, "e": 5002, "s": 4961, "text": " Howto – Concatenate Arrays using Stream" }, { "code": null, "e": 5039, "s": 5002, "text": " Howto – Remove duplicates from List" }, { "code": null, "e": 5079, "s": 5039, "text": " Howto – Filter null values from Stream" }, { "code": null, "e": 5108, "s": 5079, "text": " Howto – Convert List to Map" }, { "code": null, "e": 5140, "s": 5108, "text": " Howto – Convert Stream to List" }, { "code": null, "e": 5160, "s": 5140, "text": " Howto – Sort a Map" }, { "code": null, "e": 5182, "s": 5160, "text": " Howto – Filter a Map" }, { "code": null, "e": 5212, "s": 5182, "text": " Howto – Get Current UTC Time" }, { "code": null, "e": 5263, "s": 5212, "text": " Howto – Verify an Array contains a specific value" }, { "code": null, "e": 5299, "s": 5263, "text": " Howto – Convert ArrayList to Array" }, { "code": null, "e": 5331, "s": 5299, "text": " Howto – Read File Line By Line" }, { "code": null, "e": 5366, "s": 5331, "text": " Howto – Convert Date to LocalDate" }, { "code": null, "e": 5389, "s": 5366, "text": " Howto – Merge Streams" }, { "code": null, "e": 5436, "s": 5389, "text": " Howto – Resolve NullPointerException in toMap" }, { "code": null, "e": 5461, "s": 5436, "text": " Howto -Get Stream count" }, { "code": null, "e": 5505, "s": 5461, "text": " Howto – Get Min and Max values in a Stream" } ]
DSA using Java - Hash Table
HashTable is a datastructure in which insertion and search operations are very fast irrespective of size of the hashtable. It is nearly a constant or O(1). Hash Table uses array as a storage medium and uses hash technique to generate index where an element is to be inserted or to be located from. Hashing is a technique to convert a range of key values into a range of indexes of an array. We're going to use modulo operator to get a range of key values. Consider an example of hashtable of size 20, and following items are to be stored. Item are in (key,value) format. (1,20) (1,20) (2,70) (2,70) (42,80) (42,80) (4,25) (4,25) (12,44) (12,44) (14,32) (14,32) (17,11) (17,11) (13,78) (13,78) (37,98) (37,98) As we can see, it may happen that the hashing technique used create already used index of the array. In such case, we can search the next empty location in the array by looking into the next cell until we found an empty cell. This technique is called linear probing. Following are basic primary operations of a hashtable which are following. Search βˆ’ search an element in a hashtable. Search βˆ’ search an element in a hashtable. Insert βˆ’ insert an element in a hashtable. Insert βˆ’ insert an element in a hashtable. delete βˆ’ delete an element from a hashtable. delete βˆ’ delete an element from a hashtable. Define a data item having some data, and key based on which search is to be conducted in hashtable. public class DataItem { private int key; private int data; public DataItem(int key, int data){ this.key = key; this.data = data; } public int getKey(){ return key; } public int getData(){ return data; } } Define a hashing method to compute the hash code of the key of the data item. public int hashCode(int key){ return key % size; } Whenever an element is to be searched. Compute the hash code of the key passed and locate the element using that hashcode as index in the array. Use linear probing to get element ahead if element not found at computed hash code. public DataItem search(int key){ //get the hash int hashIndex = hashCode(key); //move in array until an empty while(hashArray[hashIndex] !=null){ if(hashArray[hashIndex].getKey() == key) return hashArray[hashIndex]; //go to next cell ++hashIndex; //wrap around the table hashIndex %= size; } return null; } Whenever an element is to be inserted. Compute the hash code of the key passed and locate the index using that hashcode as index in the array. Use linear probing for empty location if an element is found at computed hash code. public void insert(DataItem item){ int key = item.getKey(); //get the hash int hashIndex = hashCode(key); //move in array until an empty or deleted cell while(hashArray[hashIndex] !=null && hashArray[hashIndex].getKey() != -1){ //go to next cell ++hashIndex; //wrap around the table hashIndex %= size; } hashArray[hashIndex] = item; } Whenever an element is to be deleted. Compute the hash code of the key passed and locate the index using that hashcode as index in the array. Use linear probing to get element ahead if an element is not found at computed hash code. When found, store a dummy item there to keep performance of hashtable intact. public DataItem delete(DataItem item){ int key = item.getKey(); //get the hash int hashIndex = hashCode(key); //move in array until an empty while(hashArray[hashIndex] !=null){ if(hashArray[hashIndex].getKey() == key){ DataItem temp = hashArray[hashIndex]; //assign a dummy item at deleted position hashArray[hashIndex] = dummyItem; return temp; } //go to next cell ++hashIndex; //wrap around the table hashIndex %= size; } return null; } DataItem.java package com.tutorialspoint.datastructure; public class DataItem { private int key; private int data; public DataItem(int key, int data){ this.key = key; this.data = data; } public int getKey(){ return key; } public int getData(){ return data; } } HashTable.java package com.tutorialspoint.datastructure; public class HashTable { private DataItem[] hashArray; private int size; private DataItem dummyItem; public HashTable(int size){ this.size = size; hashArray = new DataItem[size]; dummyItem = new DataItem(-1,-1); } public void display(){ for(int i=0; i<size; i++) { if(hashArray[i] != null) System.out.print(" (" +hashArray[i].getKey()+"," +hashArray[i].getData() + ") "); else System.out.print(" ~~ "); } System.out.println(""); } public int hashCode(int key){ return key % size; } public DataItem search(int key){ //get the hash int hashIndex = hashCode(key); //move in array until an empty while(hashArray[hashIndex] !=null){ if(hashArray[hashIndex].getKey() == key) return hashArray[hashIndex]; //go to next cell ++hashIndex; //wrap around the table hashIndex %= size; } return null; } public void insert(DataItem item){ int key = item.getKey(); //get the hash int hashIndex = hashCode(key); //move in array until an empty or deleted cell while(hashArray[hashIndex] !=null && hashArray[hashIndex].getKey() != -1){ //go to next cell ++hashIndex; //wrap around the table hashIndex %= size; } hashArray[hashIndex] = item; } public DataItem delete(DataItem item){ int key = item.getKey(); //get the hash int hashIndex = hashCode(key); //move in array until an empty while(hashArray[hashIndex] !=null){ if(hashArray[hashIndex].getKey() == key){ DataItem temp = hashArray[hashIndex]; //assign a dummy item at deleted position hashArray[hashIndex] = dummyItem; return temp; } //go to next cell ++hashIndex; //wrap around the table hashIndex %= size; } return null; } } HashTableDemo.java package com.tutorialspoint.datastructure; public class HashTableDemo { public static void main(String[] args){ HashTable hashTable = new HashTable(20); hashTable.insert(new DataItem(1, 20)); hashTable.insert(new DataItem(2, 70)); hashTable.insert(new DataItem(42, 80)); hashTable.insert(new DataItem(4, 25)); hashTable.insert(new DataItem(12, 44)); hashTable.insert(new DataItem(14, 32)); hashTable.insert(new DataItem(17, 11)); hashTable.insert(new DataItem(13, 78)); hashTable.insert(new DataItem(37, 97)); hashTable.display(); DataItem item = hashTable.search(37); if(item != null){ System.out.println("Element found: "+ item.getData()); }else{ System.out.println("Element not found"); } hashTable.delete(item); item = hashTable.search(37); if(item != null){ System.out.println("Element found: "+ item.getData()); }else{ System.out.println("Element not found"); } } } If we compile and run the above program then it would produce following result βˆ’ ~~ (1,20) (2,70) (42,80) (4,25) ~~ ~~ ~~ ~~ ~~ ~~ ~~ (12,44) (13,78) (14,32) ~~ ~~ (17,11) (37,97) ~~ Element found: 97 Element not found Print Add Notes Bookmark this page
[ { "code": null, "e": 2466, "s": 2168, "text": "HashTable is a datastructure in which insertion and search operations are very fast irrespective of size of the hashtable. It is nearly a constant or O(1). Hash Table uses array as a storage medium and uses hash technique to generate index where an element is to be inserted or to be located from." }, { "code": null, "e": 2739, "s": 2466, "text": "Hashing is a technique to convert a range of key values into a range of indexes of an array. We're going to use modulo operator to get a range of key values. Consider an example of hashtable of size 20, and following items are to be stored. Item are in (key,value) format." }, { "code": null, "e": 2746, "s": 2739, "text": "(1,20)" }, { "code": null, "e": 2753, "s": 2746, "text": "(1,20)" }, { "code": null, "e": 2760, "s": 2753, "text": "(2,70)" }, { "code": null, "e": 2767, "s": 2760, "text": "(2,70)" }, { "code": null, "e": 2775, "s": 2767, "text": "(42,80)" }, { "code": null, "e": 2783, "s": 2775, "text": "(42,80)" }, { "code": null, "e": 2790, "s": 2783, "text": "(4,25)" }, { "code": null, "e": 2797, "s": 2790, "text": "(4,25)" }, { "code": null, "e": 2805, "s": 2797, "text": "(12,44)" }, { "code": null, "e": 2813, "s": 2805, "text": "(12,44)" }, { "code": null, "e": 2821, "s": 2813, "text": "(14,32)" }, { "code": null, "e": 2829, "s": 2821, "text": "(14,32)" }, { "code": null, "e": 2837, "s": 2829, "text": "(17,11)" }, { "code": null, "e": 2845, "s": 2837, "text": "(17,11)" }, { "code": null, "e": 2853, "s": 2845, "text": "(13,78)" }, { "code": null, "e": 2861, "s": 2853, "text": "(13,78)" }, { "code": null, "e": 2869, "s": 2861, "text": "(37,98)" }, { "code": null, "e": 2877, "s": 2869, "text": "(37,98)" }, { "code": null, "e": 3144, "s": 2877, "text": "As we can see, it may happen that the hashing technique used create already used index of the array. In such case, we can search the next empty location in the array by looking into the next cell until we found an empty cell. This technique is called linear probing." }, { "code": null, "e": 3219, "s": 3144, "text": "Following are basic primary operations of a hashtable which are following." }, { "code": null, "e": 3262, "s": 3219, "text": "Search βˆ’ search an element in a hashtable." }, { "code": null, "e": 3305, "s": 3262, "text": "Search βˆ’ search an element in a hashtable." }, { "code": null, "e": 3348, "s": 3305, "text": "Insert βˆ’ insert an element in a hashtable." }, { "code": null, "e": 3391, "s": 3348, "text": "Insert βˆ’ insert an element in a hashtable." }, { "code": null, "e": 3436, "s": 3391, "text": "delete βˆ’ delete an element from a hashtable." }, { "code": null, "e": 3481, "s": 3436, "text": "delete βˆ’ delete an element from a hashtable." }, { "code": null, "e": 3581, "s": 3481, "text": "Define a data item having some data, and key based on which search is to be conducted in hashtable." }, { "code": null, "e": 3840, "s": 3581, "text": "public class DataItem {\n private int key;\n private int data;\n\n public DataItem(int key, int data){\n this.key = key;\n this.data = data;\n }\n\n public int getKey(){\n return key;\n }\n\n public int getData(){\n return data;\n } \n}" }, { "code": null, "e": 3918, "s": 3840, "text": "Define a hashing method to compute the hash code of the key of the data item." }, { "code": null, "e": 3972, "s": 3918, "text": "public int hashCode(int key){\n return key % size;\n}" }, { "code": null, "e": 4201, "s": 3972, "text": "Whenever an element is to be searched. Compute the hash code of the key passed and locate the element using that hashcode as index in the array. Use linear probing to get element ahead if element not found at computed hash code." }, { "code": null, "e": 4607, "s": 4201, "text": "public DataItem search(int key){ \n //get the hash \n int hashIndex = hashCode(key); \n //move in array until an empty \n while(hashArray[hashIndex] !=null){\n if(hashArray[hashIndex].getKey() == key)\n return hashArray[hashIndex]; \n //go to next cell\n ++hashIndex;\n //wrap around the table\n hashIndex %= size;\n } \n return null; \n}" }, { "code": null, "e": 4834, "s": 4607, "text": "Whenever an element is to be inserted. Compute the hash code of the key passed and locate the index using that hashcode as index in the array. Use linear probing for empty location if an element is found at computed hash code." }, { "code": null, "e": 5232, "s": 4834, "text": "public void insert(DataItem item){\n int key = item.getKey();\n\n //get the hash \n int hashIndex = hashCode(key);\n\n //move in array until an empty or deleted cell\n while(hashArray[hashIndex] !=null\n && hashArray[hashIndex].getKey() != -1){\n //go to next cell\n ++hashIndex;\n //wrap around the table\n hashIndex %= size;\n }\n\n hashArray[hashIndex] = item; \n}" }, { "code": null, "e": 5542, "s": 5232, "text": "Whenever an element is to be deleted. Compute the hash code of the key passed and locate the index using that hashcode as index in the array. Use linear probing to get element ahead if an element is not found at computed hash code. When found, store a dummy item there to keep performance of hashtable intact." }, { "code": null, "e": 6111, "s": 5542, "text": "public DataItem delete(DataItem item){\n int key = item.getKey();\n\n //get the hash \n int hashIndex = hashCode(key);\n\n //move in array until an empty \n while(hashArray[hashIndex] !=null){\n if(hashArray[hashIndex].getKey() == key){\n DataItem temp = hashArray[hashIndex]; \n //assign a dummy item at deleted position\n hashArray[hashIndex] = dummyItem; \n return temp;\n } \n //go to next cell\n ++hashIndex;\n //wrap around the table\n hashIndex %= size;\n } \n return null; \n}" }, { "code": null, "e": 6125, "s": 6111, "text": "DataItem.java" }, { "code": null, "e": 6427, "s": 6125, "text": "package com.tutorialspoint.datastructure;\n\npublic class DataItem {\n private int key;\n private int data;\n\n public DataItem(int key, int data){\n this.key = key;\n this.data = data;\n }\n\n public int getKey(){\n return key;\n }\n\n public int getData(){\n return data;\n } \n}" }, { "code": null, "e": 6442, "s": 6427, "text": "HashTable.java" }, { "code": null, "e": 8647, "s": 6442, "text": "package com.tutorialspoint.datastructure;\n\npublic class HashTable {\n \n private DataItem[] hashArray; \n private int size;\n private DataItem dummyItem;\n\n public HashTable(int size){\n this.size = size;\n hashArray = new DataItem[size];\n dummyItem = new DataItem(-1,-1);\n }\n\n public void display(){\n for(int i=0; i<size; i++) {\n if(hashArray[i] != null)\n System.out.print(\" (\"\n +hashArray[i].getKey()+\",\"\n +hashArray[i].getData() + \") \");\n else\n System.out.print(\" ~~ \");\n }\n System.out.println(\"\");\n }\n \n public int hashCode(int key){\n return key % size;\n }\n\n public DataItem search(int key){ \n //get the hash \n int hashIndex = hashCode(key); \n //move in array until an empty \n while(hashArray[hashIndex] !=null){\n if(hashArray[hashIndex].getKey() == key)\n return hashArray[hashIndex]; \n //go to next cell\n ++hashIndex;\n //wrap around the table\n hashIndex %= size;\n } \n return null; \n }\n \n public void insert(DataItem item){\n int key = item.getKey();\n\n //get the hash \n int hashIndex = hashCode(key);\n\n //move in array until an empty or deleted cell\n while(hashArray[hashIndex] !=null\n && hashArray[hashIndex].getKey() != -1){\n //go to next cell\n ++hashIndex;\n //wrap around the table\n hashIndex %= size;\n }\n\n hashArray[hashIndex] = item; \n }\n\n public DataItem delete(DataItem item){\n int key = item.getKey();\n\n //get the hash \n int hashIndex = hashCode(key);\n\n //move in array until an empty \n while(hashArray[hashIndex] !=null){\n if(hashArray[hashIndex].getKey() == key){\n DataItem temp = hashArray[hashIndex]; \n //assign a dummy item at deleted position\n hashArray[hashIndex] = dummyItem; \n return temp;\n } \n //go to next cell\n ++hashIndex;\n //wrap around the table\n hashIndex %= size;\n } \n return null; \n }\n}" }, { "code": null, "e": 8666, "s": 8647, "text": "HashTableDemo.java" }, { "code": null, "e": 9708, "s": 8666, "text": "package com.tutorialspoint.datastructure;\n\npublic class HashTableDemo {\n public static void main(String[] args){\n HashTable hashTable = new HashTable(20);\n\n hashTable.insert(new DataItem(1, 20));\n hashTable.insert(new DataItem(2, 70));\n hashTable.insert(new DataItem(42, 80));\n hashTable.insert(new DataItem(4, 25));\n hashTable.insert(new DataItem(12, 44));\n hashTable.insert(new DataItem(14, 32));\n hashTable.insert(new DataItem(17, 11));\n hashTable.insert(new DataItem(13, 78));\n hashTable.insert(new DataItem(37, 97));\n\n hashTable.display();\n\n DataItem item = hashTable.search(37);\n\n if(item != null){\n System.out.println(\"Element found: \"+ item.getData());\n }else{\n System.out.println(\"Element not found\");\n }\n\n hashTable.delete(item);\n\t\n item = hashTable.search(37);\n\n if(item != null){\n System.out.println(\"Element found: \"+ item.getData());\n }else{\n System.out.println(\"Element not found\");\n }\n }\n}" }, { "code": null, "e": 9789, "s": 9708, "text": "If we compile and run the above program then it would produce following result βˆ’" }, { "code": null, "e": 9948, "s": 9789, "text": " ~~ (1,20) (2,70) (42,80) (4,25) ~~ ~~ ~~ ~~ ~~ ~~ ~~ (12,44) (13,78) (14,32) ~~ ~~ (17,11) (37,97) ~~ \nElement found: 97\nElement not found\n" }, { "code": null, "e": 9955, "s": 9948, "text": " Print" }, { "code": null, "e": 9966, "s": 9955, "text": " Add Notes" } ]
How to get the day of the month in JavaScript?
To get the day of the month, use the getDate() method. JavaScript date getDate() method returns the day of the month for the specified date according to local time. The value returned by getDate() is an integer between 1 and 31. You can try to run the following code to learn how to get a day of the month in JavaScript βˆ’ Live Demo <html> <head> <title>JavaScript getDate Method</title> </head> <body> <script> var dt = new Date("December 31, 2017 11:20:10"); document.write("Today is " + dt.getDate() ); </script> </body> </html> Today is 31
[ { "code": null, "e": 1291, "s": 1062, "text": "To get the day of the month, use the getDate() method. JavaScript date getDate() method returns the day of the month for the specified date according to local time. The value returned by getDate() is an integer between 1 and 31." }, { "code": null, "e": 1384, "s": 1291, "text": "You can try to run the following code to learn how to get a day of the month in JavaScript βˆ’" }, { "code": null, "e": 1394, "s": 1384, "text": "Live Demo" }, { "code": null, "e": 1641, "s": 1394, "text": "<html>\n <head>\n <title>JavaScript getDate Method</title>\n </head>\n <body>\n <script>\n var dt = new Date(\"December 31, 2017 11:20:10\");\n document.write(\"Today is \" + dt.getDate() );\n </script>\n </body>\n</html>" }, { "code": null, "e": 1653, "s": 1641, "text": "Today is 31" } ]
Count number of trailing zeros in (1^1)*(2^2)*(3^3)*(4^4)*.. in C++
Given an integer num as input. The goal is to find the number of trailing zeroes in the product 11 X 22 X 33 X...X numnum. For Example num=5 Count of number of trailing zeros in (1^1)*(2^2)*(3^3)*(4^4)*.. are: 5 The number of 2s and 5s in the product will be: 11 * 22* 33* 44* 55=11 * 22* 33* (22)4* 55. So total 10 2s and 5 5s, minimum is 5 so trailing zeroes will be 5. num=10 Count of number of trailing zeros in (1^1)*(2^2)*(3^3)*(4^4)*.. are: 5 The number of 2s and 5s in the product will be: 11 *22*33*44*55*66 *77*88*99*1010 = 11 *22*33*44*55*66 *77*88*99*(2*5)10. So total 20 2s and 15 5s, minimum is 15 so trailing zeroes will be 15. Approach used in the below program is as follows βˆ’ In this approach we will count the number of 2s and 5s in prime factorization of each number in the product. As each number is raised to its own power, the minimum of count of 2s or 5s in factorization will give the count of trailing zeroes. As each 2*5 adds one 0 in the product. Take an integer num as input. Take an integer num as input. Function count_trailing(int num) takes num and returns count of number of trailing zeros in (1^1)*(2^2)*(3^3)*(4^4)*..... Function count_trailing(int num) takes num and returns count of number of trailing zeros in (1^1)*(2^2)*(3^3)*(4^4)*..... Take the initial count as 0. Take the initial count as 0. Take variables temp_2 = 0, temp_5 = 0 for counts of 2s and 5s. Take variables temp_2 = 0, temp_5 = 0 for counts of 2s and 5s. Traverse using for loops from i=1 to i<=num. Traverse using for loops from i=1 to i<=num. Take temp as i. Take temp as i. While temp is divisible by 2 then reduce it to half and add i to count temp_2 as the number of 2s. While temp is divisible by 2 then reduce it to half and add i to count temp_2 as the number of 2s. While temp is divisible by 5 then divide it by 5 and add i to count temp_5 as the number of 5s. While temp is divisible by 5 then divide it by 5 and add i to count temp_5 as the number of 5s. Take count as a minimum of two counts using count = min(temp_2, temp_5). Take count as a minimum of two counts using count = min(temp_2, temp_5). Return count as result. Return count as result. Live Demo #include <bits/stdc++.h> using namespace std; int count_trailing(int num){ int count = 0; int temp_2 = 0; int temp_5 = 0; for (int i = 1; i <= num; i++){ int temp = i; while(temp % 2 == 0 && temp > 0){ temp = temp / 2; temp_2 = temp_2 + i; } while (temp % 5 == 0 && temp > 0){ temp = temp / 5; temp_5 = temp_5+ i; } } count = min(temp_2, temp_5); return count; } int main(){ int num = 5; cout<<"Count of number of trailing zeros in (1^1)*(2^2)*(3^3)*(4^4)*.. are: "<<count_trailing(num); return 0; } If we run the above code it will generate the following output βˆ’ Count of number of trailing zeros in (1^1)*(2^2)*(3^3)*(4^4)*.. are: 5
[ { "code": null, "e": 1185, "s": 1062, "text": "Given an integer num as input. The goal is to find the number of trailing zeroes in the product 11 X 22 X 33 X...X numnum." }, { "code": null, "e": 1197, "s": 1185, "text": "For Example" }, { "code": null, "e": 1203, "s": 1197, "text": "num=5" }, { "code": null, "e": 1274, "s": 1203, "text": "Count of number of trailing zeros in (1^1)*(2^2)*(3^3)*(4^4)*.. are: 5" }, { "code": null, "e": 1434, "s": 1274, "text": "The number of 2s and 5s in the product will be:\n11 * 22* 33* 44* 55=11 * 22* 33* (22)4* 55. So total 10 2s and 5 5s, minimum is 5 so trailing zeroes will be 5." }, { "code": null, "e": 1441, "s": 1434, "text": "num=10" }, { "code": null, "e": 1512, "s": 1441, "text": "Count of number of trailing zeros in (1^1)*(2^2)*(3^3)*(4^4)*.. are: 5" }, { "code": null, "e": 1705, "s": 1512, "text": "The number of 2s and 5s in the product will be:\n11 *22*33*44*55*66 *77*88*99*1010 = 11 *22*33*44*55*66 *77*88*99*(2*5)10. So total 20 2s and 15 5s, minimum is 15 so trailing zeroes will be 15." }, { "code": null, "e": 1756, "s": 1705, "text": "Approach used in the below program is as follows βˆ’" }, { "code": null, "e": 2037, "s": 1756, "text": "In this approach we will count the number of 2s and 5s in prime factorization of each number in the product. As each number is raised to its own power, the minimum of count of 2s or 5s in factorization will give the count of trailing zeroes. As each 2*5 adds one 0 in the product." }, { "code": null, "e": 2067, "s": 2037, "text": "Take an integer num as input." }, { "code": null, "e": 2097, "s": 2067, "text": "Take an integer num as input." }, { "code": null, "e": 2219, "s": 2097, "text": "Function count_trailing(int num) takes num and returns count of number of\ntrailing zeros in (1^1)*(2^2)*(3^3)*(4^4)*....." }, { "code": null, "e": 2341, "s": 2219, "text": "Function count_trailing(int num) takes num and returns count of number of\ntrailing zeros in (1^1)*(2^2)*(3^3)*(4^4)*....." }, { "code": null, "e": 2370, "s": 2341, "text": "Take the initial count as 0." }, { "code": null, "e": 2399, "s": 2370, "text": "Take the initial count as 0." }, { "code": null, "e": 2462, "s": 2399, "text": "Take variables temp_2 = 0, temp_5 = 0 for counts of 2s and 5s." }, { "code": null, "e": 2525, "s": 2462, "text": "Take variables temp_2 = 0, temp_5 = 0 for counts of 2s and 5s." }, { "code": null, "e": 2570, "s": 2525, "text": "Traverse using for loops from i=1 to i<=num." }, { "code": null, "e": 2615, "s": 2570, "text": "Traverse using for loops from i=1 to i<=num." }, { "code": null, "e": 2631, "s": 2615, "text": "Take temp as i." }, { "code": null, "e": 2647, "s": 2631, "text": "Take temp as i." }, { "code": null, "e": 2746, "s": 2647, "text": "While temp is divisible by 2 then reduce it to half and add i to count temp_2 as the number of 2s." }, { "code": null, "e": 2845, "s": 2746, "text": "While temp is divisible by 2 then reduce it to half and add i to count temp_2 as the number of 2s." }, { "code": null, "e": 2941, "s": 2845, "text": "While temp is divisible by 5 then divide it by 5 and add i to count temp_5 as the number of 5s." }, { "code": null, "e": 3037, "s": 2941, "text": "While temp is divisible by 5 then divide it by 5 and add i to count temp_5 as the number of 5s." }, { "code": null, "e": 3110, "s": 3037, "text": "Take count as a minimum of two counts using count = min(temp_2, temp_5)." }, { "code": null, "e": 3183, "s": 3110, "text": "Take count as a minimum of two counts using count = min(temp_2, temp_5)." }, { "code": null, "e": 3207, "s": 3183, "text": "Return count as result." }, { "code": null, "e": 3231, "s": 3207, "text": "Return count as result." }, { "code": null, "e": 3242, "s": 3231, "text": " Live Demo" }, { "code": null, "e": 3838, "s": 3242, "text": "#include <bits/stdc++.h>\nusing namespace std;\nint count_trailing(int num){\n int count = 0;\n int temp_2 = 0;\n int temp_5 = 0;\n for (int i = 1; i <= num; i++){\n int temp = i;\n while(temp % 2 == 0 && temp > 0){\n temp = temp / 2;\n temp_2 = temp_2 + i;\n }\n while (temp % 5 == 0 && temp > 0){\n temp = temp / 5;\n temp_5 = temp_5+ i;\n }\n }\n count = min(temp_2, temp_5);\n return count;\n}\nint main(){\n int num = 5;\n cout<<\"Count of number of trailing zeros in (1^1)*(2^2)*(3^3)*(4^4)*.. are: \"<<count_trailing(num);\n return 0;\n}" }, { "code": null, "e": 3903, "s": 3838, "text": "If we run the above code it will generate the following output βˆ’" }, { "code": null, "e": 3974, "s": 3903, "text": "Count of number of trailing zeros in (1^1)*(2^2)*(3^3)*(4^4)*.. are: 5" } ]
Program to find Lexicographically Smallest String With One Swap in Python
Suppose we have a string s, we have to find the lexicographically smallest string that can be made if we can make at most one swap between two characters in the given string s. So, if the input is like "zyzx", then the output will be "xyzz" To solve this, we will follow these steps βˆ’ temp := an array of size s and fill with 0 m:= size of s - 1 for i in range size of s -1 to -1, decrease by 1, doif s[i] < s[m], thenm := itemp[i] := mfor i in range 0 to size of s, doa := temp[i]if s[a] is not same as s[i], thenreturn substring of s [from index 0 to i] concatenate s[a] concatenate substring of s [from index i+1 to a] concatenate s[i] concatenate substring of s [from index a+1 to end] if s[i] < s[m], thenm := i m := i temp[i] := m for i in range 0 to size of s, doa := temp[i]if s[a] is not same as s[i], thenreturn substring of s [from index 0 to i] concatenate s[a] concatenate substring of s [from index i+1 to a] concatenate s[i] concatenate substring of s [from index a+1 to end] a := temp[i] if s[a] is not same as s[i], thenreturn substring of s [from index 0 to i] concatenate s[a] concatenate substring of s [from index i+1 to a] concatenate s[i] concatenate substring of s [from index a+1 to end] return substring of s [from index 0 to i] concatenate s[a] concatenate substring of s [from index i+1 to a] concatenate s[i] concatenate substring of s [from index a+1 to end] return s Live Demo class Solution: def solve(self, s): temp = [0]*len(s) m=len(s)-1 for i in range(len(s)-1, -1, -1): if s[i]<s[m]: m=i temp[i] = m for i in range(len(s)): a = temp[i] if s[a] != s[i]: return s[:i]+s[a]+s[i+1:a]+s[i]+s[a+1:] return s ob = Solution() print(ob.solve("zyzx")) zyzx xyzz
[ { "code": null, "e": 1239, "s": 1062, "text": "Suppose we have a string s, we have to find the lexicographically smallest string that can be made if we can make at most one swap between two characters in the given string s." }, { "code": null, "e": 1303, "s": 1239, "text": "So, if the input is like \"zyzx\", then the output will be \"xyzz\"" }, { "code": null, "e": 1347, "s": 1303, "text": "To solve this, we will follow these steps βˆ’" }, { "code": null, "e": 1390, "s": 1347, "text": "temp := an array of size s and fill with 0" }, { "code": null, "e": 1408, "s": 1390, "text": "m:= size of s - 1" }, { "code": null, "e": 1752, "s": 1408, "text": "for i in range size of s -1 to -1, decrease by 1, doif s[i] < s[m], thenm := itemp[i] := mfor i in range 0 to size of s, doa := temp[i]if s[a] is not same as s[i], thenreturn substring of s [from index 0 to i] concatenate s[a] concatenate\nsubstring of s [from index i+1 to a] concatenate s[i] concatenate\nsubstring of s [from index a+1 to end]" }, { "code": null, "e": 1779, "s": 1752, "text": "if s[i] < s[m], thenm := i" }, { "code": null, "e": 1786, "s": 1779, "text": "m := i" }, { "code": null, "e": 1799, "s": 1786, "text": "temp[i] := m" }, { "code": null, "e": 2053, "s": 1799, "text": "for i in range 0 to size of s, doa := temp[i]if s[a] is not same as s[i], thenreturn substring of s [from index 0 to i] concatenate s[a] concatenate\nsubstring of s [from index i+1 to a] concatenate s[i] concatenate\nsubstring of s [from index a+1 to end]" }, { "code": null, "e": 2066, "s": 2053, "text": "a := temp[i]" }, { "code": null, "e": 2275, "s": 2066, "text": "if s[a] is not same as s[i], thenreturn substring of s [from index 0 to i] concatenate s[a] concatenate\nsubstring of s [from index i+1 to a] concatenate s[i] concatenate\nsubstring of s [from index a+1 to end]" }, { "code": null, "e": 2451, "s": 2275, "text": "return substring of s [from index 0 to i] concatenate s[a] concatenate\nsubstring of s [from index i+1 to a] concatenate s[i] concatenate\nsubstring of s [from index a+1 to end]" }, { "code": null, "e": 2460, "s": 2451, "text": "return s" }, { "code": null, "e": 2471, "s": 2460, "text": " Live Demo" }, { "code": null, "e": 2826, "s": 2471, "text": "class Solution:\n def solve(self, s):\n temp = [0]*len(s)\n m=len(s)-1\n for i in range(len(s)-1, -1, -1):\n if s[i]<s[m]: m=i\n temp[i] = m\n for i in range(len(s)):\n a = temp[i]\n if s[a] != s[i]:\n return s[:i]+s[a]+s[i+1:a]+s[i]+s[a+1:]\n return s\nob = Solution()\nprint(ob.solve(\"zyzx\"))" }, { "code": null, "e": 2831, "s": 2826, "text": "zyzx" }, { "code": null, "e": 2836, "s": 2831, "text": "xyzz" } ]
Ruby | String chop Method - GeeksforGeeks
17 Jun, 2021 chop is a String class method in Ruby which is used to return a new String with the last character removed. Both characters are removed if the string ends with \r\n, b. Applying chop to an empty string returns an empty string. Syntax:str.chopParameters: Here, str is the given string.Returns: A new string having no record separator. Example 1: Ruby # Ruby program to demonstrate# the chop method # Taking a string and# using the methodputs "Ruby".chopputs "Ruby\r\n".chop Output: Rub Ruby Example 2: Ruby # Ruby program to demonstrate# the chop method # Taking a string and# using the methodputs "String\r\n\r\r\n".chop # Removing two charactersputs "Method".chop.chop Output: String Meth sweetyty Ruby String-class Ruby-Methods Ruby Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Ruby | Enumerator each_with_index function Ruby | Types of Iterators Ruby | Decision Making (if, if-else, if-else-if, ternary) | Set - 1 Ruby | Class Method and Variables Ruby | pop() function Ruby | String chomp! Method Ruby | Array shift() function Ruby | String concat Method Ruby | Operators Ruby on Rails Introduction
[ { "code": null, "e": 23906, "s": 23878, "text": "\n17 Jun, 2021" }, { "code": null, "e": 24134, "s": 23906, "text": "chop is a String class method in Ruby which is used to return a new String with the last character removed. Both characters are removed if the string ends with \\r\\n, b. Applying chop to an empty string returns an empty string. " }, { "code": null, "e": 24243, "s": 24134, "text": "Syntax:str.chopParameters: Here, str is the given string.Returns: A new string having no record separator. " }, { "code": null, "e": 24256, "s": 24243, "text": "Example 1: " }, { "code": null, "e": 24261, "s": 24256, "text": "Ruby" }, { "code": "# Ruby program to demonstrate# the chop method # Taking a string and# using the methodputs \"Ruby\".chopputs \"Ruby\\r\\n\".chop", "e": 24389, "s": 24261, "text": null }, { "code": null, "e": 24399, "s": 24389, "text": "Output: " }, { "code": null, "e": 24408, "s": 24399, "text": "Rub\nRuby" }, { "code": null, "e": 24420, "s": 24408, "text": "Example 2: " }, { "code": null, "e": 24425, "s": 24420, "text": "Ruby" }, { "code": "# Ruby program to demonstrate# the chop method # Taking a string and# using the methodputs \"String\\r\\n\\r\\r\\n\".chop # Removing two charactersputs \"Method\".chop.chop", "e": 24594, "s": 24425, "text": null }, { "code": null, "e": 24604, "s": 24594, "text": "Output: " }, { "code": null, "e": 24617, "s": 24604, "text": "String\n\nMeth" }, { "code": null, "e": 24628, "s": 24619, "text": "sweetyty" }, { "code": null, "e": 24646, "s": 24628, "text": "Ruby String-class" }, { "code": null, "e": 24659, "s": 24646, "text": "Ruby-Methods" }, { "code": null, "e": 24664, "s": 24659, "text": "Ruby" }, { "code": null, "e": 24762, "s": 24664, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 24771, "s": 24762, "text": "Comments" }, { "code": null, "e": 24784, "s": 24771, "text": "Old Comments" }, { "code": null, "e": 24827, "s": 24784, "text": "Ruby | Enumerator each_with_index function" }, { "code": null, "e": 24853, "s": 24827, "text": "Ruby | Types of Iterators" }, { "code": null, "e": 24921, "s": 24853, "text": "Ruby | Decision Making (if, if-else, if-else-if, ternary) | Set - 1" }, { "code": null, "e": 24955, "s": 24921, "text": "Ruby | Class Method and Variables" }, { "code": null, "e": 24977, "s": 24955, "text": "Ruby | pop() function" }, { "code": null, "e": 25005, "s": 24977, "text": "Ruby | String chomp! Method" }, { "code": null, "e": 25035, "s": 25005, "text": "Ruby | Array shift() function" }, { "code": null, "e": 25063, "s": 25035, "text": "Ruby | String concat Method" }, { "code": null, "e": 25080, "s": 25063, "text": "Ruby | Operators" } ]
Getter and Setter in Dart Programming
Reading and writing access to objects is very important in any programming language. Getter and Setter are the exact methods that we use when we want to access the reading and writing privileges to an object's properties. A getter usually looks something like this - returnType get fieldName { // return the value } The returnType is the type of data we are returning. The get keyword is what tells us and the compiler that is a getter, and then lastly we have the fieldName whose value we are trying to get. A setter usually looks something like this βˆ’ set fieldName { // set the value } The set is the keyword that tells us and the compiler that this is a setter method. After the set keyword, we have the fieldName whose value we are trying to set in the following code block. Now, let's create a class named Employee in which we will have different fields to apply our getter and setter methods to. Consider the example shown below βˆ’ Live Demo class Employee { var empName = "mukul"; var empAge = 24; var empSalary = 500; String get employeeName { return empName; } void set employeeName(String name) { this.empName = name; } void set employeeAge(int age) { if(age<= 18) { print("Employee Age should be greater than 18 Years."); } else { this.empAge = age; } } int get employeeAge { return empAge; } void set employeeSalary(int salary) { if(salary<= 0) { print("Salary cannot be less than 0"); } else { this.empSalary = salary; } } int get employeeSalary { return empSalary; } } void main() { Employee emp = new Employee(); emp.employeeName = 'Rahul'; emp.employeeAge = 25; emp.employeeSalary = 2000; print("Employee's Name is : ${emp.employeeName}"); print("Employee's Age is : ${emp.employeeAge}"); print("Employee's Salary is : ${emp.employeeSalary}"); } In the above example, we have an Employee class and when we are creating an object of the Employee class inside the main function, we are then making use of different getter and setter methods to access and write to the object's fields. Employee's Name is : Rahul Employee's Age is : 25 Employee's Salary is : 2000
[ { "code": null, "e": 1284, "s": 1062, "text": "Reading and writing access to objects is very important in any programming language. Getter and Setter are the exact methods that we use when we want to access the reading and writing privileges to an object's properties." }, { "code": null, "e": 1329, "s": 1284, "text": "A getter usually looks something like this -" }, { "code": null, "e": 1381, "s": 1329, "text": "returnType get fieldName {\n // return the value\n}" }, { "code": null, "e": 1574, "s": 1381, "text": "The returnType is the type of data we are returning. The get keyword is what tells us and the compiler that is a getter, and then lastly we have the fieldName whose value we are trying to get." }, { "code": null, "e": 1619, "s": 1574, "text": "A setter usually looks something like this βˆ’" }, { "code": null, "e": 1657, "s": 1619, "text": "set fieldName {\n // set the value\n}" }, { "code": null, "e": 1848, "s": 1657, "text": "The set is the keyword that tells us and the compiler that this is a setter method. After the set keyword, we have the fieldName whose value we are trying to set in the following code block." }, { "code": null, "e": 1971, "s": 1848, "text": "Now, let's create a class named Employee in which we will have different fields to apply our getter and setter methods to." }, { "code": null, "e": 2006, "s": 1971, "text": "Consider the example shown below βˆ’" }, { "code": null, "e": 2017, "s": 2006, "text": " Live Demo" }, { "code": null, "e": 2993, "s": 2017, "text": "class Employee {\n var empName = \"mukul\";\n var empAge = 24;\n var empSalary = 500;\n String get employeeName {\n return empName;\n }\n void set employeeName(String name) {\n this.empName = name;\n }\n void set employeeAge(int age) {\n if(age<= 18) {\n print(\"Employee Age should be greater than 18 Years.\");\n } else {\n this.empAge = age;\n }\n }\n int get employeeAge {\n return empAge;\n }\n void set employeeSalary(int salary) {\n if(salary<= 0) {\n print(\"Salary cannot be less than 0\");\n } else {\n this.empSalary = salary;\n }\n }\n int get employeeSalary {\n return empSalary;\n }\n}\nvoid main() {\n Employee emp = new Employee();\n emp.employeeName = 'Rahul';\n emp.employeeAge = 25;\n emp.employeeSalary = 2000;\n print(\"Employee's Name is : ${emp.employeeName}\");\n print(\"Employee's Age is : ${emp.employeeAge}\");\n print(\"Employee's Salary is : ${emp.employeeSalary}\");\n}" }, { "code": null, "e": 3230, "s": 2993, "text": "In the above example, we have an Employee class and when we are creating an object of the Employee class inside the main function, we are then making use of different getter and setter methods to access and write to the object's fields." }, { "code": null, "e": 3308, "s": 3230, "text": "Employee's Name is : Rahul\nEmployee's Age is : 25\nEmployee's Salary is : 2000" } ]
Bitwise NOT in Arduino
Unlike logical NOT, which inverts the truth value of an expression, the bitwise NOT applies to each bit of a number and inverts its value (0 to 1 and 1 to 0). The operator is ~. The syntax thus is ~a, where a is the number on which this operator has to apply. Please note, that all the leading 0s in the number’s representation are also converted to 1. For example, if your board uses 16 bits to represent an integer, then here’s what ~10 will look like As you can see, each bit of 10 got inverted. This number corresponds to, using 2’s complement, -11. You can use this site for quickly converting decimal number to their 2’s complements and vice versa https://www.exploringbinary.com/twos-complement-converter/. You can read more about 2’s complement here &minnus; https://www.tutorialspoint.com/two-scomplement Let’s verify this on the Serial Monitor. The code is given below βˆ’ void setup() { // put your setup code here, to run once: Serial.begin(9600); Serial.println(); int a = 10; Serial.println(~a); } void loop() { // put your main code here, to run repeatedly: } The Serial Monitor output is βˆ’ As you can see, the output was exactly as expected.
[ { "code": null, "e": 1240, "s": 1062, "text": "Unlike logical NOT, which inverts the truth value of an expression, the bitwise NOT applies to each bit of a number and inverts its value (0 to 1 and 1 to 0). The operator is ~." }, { "code": null, "e": 1322, "s": 1240, "text": "The syntax thus is ~a, where a is the number on which this operator has to apply." }, { "code": null, "e": 1516, "s": 1322, "text": "Please note, that all the leading 0s in the number’s representation are also converted to 1. For example, if your board uses 16 bits to represent an integer, then here’s what ~10 will look like" }, { "code": null, "e": 1776, "s": 1516, "text": "As you can see, each bit of 10 got inverted. This number corresponds to, using 2’s complement, -11. You can use this site for quickly converting decimal number to their 2’s complements and vice versa https://www.exploringbinary.com/twos-complement-converter/." }, { "code": null, "e": 1876, "s": 1776, "text": "You can read more about 2’s complement here &minnus; https://www.tutorialspoint.com/two-scomplement" }, { "code": null, "e": 1943, "s": 1876, "text": "Let’s verify this on the Serial Monitor. The code is given below βˆ’" }, { "code": null, "e": 2155, "s": 1943, "text": "void setup() {\n // put your setup code here, to run once:\n Serial.begin(9600);\n Serial.println();\n\n int a = 10;\n Serial.println(~a);\n}\n\nvoid loop() {\n // put your main code here, to run repeatedly:\n}" }, { "code": null, "e": 2186, "s": 2155, "text": "The Serial Monitor output is βˆ’" }, { "code": null, "e": 2238, "s": 2186, "text": "As you can see, the output was exactly as expected." } ]
GATE | GATE CS 2008 | Question 69 - GeeksforGeeks
24 Sep, 2021 Consider the following relational schemes for a library database:Book (Title, Author, Catalog_no, Publisher, Year, Price)Collection (Title, Author, Catalog_no) with in the following functional dependencies: I. Title Author --> Catalog_no II. Catalog_no --> Title, Author, Publisher, Year III. Publisher Title Year --> Price Assume {Author, Title} is the key for both schemes. Which of the following statements is true?(A) Both Book and Collection are in BCNF(B) Both Book and Collection are in 3NF only(C) Book is in 2NF and Collection is in 3NF(D) Both Book and Collection are in 2NF onlyAnswer: (C)Explanation: Book (Title, Author, Catalog_no, Publisher, Year, Price) Collection (Title, Author, Catalog_no) with in the following functional dependencies: I. Title, Author --> Catalog_no II. Catalog_no --> Title, Author, Publisher, Year III. Publisher, Title, Year --> Price Assume {Author, Title} is the key for both schemes The table β€œCollection” is in BCNF as there is only one functional dependency β€œTitle Author –> Catalog_no” and {Author, Title} is key for collection. Book is not in BCNF because Catalog_no is not a key and there is a functional dependency β€œCatalog_no –> Title Author Publisher Year”. Book is not in 3NF because non-prime attributes (Publisher Year) are transitively dependent on key [Title, Author]. Book is in 2NF because every non-prime attribute of the table is either dependent on the whole of a candidate key [Title, Author], or on another non prime attribute.In table book, candidate keys are {Title, Author} and {Catalog_no}. In table Book, non-prime attributes (attributes that do not occur in any candidate key) are Publisher, Year and Place Please refer Database Normalization | Normal Forms for details of normal forms.Quiz of this Question jainarpitkekri GATE-CS-2008 GATE-GATE CS 2008 GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments GATE | GATE-CS-2014-(Set-3) | Question 38 GATE | GATE-IT-2004 | Question 83 GATE | GATE CS 2018 | Question 37 GATE | GATE-CS-2016 (Set 2) | Question 48 GATE | GATE-CS-2016 (Set 1) | Question 65 GATE | GATE-CS-2016 (Set 1) | Question 63 GATE | GATE-IT-2004 | Question 12 GATE | GATE-CS-2014-(Set-3) | Question 65 GATE | GATE-CS-2007 | Question 64 GATE | GATE-CS-2014-(Set-3) | Question 65
[ { "code": null, "e": 24338, "s": 24310, "text": "\n24 Sep, 2021" }, { "code": null, "e": 24498, "s": 24338, "text": "Consider the following relational schemes for a library database:Book (Title, Author, Catalog_no, Publisher, Year, Price)Collection (Title, Author, Catalog_no)" }, { "code": null, "e": 24545, "s": 24498, "text": "with in the following functional dependencies:" }, { "code": null, "e": 24663, "s": 24545, "text": "I. Title Author --> Catalog_no\nII. Catalog_no --> Title, Author, Publisher, Year\nIII. Publisher Title Year --> Price " }, { "code": null, "e": 24952, "s": 24663, "text": "Assume {Author, Title} is the key for both schemes. Which of the following statements is true?(A) Both Book and Collection are in BCNF(B) Both Book and Collection are in 3NF only(C) Book is in 2NF and Collection is in 3NF(D) Both Book and Collection are in 2NF onlyAnswer: (C)Explanation:" }, { "code": null, "e": 25049, "s": 24952, "text": "Book (Title, Author, Catalog_no, Publisher, Year, Price)\nCollection (Title, Author, Catalog_no) " }, { "code": null, "e": 25096, "s": 25049, "text": "with in the following functional dependencies:" }, { "code": null, "e": 25271, "s": 25096, "text": "I. Title, Author --> Catalog_no\nII. Catalog_no --> Title, Author, Publisher, Year\nIII. Publisher, Title, Year --> Price \n\nAssume {Author, Title} is the key for both schemes " }, { "code": null, "e": 25420, "s": 25271, "text": "The table β€œCollection” is in BCNF as there is only one functional dependency β€œTitle Author –> Catalog_no” and {Author, Title} is key for collection." }, { "code": null, "e": 25554, "s": 25420, "text": "Book is not in BCNF because Catalog_no is not a key and there is a functional dependency β€œCatalog_no –> Title Author Publisher Year”." }, { "code": null, "e": 25670, "s": 25554, "text": "Book is not in 3NF because non-prime attributes (Publisher Year) are transitively dependent on key [Title, Author]." }, { "code": null, "e": 26021, "s": 25670, "text": "Book is in 2NF because every non-prime attribute of the table is either dependent on the whole of a candidate key [Title, Author], or on another non prime attribute.In table book, candidate keys are {Title, Author} and {Catalog_no}. In table Book, non-prime attributes (attributes that do not occur in any candidate key) are Publisher, Year and Place" }, { "code": null, "e": 26122, "s": 26021, "text": "Please refer Database Normalization | Normal Forms for details of normal forms.Quiz of this Question" }, { "code": null, "e": 26137, "s": 26122, "text": "jainarpitkekri" }, { "code": null, "e": 26150, "s": 26137, "text": "GATE-CS-2008" }, { "code": null, "e": 26168, "s": 26150, "text": "GATE-GATE CS 2008" }, { "code": null, "e": 26173, "s": 26168, "text": "GATE" }, { "code": null, "e": 26271, "s": 26173, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26280, "s": 26271, "text": "Comments" }, { "code": null, "e": 26293, "s": 26280, "text": "Old Comments" }, { "code": null, "e": 26335, "s": 26293, "text": "GATE | GATE-CS-2014-(Set-3) | Question 38" }, { "code": null, "e": 26369, "s": 26335, "text": "GATE | GATE-IT-2004 | Question 83" }, { "code": null, "e": 26403, "s": 26369, "text": "GATE | GATE CS 2018 | Question 37" }, { "code": null, "e": 26445, "s": 26403, "text": "GATE | GATE-CS-2016 (Set 2) | Question 48" }, { "code": null, "e": 26487, "s": 26445, "text": "GATE | GATE-CS-2016 (Set 1) | Question 65" }, { "code": null, "e": 26529, "s": 26487, "text": "GATE | GATE-CS-2016 (Set 1) | Question 63" }, { "code": null, "e": 26563, "s": 26529, "text": "GATE | GATE-IT-2004 | Question 12" }, { "code": null, "e": 26605, "s": 26563, "text": "GATE | GATE-CS-2014-(Set-3) | Question 65" }, { "code": null, "e": 26639, "s": 26605, "text": "GATE | GATE-CS-2007 | Question 64" } ]
How to show values in boxplot in R?
The main values in a boxplot are minimum, first quartile, median, third quartile, and the maximum, and this group of values is also called five-number summary. Therefore, if we want to show values in boxplot then we can use text function and provide the five-number summary and labels with fivenum function as shown in the below examples. x<-sample(0:9,500,replace=TRUE) boxplot(x,horizontal=TRUE) text(x=fivenum(x),labels=fivenum(x),y=1.25) y<-rpois(5000,10) boxplot(y,horizontal=TRUE) text(x=fivenum(y),labels=fivenum(y),y=1.25)
[ { "code": null, "e": 1401, "s": 1062, "text": "The main values in a boxplot are minimum, first quartile, median, third quartile, and the maximum, and this group of values is also called five-number summary. Therefore, if we want to show values in boxplot then we can use text function and provide the five-number summary and labels with fivenum function as shown in the below examples." }, { "code": null, "e": 1504, "s": 1401, "text": "x<-sample(0:9,500,replace=TRUE)\nboxplot(x,horizontal=TRUE) text(x=fivenum(x),labels=fivenum(x),y=1.25)" }, { "code": null, "e": 1593, "s": 1504, "text": "y<-rpois(5000,10)\nboxplot(y,horizontal=TRUE)\ntext(x=fivenum(y),labels=fivenum(y),y=1.25)" } ]
Is Python Object Oriented or Procedural?
Yes, Python support both Object Oriented and Procedural Programming language as it is a high level programming language designed for general purpose programming. Python are multi-paradigm, you can write programs or libraries that are largely procedural, object-oriented, or functional in all of these languages. It depends on what you mean by functional. Python does have some features of a functional language. OOP's concepts like, Classes,Encapsulation,Polymorphism, Inheritance etc.. in Python makes it as a object oriented programming language. In Similar way we can created procedural program through python using loops ,for ,while etc ..and control structure. class Rectangle: def __init__(self, length, breadth, unit_cost=0): self.length = length self.breadth = breadth self.unit_cost = unit_cost def get_perimeter(self): return 2 * (self.length + self.breadth) def get_area(self): return self.length * self.breadth def calculate_cost(self): area = self.get_area() return area * self.unit_cost # breadth = 120 cm, length = 160 cm, 1 cm^2 = Rs 2000 r = Rectangle(160, 120, 2000) print("Area of Rectangle: %s cm^2" % (r.get_area())) print("Cost of rectangular field: Rs. %s " %(r.calculate_cost())) Area of Rectangle: 19200 cm^2 Cost of rectangular field: Rs. 38400000
[ { "code": null, "e": 1477, "s": 1062, "text": "Yes, Python support both Object Oriented and Procedural Programming language as it is a high level programming language designed for general purpose programming. Python are multi-paradigm, you can write programs or libraries that are largely procedural, object-oriented, or functional in all of these languages. It depends on what you mean by functional. Python does have some features of a functional language. " }, { "code": null, "e": 1615, "s": 1477, "text": "OOP's concepts like, Classes,Encapsulation,Polymorphism, Inheritance etc.. in Python makes it as a object oriented programming language. " }, { "code": null, "e": 1732, "s": 1615, "text": "In Similar way we can created procedural program through python using loops ,for ,while etc ..and control structure." }, { "code": null, "e": 2326, "s": 1732, "text": "class Rectangle:\n def __init__(self, length, breadth, unit_cost=0):\n self.length = length\n self.breadth = breadth\n self.unit_cost = unit_cost\n def get_perimeter(self):\n return 2 * (self.length + self.breadth)\n def get_area(self):\n return self.length * self.breadth\n def calculate_cost(self):\n area = self.get_area()\n return area * self.unit_cost\n# breadth = 120 cm, length = 160 cm, 1 cm^2 = Rs 2000\nr = Rectangle(160, 120, 2000)\nprint(\"Area of Rectangle: %s cm^2\" % (r.get_area()))\nprint(\"Cost of rectangular field: Rs. %s \" %(r.calculate_cost()))" }, { "code": null, "e": 2396, "s": 2326, "text": "Area of Rectangle: 19200 cm^2\nCost of rectangular field: Rs. 38400000" } ]
How to insert own values into auto_increment column in MySQL?
You can achieve this with the help of INSERT statement i.e, you can simply insert it like a normal insert. The syntax is as follows βˆ’ INSERT INTO yourTableName (yourIdColumnName,yourColumnName) values(value1,'value2'); Let us first create a table: mysql> create table InsertValueInAutoIncrement -> ( -> UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> UserName varchar(20) -> ); Query OK, 0 rows affected (0.59 sec) Now you can insert some records in the table using insert command. Here, we are also inserting our own values for the auto_increment field UserId. The query is as follows βˆ’ mysql> insert into InsertValueInAutoIncrement(UserName) values('John'); Query OK, 1 row affected (0.19 sec) mysql> insert into InsertValueInAutoIncrement(UserName) values('Carol'); Query OK, 1 row affected (0.17 sec) mysql> insert into InsertValueInAutoIncrement(UserName) values('Sam'); Query OK, 1 row affected (0.11 sec) mysql> insert into InsertValueInAutoIncrement(UserName) values('Bob'); Query OK, 1 row affected (0.18 sec) mysql> insert into InsertValueInAutoIncrement(UserId,UserName) values(100,'Maxwell'); Query OK, 1 row affected (0.18 sec) mysql> insert into InsertValueInAutoIncrement(UserName) values('James'); Query OK, 1 row affected (0.20 sec) mysql> insert into InsertValueInAutoIncrement(UserId,UserName) values(1000,'Larry'); Query OK, 1 row affected (0.12 sec) Display all records from the table using a select statement. The query is as follows βˆ’ mysql> select *from InsertValueInAutoIncrement; The following is the table βˆ’ +--------+----------+ | UserId | UserName | +--------+----------+ | 1 | John | | 2 | Carol | | 3 | Sam | | 4 | Bob | | 100 | Maxwell | | 101 | James | | 1000 | Larry | +--------+----------+ 7 rows in set (0.00 sec)
[ { "code": null, "e": 1196, "s": 1062, "text": "You can achieve this with the help of INSERT statement i.e, you can simply insert it like a normal insert. The syntax is as follows βˆ’" }, { "code": null, "e": 1492, "s": 1196, "text": "INSERT INTO yourTableName (yourIdColumnName,yourColumnName) values(value1,'value2');\nLet us first create a table:\nmysql> create table InsertValueInAutoIncrement\n -> (\n -> UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n -> UserName varchar(20)\n -> );\nQuery OK, 0 rows affected (0.59 sec)" }, { "code": null, "e": 1665, "s": 1492, "text": "Now you can insert some records in the table using insert command. Here, we are also inserting our own values for the auto_increment field UserId. The query is as follows βˆ’" }, { "code": null, "e": 2448, "s": 1665, "text": "mysql> insert into InsertValueInAutoIncrement(UserName) values('John');\nQuery OK, 1 row affected (0.19 sec)\nmysql> insert into InsertValueInAutoIncrement(UserName) values('Carol');\nQuery OK, 1 row affected (0.17 sec)\nmysql> insert into InsertValueInAutoIncrement(UserName) values('Sam');\nQuery OK, 1 row affected (0.11 sec)\nmysql> insert into InsertValueInAutoIncrement(UserName) values('Bob');\nQuery OK, 1 row affected (0.18 sec)\nmysql> insert into InsertValueInAutoIncrement(UserId,UserName) values(100,'Maxwell');\nQuery OK, 1 row affected (0.18 sec)\nmysql> insert into InsertValueInAutoIncrement(UserName) values('James');\nQuery OK, 1 row affected (0.20 sec)\nmysql> insert into InsertValueInAutoIncrement(UserId,UserName) values(1000,'Larry');\nQuery OK, 1 row affected (0.12 sec)" }, { "code": null, "e": 2535, "s": 2448, "text": "Display all records from the table using a select statement. The query is as follows βˆ’" }, { "code": null, "e": 2583, "s": 2535, "text": "mysql> select *from InsertValueInAutoIncrement;" }, { "code": null, "e": 2612, "s": 2583, "text": "The following is the table βˆ’" }, { "code": null, "e": 2879, "s": 2612, "text": "+--------+----------+\n| UserId | UserName |\n+--------+----------+\n| 1 | John |\n| 2 | Carol |\n| 3 | Sam |\n| 4 | Bob |\n| 100 | Maxwell |\n| 101 | James |\n| 1000 | Larry |\n+--------+----------+\n7 rows in set (0.00 sec)" } ]
Material Design Time Picker in Android - GeeksforGeeks
06 Jun, 2021 Material Design Components (MDC Android) offers designers and developers a way to implement Material Design in their Android application. Developed by a core team of engineers and UX designers at Google, these components enable a reliable development workflow to build beautiful and functional Android applications. If you like the way how the UI elements from Google Material Design Components for android which are designed by Google are pretty awesome, then here are some steps that need to be followed to get them, and one of them is Time Picker. It is not the same as that of the regular time picker in android and allows a lot of customization to improve User Experience. It gives an immense experience for the user. So in this article, it’s been discussed how to implement the Material Design Time Picker in android. Have a look at the following image on what all the perspectives the Material Design Time Picker can appear. Step 1: Create an empty activity project Create an empty activity android studio project. Refer to How to Create/Start a New Project in Android Studio. Step 2: Add the required dependencies There is a need for Material Design dependencies. To the app-level Gradle file add the following dependency. // The version 1.3.0-alpha04 may vary implementation β€˜com.google.android.material:material:1.3.0-alpha04’ Step 3: Working with activity_main.xml file The main layout of the application contains a button and one TextView. The Button opens the Material Design Time Picker and TextView previews the picked time. To implement the same UI invoke the following code inside the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" tools:ignore="HardcodedText"> <Button android:id="@+id/pick_time_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="128dp" android:text="PICK TIME" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <TextView android:id="@+id/preview_picked_time_textView" style="@style/TextAppearance.MaterialComponents.Headline6" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="32dp" android:text="Preview picked time here" app:layout_constraintEnd_toEndOf="@+id/pick_time_button" app:layout_constraintStart_toStartOf="@+id/pick_time_button" app:layout_constraintTop_toBottomOf="@+id/pick_time_button" /> </androidx.constraintlayout.widget.ConstraintLayout> Output UI: Before heading to interact with the dialog interface understanding the anatomy of dialog is important Anatomy of the MDC Time Picker (immersive dialog). Anatomy of the MDC Time Picker (compact). Step 4: Working with MainActivity.kt file In the MainActivity.kt file, handle the button click to open the Material Design Timer Picker dialog, and check for a single-digit hour and minute and update the preview text. To implement the same invoke the following code inside the MainAactivity.kt file. Kotlin import android.os.Bundleimport android.widget.Buttonimport android.widget.TextViewimport androidx.appcompat.app.AppCompatActivityimport com.google.android.material.timepicker.MaterialTimePickerimport com.google.android.material.timepicker.TimeFormat class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // create instance of the UI elements val pickTimeButton: Button = findViewById(R.id.pick_time_button) val previewPickedTimeTextView: TextView = findViewById(R.id.preview_picked_time_textView) // handle the pick time button to open pickTimeButton.setOnClickListener { // instance of MDC time picker val materialTimePicker: MaterialTimePicker = MaterialTimePicker.Builder() // set the title for the alert dialog .setTitleText("SELECT YOUR TIMING") // set the default hour for the // dialog when the dialog opens .setHour(12) // set the default minute for the // dialog when the dialog opens .setMinute(10) // set the time format // according to the region .setTimeFormat(TimeFormat.CLOCK_12H) .build() materialTimePicker.show(supportFragmentManager, "MainActivity") // on clicking the positive button of the time picker // dialog update the TextView accordingly materialTimePicker.addOnPositiveButtonClickListener { val pickedHour: Int = materialTimePicker.hour val pickedMinute: Int = materialTimePicker.minute // check for single digit hour hour and minute // and update TextView accordingly val formattedTime: String = when { pickedHour > 12 -> { if (pickedMinute < 10) { "${materialTimePicker.hour - 12}:0${materialTimePicker.minute} pm" } else { "${materialTimePicker.hour - 12}:${materialTimePicker.minute} pm" } } pickedHour == 12 -> { if (pickedMinute < 10) { "${materialTimePicker.hour}:0${materialTimePicker.minute} pm" } else { "${materialTimePicker.hour}:${materialTimePicker.minute} pm" } } pickedHour == 0 -> { if (pickedMinute < 10) { "${materialTimePicker.hour + 12}:0${materialTimePicker.minute} am" } else { "${materialTimePicker.hour + 12}:${materialTimePicker.minute} am" } } else -> { if (pickedMinute < 10) { "${materialTimePicker.hour}:0${materialTimePicker.minute} am" } else { "${materialTimePicker.hour}:${materialTimePicker.minute} am" } } } // then update the preview TextView previewPickedTimeTextView.text = formattedTime } } }} Output: Android Kotlin Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Flutter - Custom Bottom Navigation Bar How to Read Data from SQLite Database in Android? How to Post Data to API using Retrofit in Android? Android Listview in Java with Example Retrofit with Kotlin Coroutine in Android Android UI Layouts Kotlin Array Retrofit with Kotlin Coroutine in Android Kotlin Setters and Getters
[ { "code": null, "e": 24725, "s": 24697, "text": "\n06 Jun, 2021" }, { "code": null, "e": 25657, "s": 24725, "text": "Material Design Components (MDC Android) offers designers and developers a way to implement Material Design in their Android application. Developed by a core team of engineers and UX designers at Google, these components enable a reliable development workflow to build beautiful and functional Android applications. If you like the way how the UI elements from Google Material Design Components for android which are designed by Google are pretty awesome, then here are some steps that need to be followed to get them, and one of them is Time Picker. It is not the same as that of the regular time picker in android and allows a lot of customization to improve User Experience. It gives an immense experience for the user. So in this article, it’s been discussed how to implement the Material Design Time Picker in android. Have a look at the following image on what all the perspectives the Material Design Time Picker can appear." }, { "code": null, "e": 25698, "s": 25657, "text": "Step 1: Create an empty activity project" }, { "code": null, "e": 25809, "s": 25698, "text": "Create an empty activity android studio project. Refer to How to Create/Start a New Project in Android Studio." }, { "code": null, "e": 25847, "s": 25809, "text": "Step 2: Add the required dependencies" }, { "code": null, "e": 25956, "s": 25847, "text": "There is a need for Material Design dependencies. To the app-level Gradle file add the following dependency." }, { "code": null, "e": 25994, "s": 25956, "text": "// The version 1.3.0-alpha04 may vary" }, { "code": null, "e": 26062, "s": 25994, "text": "implementation β€˜com.google.android.material:material:1.3.0-alpha04’" }, { "code": null, "e": 26106, "s": 26062, "text": "Step 3: Working with activity_main.xml file" }, { "code": null, "e": 26265, "s": 26106, "text": "The main layout of the application contains a button and one TextView. The Button opens the Material Design Time Picker and TextView previews the picked time." }, { "code": null, "e": 26351, "s": 26265, "text": "To implement the same UI invoke the following code inside the activity_main.xml file." }, { "code": null, "e": 26355, "s": 26351, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\" tools:ignore=\"HardcodedText\"> <Button android:id=\"@+id/pick_time_button\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"128dp\" android:text=\"PICK TIME\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" /> <TextView android:id=\"@+id/preview_picked_time_textView\" style=\"@style/TextAppearance.MaterialComponents.Headline6\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"32dp\" android:text=\"Preview picked time here\" app:layout_constraintEnd_toEndOf=\"@+id/pick_time_button\" app:layout_constraintStart_toStartOf=\"@+id/pick_time_button\" app:layout_constraintTop_toBottomOf=\"@+id/pick_time_button\" /> </androidx.constraintlayout.widget.ConstraintLayout>", "e": 27689, "s": 26355, "text": null }, { "code": null, "e": 27700, "s": 27689, "text": "Output UI:" }, { "code": null, "e": 27802, "s": 27700, "text": "Before heading to interact with the dialog interface understanding the anatomy of dialog is important" }, { "code": null, "e": 27853, "s": 27802, "text": "Anatomy of the MDC Time Picker (immersive dialog)." }, { "code": null, "e": 27895, "s": 27853, "text": "Anatomy of the MDC Time Picker (compact)." }, { "code": null, "e": 27937, "s": 27895, "text": "Step 4: Working with MainActivity.kt file" }, { "code": null, "e": 28113, "s": 27937, "text": "In the MainActivity.kt file, handle the button click to open the Material Design Timer Picker dialog, and check for a single-digit hour and minute and update the preview text." }, { "code": null, "e": 28195, "s": 28113, "text": "To implement the same invoke the following code inside the MainAactivity.kt file." }, { "code": null, "e": 28202, "s": 28195, "text": "Kotlin" }, { "code": "import android.os.Bundleimport android.widget.Buttonimport android.widget.TextViewimport androidx.appcompat.app.AppCompatActivityimport com.google.android.material.timepicker.MaterialTimePickerimport com.google.android.material.timepicker.TimeFormat class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // create instance of the UI elements val pickTimeButton: Button = findViewById(R.id.pick_time_button) val previewPickedTimeTextView: TextView = findViewById(R.id.preview_picked_time_textView) // handle the pick time button to open pickTimeButton.setOnClickListener { // instance of MDC time picker val materialTimePicker: MaterialTimePicker = MaterialTimePicker.Builder() // set the title for the alert dialog .setTitleText(\"SELECT YOUR TIMING\") // set the default hour for the // dialog when the dialog opens .setHour(12) // set the default minute for the // dialog when the dialog opens .setMinute(10) // set the time format // according to the region .setTimeFormat(TimeFormat.CLOCK_12H) .build() materialTimePicker.show(supportFragmentManager, \"MainActivity\") // on clicking the positive button of the time picker // dialog update the TextView accordingly materialTimePicker.addOnPositiveButtonClickListener { val pickedHour: Int = materialTimePicker.hour val pickedMinute: Int = materialTimePicker.minute // check for single digit hour hour and minute // and update TextView accordingly val formattedTime: String = when { pickedHour > 12 -> { if (pickedMinute < 10) { \"${materialTimePicker.hour - 12}:0${materialTimePicker.minute} pm\" } else { \"${materialTimePicker.hour - 12}:${materialTimePicker.minute} pm\" } } pickedHour == 12 -> { if (pickedMinute < 10) { \"${materialTimePicker.hour}:0${materialTimePicker.minute} pm\" } else { \"${materialTimePicker.hour}:${materialTimePicker.minute} pm\" } } pickedHour == 0 -> { if (pickedMinute < 10) { \"${materialTimePicker.hour + 12}:0${materialTimePicker.minute} am\" } else { \"${materialTimePicker.hour + 12}:${materialTimePicker.minute} am\" } } else -> { if (pickedMinute < 10) { \"${materialTimePicker.hour}:0${materialTimePicker.minute} am\" } else { \"${materialTimePicker.hour}:${materialTimePicker.minute} am\" } } } // then update the preview TextView previewPickedTimeTextView.text = formattedTime } } }}", "e": 31693, "s": 28202, "text": null }, { "code": null, "e": 31701, "s": 31693, "text": "Output:" }, { "code": null, "e": 31709, "s": 31701, "text": "Android" }, { "code": null, "e": 31716, "s": 31709, "text": "Kotlin" }, { "code": null, "e": 31724, "s": 31716, "text": "Android" }, { "code": null, "e": 31822, "s": 31724, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31831, "s": 31822, "text": "Comments" }, { "code": null, "e": 31844, "s": 31831, "text": "Old Comments" }, { "code": null, "e": 31883, "s": 31844, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 31933, "s": 31883, "text": "How to Read Data from SQLite Database in Android?" }, { "code": null, "e": 31984, "s": 31933, "text": "How to Post Data to API using Retrofit in Android?" }, { "code": null, "e": 32022, "s": 31984, "text": "Android Listview in Java with Example" }, { "code": null, "e": 32064, "s": 32022, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 32083, "s": 32064, "text": "Android UI Layouts" }, { "code": null, "e": 32096, "s": 32083, "text": "Kotlin Array" }, { "code": null, "e": 32138, "s": 32096, "text": "Retrofit with Kotlin Coroutine in Android" } ]
Node.js Buffer.equals() Method - GeeksforGeeks
12 Oct, 2021 The Buffer.equals() method is used to compare two buffer objects and returns True of both buffer objects are the same otherwise returns False. Syntax: buffer.equals( buf ) Parameters: This method accepts single parameter otherBuffer which holds the another buffer to compare with buffer object. Return Value: This method returns True if both buffer objects are equal otherwise returns false. Below examples illustrate the Buffer.equals() method in Node.js: Example 1: // Node.js program to demonstrate the // Buffer.equals() Method // Create two bufferesvar buf1 = Buffer.from('Hi');var buf2 = Buffer.from('Hi'); // Prints true(boolean value)console.log(buf1.equals(buf2)); Output: true Example 2: // Node.js program to demonstrate the // Buffer.equals() Method // Create two bufferesvar buf1 = Buffer.from('Hi');var buf2 = Buffer.from('Hello'); // Prints false(boolean value)console.log(buf1.equals(buf2)); Output: false Reference: https://nodejs.org/api/buffer.html#buffer_buf_equals_otherbuffer Node.js-Buffer-module Picked Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Express.js express.Router() Function How to update Node.js and NPM to next version ? Node.js fs.readFileSync() Method How to update NPM ? Difference between promise and async await in Node.js Roadmap to Become a Web Developer in 2022 How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 37176, "s": 37148, "text": "\n12 Oct, 2021" }, { "code": null, "e": 37319, "s": 37176, "text": "The Buffer.equals() method is used to compare two buffer objects and returns True of both buffer objects are the same otherwise returns False." }, { "code": null, "e": 37327, "s": 37319, "text": "Syntax:" }, { "code": null, "e": 37348, "s": 37327, "text": "buffer.equals( buf )" }, { "code": null, "e": 37471, "s": 37348, "text": "Parameters: This method accepts single parameter otherBuffer which holds the another buffer to compare with buffer object." }, { "code": null, "e": 37568, "s": 37471, "text": "Return Value: This method returns True if both buffer objects are equal otherwise returns false." }, { "code": null, "e": 37633, "s": 37568, "text": "Below examples illustrate the Buffer.equals() method in Node.js:" }, { "code": null, "e": 37644, "s": 37633, "text": "Example 1:" }, { "code": "// Node.js program to demonstrate the // Buffer.equals() Method // Create two bufferesvar buf1 = Buffer.from('Hi');var buf2 = Buffer.from('Hi'); // Prints true(boolean value)console.log(buf1.equals(buf2));", "e": 37855, "s": 37644, "text": null }, { "code": null, "e": 37863, "s": 37855, "text": "Output:" }, { "code": null, "e": 37868, "s": 37863, "text": "true" }, { "code": null, "e": 37879, "s": 37868, "text": "Example 2:" }, { "code": "// Node.js program to demonstrate the // Buffer.equals() Method // Create two bufferesvar buf1 = Buffer.from('Hi');var buf2 = Buffer.from('Hello'); // Prints false(boolean value)console.log(buf1.equals(buf2));", "e": 38093, "s": 37879, "text": null }, { "code": null, "e": 38101, "s": 38093, "text": "Output:" }, { "code": null, "e": 38107, "s": 38101, "text": "false" }, { "code": null, "e": 38183, "s": 38107, "text": "Reference: https://nodejs.org/api/buffer.html#buffer_buf_equals_otherbuffer" }, { "code": null, "e": 38205, "s": 38183, "text": "Node.js-Buffer-module" }, { "code": null, "e": 38212, "s": 38205, "text": "Picked" }, { "code": null, "e": 38220, "s": 38212, "text": "Node.js" }, { "code": null, "e": 38237, "s": 38220, "text": "Web Technologies" }, { "code": null, "e": 38335, "s": 38237, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38344, "s": 38335, "text": "Comments" }, { "code": null, "e": 38357, "s": 38344, "text": "Old Comments" }, { "code": null, "e": 38394, "s": 38357, "text": "Express.js express.Router() Function" }, { "code": null, "e": 38442, "s": 38394, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 38475, "s": 38442, "text": "Node.js fs.readFileSync() Method" }, { "code": null, "e": 38495, "s": 38475, "text": "How to update NPM ?" }, { "code": null, "e": 38549, "s": 38495, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 38591, "s": 38549, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 38634, "s": 38591, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 38696, "s": 38634, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 38746, "s": 38696, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Distinct Subsequences in C++
Suppose we have strings S and T. We have to count number of distinct sequences of S which is equal to T. We know that a subsequence of a string is a new string which is formed from the original string by removing some (can be none) of the characters without disturbing the relative positions of the remaining characters. (Like, "ACE" is a subsequence of "ABCDE" while "AEC" is not). If the input strings are β€œbaalllloonnn” and β€œballoon”, then there will be 36 different ways to select. To solve this, we will follow these steps βˆ’ n := size of s, m := size of t. Update s and t by concatenating blank spaces before them n := size of s, m := size of t. Update s and t by concatenating blank spaces before them Make one matrix of size (n + 1) x (m + 1) Make one matrix of size (n + 1) x (m + 1) set dp[0, 0] := 1, then set 1 for 0th column of all row, put 1 set dp[0, 0] := 1, then set 1 for 0th column of all row, put 1 for i in range 1 to nfor j in range 1 to mif s[i] = t[j], thendp[i, j] := dp[i – 1, j – 1]dp[i, j] := dp[i, j] + dp[i – 1, j] for i in range 1 to n for j in range 1 to mif s[i] = t[j], thendp[i, j] := dp[i – 1, j – 1]dp[i, j] := dp[i, j] + dp[i – 1, j] for j in range 1 to m if s[i] = t[j], thendp[i, j] := dp[i – 1, j – 1] if s[i] = t[j], then dp[i, j] := dp[i – 1, j – 1] dp[i, j] := dp[i – 1, j – 1] dp[i, j] := dp[i, j] + dp[i – 1, j] dp[i, j] := dp[i, j] + dp[i – 1, j] return dp[n, m] return dp[n, m] Let us see the following implementation to get better understanding βˆ’ Live Demo #include <bits/stdc++.h> using namespace std; typedef long long int lli; class Solution { public: int numDistinct(string s, string t) { int n = s.size(); int m = t.size(); s = " " + s; t = " " + t; vector < vector <lli>> dp(n + 1, vector <lli> (m + 1)); dp[0][0] = 1; for(int i = 1; i<= n; i++)dp[i][0] = 1; for(int i = 1; i <= n; i++){ for(int j = 1; j <= m; j++){ if(s[i] == t[j]) dp[i][j] = dp[i - 1][j - 1]; dp[i][j]+= dp[i - 1][j]; } } return dp[n][m]; } }; main(){ Solution ob; cout << (ob.numDistinct("baalllloonnn", "balloon")); } "baalllloonnn" "balloon" 36
[ { "code": null, "e": 1167, "s": 1062, "text": "Suppose we have strings S and T. We have to count number of distinct sequences of S which is equal to T." }, { "code": null, "e": 1445, "s": 1167, "text": "We know that a subsequence of a string is a new string which is formed from the original string by removing some (can be none) of the characters without disturbing the relative positions of the remaining characters. (Like, \"ACE\" is a subsequence of \"ABCDE\" while \"AEC\" is not)." }, { "code": null, "e": 1548, "s": 1445, "text": "If the input strings are β€œbaalllloonnn” and β€œballoon”, then there will be 36 different ways to select." }, { "code": null, "e": 1592, "s": 1548, "text": "To solve this, we will follow these steps βˆ’" }, { "code": null, "e": 1681, "s": 1592, "text": "n := size of s, m := size of t. Update s and t by concatenating blank spaces before them" }, { "code": null, "e": 1770, "s": 1681, "text": "n := size of s, m := size of t. Update s and t by concatenating blank spaces before them" }, { "code": null, "e": 1812, "s": 1770, "text": "Make one matrix of size (n + 1) x (m + 1)" }, { "code": null, "e": 1854, "s": 1812, "text": "Make one matrix of size (n + 1) x (m + 1)" }, { "code": null, "e": 1917, "s": 1854, "text": "set dp[0, 0] := 1, then set 1 for 0th column of all row, put 1" }, { "code": null, "e": 1980, "s": 1917, "text": "set dp[0, 0] := 1, then set 1 for 0th column of all row, put 1" }, { "code": null, "e": 2106, "s": 1980, "text": "for i in range 1 to nfor j in range 1 to mif s[i] = t[j], thendp[i, j] := dp[i – 1, j – 1]dp[i, j] := dp[i, j] + dp[i – 1, j]" }, { "code": null, "e": 2128, "s": 2106, "text": "for i in range 1 to n" }, { "code": null, "e": 2233, "s": 2128, "text": "for j in range 1 to mif s[i] = t[j], thendp[i, j] := dp[i – 1, j – 1]dp[i, j] := dp[i, j] + dp[i – 1, j]" }, { "code": null, "e": 2255, "s": 2233, "text": "for j in range 1 to m" }, { "code": null, "e": 2304, "s": 2255, "text": "if s[i] = t[j], thendp[i, j] := dp[i – 1, j – 1]" }, { "code": null, "e": 2325, "s": 2304, "text": "if s[i] = t[j], then" }, { "code": null, "e": 2354, "s": 2325, "text": "dp[i, j] := dp[i – 1, j – 1]" }, { "code": null, "e": 2383, "s": 2354, "text": "dp[i, j] := dp[i – 1, j – 1]" }, { "code": null, "e": 2419, "s": 2383, "text": "dp[i, j] := dp[i, j] + dp[i – 1, j]" }, { "code": null, "e": 2455, "s": 2419, "text": "dp[i, j] := dp[i, j] + dp[i – 1, j]" }, { "code": null, "e": 2471, "s": 2455, "text": "return dp[n, m]" }, { "code": null, "e": 2487, "s": 2471, "text": "return dp[n, m]" }, { "code": null, "e": 2557, "s": 2487, "text": "Let us see the following implementation to get better understanding βˆ’" }, { "code": null, "e": 2568, "s": 2557, "text": " Live Demo" }, { "code": null, "e": 3224, "s": 2568, "text": "#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long int lli;\nclass Solution {\n public:\n int numDistinct(string s, string t) {\n int n = s.size();\n int m = t.size();\n s = \" \" + s;\n t = \" \" + t;\n vector < vector <lli>> dp(n + 1, vector <lli> (m + 1));\n dp[0][0] = 1;\n for(int i = 1; i<= n; i++)dp[i][0] = 1;\n for(int i = 1; i <= n; i++){\n for(int j = 1; j <= m; j++){\n if(s[i] == t[j]) dp[i][j] = dp[i - 1][j - 1];\n dp[i][j]+= dp[i - 1][j];\n }\n }\n return dp[n][m];\n }\n};\nmain(){\n Solution ob;\n cout << (ob.numDistinct(\"baalllloonnn\", \"balloon\"));\n}" }, { "code": null, "e": 3249, "s": 3224, "text": "\"baalllloonnn\"\n\"balloon\"" }, { "code": null, "e": 3252, "s": 3249, "text": "36" } ]
Rearrange a linked list | Practice | GeeksforGeeks
Given a singly linked list, the task is to rearrange it in a way that all odd position nodes are together and all even positions node are together. Assume the first element to be at position 1 followed by second element at position 2 and so on. Note: You should place all odd positioned nodes first and then the even positioned ones. (considering 1 based indexing). Also, the relative order of odd positioned nodes and even positioned nodes should be maintained. Example 1: Input: LinkedList: 1->2->3->4 Output: 1 3 2 4 Explanation: Odd elements are 1, 3 and even elements are 2, 4. Hence, resultant linked list is 1->3->2->4. Example 2: Input: LinkedList: 1->2->3->4->5 Output: 1 3 5 2 4 Explanation: Odd elements are 1, 3, 5 and even elements are 2, 4. Hence, resultant linked list is ​1->3->5->2->4. Your Task: The task is to complete the function rearrangeEvenOdd() which rearranges the nodes in the linked list as required and doesn't return anything. Expected Time Complexity: O(N). Expected Auxiliary Space: O(1). Constraints: 1 ≀ Size of the linked list ≀ 104 0 ≀ value of linked list ≀ 103 0 swapniltayal4225 days ago class Solution{ public: void rearrangeEvenOdd(Node *head) { // Your Code here if (head == NULL || head->next == NULL){ return; } Node* odd = head; Node* even = head->next; Node* evenStart = even; Node* oddStart = odd; while (odd->next != NULL && even->next != NULL){ odd->next = even->next; odd = odd->next; even->next = odd->next; even = even->next; } odd->next = evenStart; head = oddStart; }}; 0 shakshamkaushik15 days ago Time --2.25 void rearrangeEvenOdd(Node head) { Node curr = head; Node q = new Node(0); Node ans = q; int count = 1; while(curr!=null){ if(count%2==1){ q.next = new Node(curr.data); q = q.next; } count++; curr = curr.next; } curr = head; int count1 = 1; while (curr!=null){ if(count1%2==0){ q.next = new Node(curr.data); q = q.next; } count1++; curr= curr.next; } Node temp = ans.next; while(temp!=null){ head.data = temp.data; head = head.next; temp = temp.next; } }} 0 vishalsavade1 week ago //This code is contributed by Vishal Savade void rearrangeEvenOdd(Node *head) { // Your Code here if(head == NULL || head->next == NULL || head->next->next == NULL) return; Node *ol = head; Node *el = head->next; Node *el_head = el; Node *t = head->next->next; int flag = 0; while(t!= NULL){ if(flag == 0){ ol->next = t; ol = ol->next; flag = 1; } else{ el->next = t; el = el->next; flag = 0; } t = t->next; } ol->next = NULL; el->next = NULL; ol->next = el_head; } +1 shubhamkhavare2 weeks ago Simplest Java Code: Node temp = head; Node res = new Node(0); Node ans = res; int count = 1; while(temp != null) { if(count%2 != 0) { res.next = new Node(temp.data); res = res.next; } count++; temp = temp.next; } Node temp1 = head; int count1 = 1; while(temp1 != null) { if(count1%2 == 0) { res.next = new Node(temp1.data); res = res.next; } count1++; temp1 = temp1.next; } Node tempNode = ans.next; while(tempNode != null) { head.data = tempNode.data; head = head.next; tempNode = tempNode.next; } 0 cs200152 weeks ago Node *p=head; vector<int>v; while(p){ v.push_back(p->data); p=p->next; } p=head; for(int i=0;i<v.size();i+=2){ p->data=v[i]; p=p->next; } for(int i=1;i<=v.size() && p!=NULL;i+=2){ p->data=v[i]; p=p->next; } } Read Less Reply Open Externally 0 best code +3 tanashah3 weeks ago Guys it is,all odd position nodes are together and all even positions node are together. Not a odd number and even number. +2 badgujarsachin834 weeks ago void rearrangeEvenOdd(Node *head) { // Your Code here Node* even=new Node(0); Node* odd=new Node(0); Node* e=even; Node* temp=head; Node* o=odd; int c=1; while(temp){ if(c%2!=0){ o->next=temp; o=o->next; }else{ e->next=temp; e=e->next; } temp=temp->next; c++; } o->next=NULL; e->next=NULL; o->next=even->next; head=odd; } 0 hr061 month ago class Solution { public: void rearrangeEvenOdd(Node *head) { // Your Code here if(head == NULL || head->next == NULL) { return; } Node* odd = head; Node* oddH = odd; Node* even = head->next; Node* evenH = even; while(odd->next && even->next) { odd->next = odd->next->next; even->next = even->next->next; odd = odd->next; even = even->next; } odd->next = evenH; head = oddH; } }; 0 rohanjaiswal200120182 months ago void rearrangeEvenOdd(Node *head) { // Your Code here Node* even=new Node(0); Node* odd=new Node(0); Node* temp=head, *e=even, *o=odd; int c=1; while(temp){ if(c%2!=0){ o->next=temp;o=o->next; } else{ e->next=temp;e=e->next; } c++;temp=temp->next; } o->next==NULL;e->next=NULL; o->next=even->next; head=odd; } void rearrangeEvenOdd(Node *head) { // Your Code here Node* even=new Node(0); Node* odd=new Node(0); Node* temp=head, *e=even, *o=odd; int c=1; while(temp){ if(c%2!=0){ o->next=temp;o=o->next; } else{ e->next=temp;e=e->next; } c++;temp=temp->next; } o->next==NULL;e->next=NULL; o->next=even->next; head=odd; } 0 lakshta192 months ago void rearrangeEvenOdd(Node *head) { Node *p=head; vector<int>v; while(p){ v.push_back(p->data); p=p->next; } p=head; for(int i=0;i<v.size();i+=2){ p->data=v[i]; p=p->next; } for(int i=1;i<=v.size() && p!=NULL;i+=2){ p->data=v[i]; p=p->next; } } 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": 701, "s": 238, "text": "Given a singly linked list, the task is to rearrange it in a way that all odd position nodes are together and all even positions node are together.\nAssume the first element to be at position 1 followed by second element at position 2 and so on.\nNote: You should place all odd positioned nodes first and then the even positioned ones. (considering 1 based indexing). Also, the relative order of odd positioned nodes and even positioned nodes should be maintained." }, { "code": null, "e": 712, "s": 701, "text": "Example 1:" }, { "code": null, "e": 870, "s": 712, "text": "Input:\nLinkedList: 1->2->3->4\nOutput: 1 3 2 4 \nExplanation: \nOdd elements are 1, 3 and even elements are \n2, 4. Hence, resultant linked list is \n1->3->2->4.\n" }, { "code": null, "e": 881, "s": 870, "text": "Example 2:" }, { "code": null, "e": 1052, "s": 881, "text": "Input:\nLinkedList: 1->2->3->4->5\nOutput: 1 3 5 2 4 \nExplanation: \nOdd elements are 1, 3, 5 and even elements are\n2, 4. Hence, resultant linked list is\n​1->3->5->2->4.\n" }, { "code": null, "e": 1206, "s": 1052, "text": "Your Task:\nThe task is to complete the function rearrangeEvenOdd() which rearranges the nodes in the linked list as required and doesn't return anything." }, { "code": null, "e": 1270, "s": 1206, "text": "Expected Time Complexity: O(N).\nExpected Auxiliary Space: O(1)." }, { "code": null, "e": 1348, "s": 1270, "text": "Constraints:\n1 ≀ Size of the linked list ≀ 104\n0 ≀ value of linked list ≀ 103" }, { "code": null, "e": 1350, "s": 1348, "text": "0" }, { "code": null, "e": 1376, "s": 1350, "text": "swapniltayal4225 days ago" }, { "code": null, "e": 1899, "s": 1376, "text": "class Solution{ public: void rearrangeEvenOdd(Node *head) { // Your Code here if (head == NULL || head->next == NULL){ return; } Node* odd = head; Node* even = head->next; Node* evenStart = even; Node* oddStart = odd; while (odd->next != NULL && even->next != NULL){ odd->next = even->next; odd = odd->next; even->next = odd->next; even = even->next; } odd->next = evenStart; head = oddStart; }};" }, { "code": null, "e": 1901, "s": 1899, "text": "0" }, { "code": null, "e": 1928, "s": 1901, "text": "shakshamkaushik15 days ago" }, { "code": null, "e": 2265, "s": 1928, "text": "Time --2.25\n void rearrangeEvenOdd(Node head)\n {\n Node curr = head;\n Node q = new Node(0);\n Node ans = q;\n int count = 1;\n while(curr!=null){\n if(count%2==1){\n q.next = new Node(curr.data);\n q = q.next;\n }\n count++;\n curr = curr.next;" }, { "code": null, "e": 2663, "s": 2265, "text": " } curr = head; int count1 = 1; while (curr!=null){ if(count1%2==0){ q.next = new Node(curr.data); q = q.next; } count1++; curr= curr.next; } Node temp = ans.next; while(temp!=null){ head.data = temp.data; head = head.next; temp = temp.next; } }} " }, { "code": null, "e": 2665, "s": 2663, "text": "0" }, { "code": null, "e": 2688, "s": 2665, "text": "vishalsavade1 week ago" }, { "code": null, "e": 3415, "s": 2688, "text": "//This code is contributed by Vishal Savade\nvoid rearrangeEvenOdd(Node *head)\n {\n // Your Code here\n \n if(head == NULL || head->next == NULL || head->next->next == NULL) return;\n \n Node *ol = head;\n Node *el = head->next;\n Node *el_head = el;\n Node *t = head->next->next;\n \n int flag = 0;\n while(t!= NULL){\n if(flag == 0){\n ol->next = t;\n ol = ol->next;\n flag = 1;\n }\n else{\n el->next = t;\n el = el->next;\n flag = 0;\n }\n t = t->next;\n }\n ol->next = NULL;\n el->next = NULL;\n ol->next = el_head;\n }" }, { "code": null, "e": 3418, "s": 3415, "text": "+1" }, { "code": null, "e": 3444, "s": 3418, "text": "shubhamkhavare2 weeks ago" }, { "code": null, "e": 3464, "s": 3444, "text": "Simplest Java Code:" }, { "code": null, "e": 4292, "s": 3464, "text": " Node temp = head; Node res = new Node(0); Node ans = res; int count = 1; while(temp != null) { if(count%2 != 0) { res.next = new Node(temp.data); res = res.next; } count++; temp = temp.next; } Node temp1 = head; int count1 = 1; while(temp1 != null) { if(count1%2 == 0) { res.next = new Node(temp1.data); res = res.next; } count1++; temp1 = temp1.next; } Node tempNode = ans.next; while(tempNode != null) { head.data = tempNode.data; head = head.next; tempNode = tempNode.next; }" }, { "code": null, "e": 4294, "s": 4292, "text": "0" }, { "code": null, "e": 4313, "s": 4294, "text": "cs200152 weeks ago" }, { "code": null, "e": 4653, "s": 4313, "text": "\n\n Node *p=head;\n vector<int>v;\n while(p){\n v.push_back(p->data);\n p=p->next;\n }\n p=head;\n for(int i=0;i<v.size();i+=2){\n p->data=v[i];\n p=p->next;\n }\n for(int i=1;i<=v.size() && p!=NULL;i+=2){\n p->data=v[i];\n p=p->next;\n }\n }" }, { "code": null, "e": 4663, "s": 4653, "text": "Read Less" }, { "code": null, "e": 4685, "s": 4663, "text": "Reply Open Externally" }, { "code": null, "e": 4687, "s": 4685, "text": "0" }, { "code": null, "e": 4699, "s": 4687, "text": "best code " }, { "code": null, "e": 4702, "s": 4699, "text": "+3" }, { "code": null, "e": 4722, "s": 4702, "text": "tanashah3 weeks ago" }, { "code": null, "e": 4811, "s": 4722, "text": "Guys it is,all odd position nodes are together and all even positions node are together." }, { "code": null, "e": 4845, "s": 4811, "text": "Not a odd number and even number." }, { "code": null, "e": 4848, "s": 4845, "text": "+2" }, { "code": null, "e": 4876, "s": 4848, "text": "badgujarsachin834 weeks ago" }, { "code": null, "e": 5412, "s": 4876, "text": "void rearrangeEvenOdd(Node *head)\n {\n // Your Code here\n Node* even=new Node(0);\n Node* odd=new Node(0);\n Node* e=even;\n Node* temp=head;\n Node* o=odd;\n int c=1;\n while(temp){\n if(c%2!=0){\n o->next=temp;\n o=o->next;\n }else{\n e->next=temp;\n e=e->next;\n }\n temp=temp->next;\n c++;\n }\n o->next=NULL;\n e->next=NULL;\n o->next=even->next;\n head=odd;\n }" }, { "code": null, "e": 5414, "s": 5412, "text": "0" }, { "code": null, "e": 5430, "s": 5414, "text": "hr061 month ago" }, { "code": null, "e": 6003, "s": 5430, "text": "class Solution\n{\n public:\n void rearrangeEvenOdd(Node *head)\n {\n // Your Code here\n \n if(head == NULL || head->next == NULL)\n {\n return;\n }\n \n Node* odd = head;\n Node* oddH = odd;\n Node* even = head->next;\n Node* evenH = even;\n \n while(odd->next && even->next)\n {\n odd->next = odd->next->next;\n even->next = even->next->next;\n \n odd = odd->next;\n even = even->next;\n }\n \n odd->next = evenH;\n head = oddH;\n \n \n }\n};" }, { "code": null, "e": 6005, "s": 6003, "text": "0" }, { "code": null, "e": 6038, "s": 6005, "text": "rohanjaiswal200120182 months ago" }, { "code": null, "e": 6487, "s": 6038, "text": "void rearrangeEvenOdd(Node *head) { // Your Code here Node* even=new Node(0); Node* odd=new Node(0); Node* temp=head, *e=even, *o=odd; int c=1; while(temp){ if(c%2!=0){ o->next=temp;o=o->next; } else{ e->next=temp;e=e->next; } c++;temp=temp->next; } o->next==NULL;e->next=NULL; o->next=even->next; head=odd; }" }, { "code": null, "e": 6936, "s": 6487, "text": "void rearrangeEvenOdd(Node *head) { // Your Code here Node* even=new Node(0); Node* odd=new Node(0); Node* temp=head, *e=even, *o=odd; int c=1; while(temp){ if(c%2!=0){ o->next=temp;o=o->next; } else{ e->next=temp;e=e->next; } c++;temp=temp->next; } o->next==NULL;e->next=NULL; o->next=even->next; head=odd; }" }, { "code": null, "e": 6938, "s": 6936, "text": "0" }, { "code": null, "e": 6960, "s": 6938, "text": "lakshta192 months ago" }, { "code": null, "e": 7341, "s": 6960, "text": " void rearrangeEvenOdd(Node *head)\n {\n Node *p=head;\n vector<int>v;\n while(p){\n v.push_back(p->data);\n p=p->next;\n }\n p=head;\n for(int i=0;i<v.size();i+=2){\n p->data=v[i];\n p=p->next;\n }\n for(int i=1;i<=v.size() && p!=NULL;i+=2){\n p->data=v[i];\n p=p->next;\n }\n }" }, { "code": null, "e": 7487, "s": 7341, "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": 7523, "s": 7487, "text": " Login to access your submissions. " }, { "code": null, "e": 7533, "s": 7523, "text": "\nProblem\n" }, { "code": null, "e": 7543, "s": 7533, "text": "\nContest\n" }, { "code": null, "e": 7606, "s": 7543, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 7754, "s": 7606, "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": 7962, "s": 7754, "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": 8068, "s": 7962, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Group by JavaScript Array Object
Suppose we have an array of arrays that contains the marks of some students in some subjects like this βˆ’ const arr = [ ["English", 52], ["Hindi", 154], ["Hindi", 241], ["Spanish", 10], ["French", 65], ["German", 98], ["Russian", 10] ]; We are required to write a JavaScript function that takes in one such array and returns an object of objects. The return object should contain an object for each unique subject, and that object should contain information like the number of appearances of that language, sum of total marks and the average. The code for this will be βˆ’ const arr = [ ["English", 52], ["Hindi", 154], ["Hindi", 241], ["Spanish", 10], ["French", 65], ["German", 98], ["Russian", 10] ]; const groupSubjects = arr => { const grouped = arr.reduce((acc, val) => { const [key, total] = val; if(!acc.hasOwnProperty(key)){ acc[key] = { 'count': 0, 'total': 0 }; }; const accuKey = acc[key]; accuKey['count']++; accuKey['total'] += total; accuKey['average'] = total / accuKey['count']; return acc; }, {}); return grouped; }; console.log(groupSubjects(arr)); And the output in the console will be βˆ’ { English: { count: 1, total: 52, average: 52 }, Hindi: { count: 2, total: 395, average: 120.5 }, Spanish: { count: 1, total: 10, average: 10 }, French: { count: 1, total: 65, average: 65 }, German: { count: 1, total: 98, average: 98 }, Russian: { count: 1, total: 10, average: 10 } }
[ { "code": null, "e": 1167, "s": 1062, "text": "Suppose we have an array of arrays that contains the marks of some students in some subjects like this βˆ’" }, { "code": null, "e": 1298, "s": 1167, "text": "const arr = [ [\"English\", 52], [\"Hindi\", 154], [\"Hindi\", 241], [\"Spanish\", 10], [\"French\", 65], [\"German\", 98], [\"Russian\", 10] ];" }, { "code": null, "e": 1408, "s": 1298, "text": "We are required to write a JavaScript function that takes in one such array and returns an object of objects." }, { "code": null, "e": 1604, "s": 1408, "text": "The return object should contain an object for each unique subject, and that object should contain information like the number of appearances of that language, sum of total marks and the average." }, { "code": null, "e": 1632, "s": 1604, "text": "The code for this will be βˆ’" }, { "code": null, "e": 2247, "s": 1632, "text": "const arr = [\n [\"English\", 52],\n [\"Hindi\", 154],\n [\"Hindi\", 241],\n [\"Spanish\", 10],\n [\"French\", 65],\n [\"German\", 98],\n [\"Russian\", 10]\n];\nconst groupSubjects = arr => {\n const grouped = arr.reduce((acc, val) => {\n const [key, total] = val;\n if(!acc.hasOwnProperty(key)){\n acc[key] = {\n 'count': 0,\n 'total': 0\n };\n };\n const accuKey = acc[key];\n accuKey['count']++;\n accuKey['total'] += total;\n accuKey['average'] = total / accuKey['count'];\n return acc;\n }, {});\n return grouped;\n};\nconsole.log(groupSubjects(arr));" }, { "code": null, "e": 2287, "s": 2247, "text": "And the output in the console will be βˆ’" }, { "code": null, "e": 2572, "s": 2287, "text": "{\nEnglish: { count: 1, total: 52, average: 52 },\nHindi: { count: 2, total: 395, average: 120.5 },\nSpanish: { count: 1, total: 10, average: 10 },\nFrench: { count: 1, total: 65, average: 65 },\nGerman: { count: 1, total: 98, average: 98 },\nRussian: { count: 1, total: 10, average: 10 }\n}" } ]
Count two different columns in a single query in MySQL?
You can use CASE statement to count two different columns in a single query. To understand the concept, let us first create a table. The query to create a table is as follows. mysql> create table CountDifferentDemo - > ( - > ProductId int NOT NULL AUTO_INCREMENT PRIMARY KEY, - > ProductName varchar(20), - > ProductColor varchar(20), - > ProductDescription varchar(20) - > ); Query OK, 0 rows affected (1.06 sec) Insert some records in the table using insert command. The query is as follows mysql> insert into CountDifferentDemo(ProductName,ProductColor,ProductDescription) values('Product-1','Red','Used'); Query OK, 1 row affected (0.46 sec) mysql> insert into CountDifferentDemo(ProductName,ProductColor,ProductDescription) values('Product-1','Blue','Used'); Query OK, 1 row affected (0.17 sec) mysql> insert into CountDifferentDemo(ProductName,ProductColor,ProductDescription) values('Product-2','Green','New'); Query OK, 1 row affected (0.12 sec) mysql> insert into CountDifferentDemo(ProductName,ProductColor,ProductDescription) values('Product-2','Blue','New'); Query OK, 1 row affected (0.14 sec) mysql> insert into CountDifferentDemo(ProductName,ProductColor,ProductDescription) values('Product-3','Green','New'); Query OK, 1 row affected (0.21 sec) mysql> insert into CountDifferentDemo(ProductName,ProductColor,ProductDescription) values('Product-4','Blue','Used'); Query OK, 1 row affected (0.20 sec) Display all records from the table using select statement. The query is as follows mysql> select *from CountDifferentDemo; The following is the output +-----------+-------------+--------------+--------------------+ | ProductId | ProductName | ProductColor | ProductDescription | +-----------+-------------+--------------+--------------------+ | 1 | Product-1 | Red | Used | | 2 | Product-1 | Blue | Used | | 3 | Product-2 | Green | New | | 4 | Product-2 | Blue | New | | 5 | Product-3 | Green | New | | 6 | Product-4 | Blue | Used | +-----------+-------------+--------------+--------------------+ 6 rows in set (0.01 sec) Here is the query to count two different columns in a single query i.e. we are counting the occurrence of a particular color β€œRed” and description β€œNew” mysql> select ProductName, - > SUM(CASE WHEN ProductColor = 'Red' THEN 1 ELSE 0 END) AS Color, - > SUM(CASE WHEN ProductDescription = 'New' THEN 1 ELSE 0 END) AS Desciption - > from CountDifferentDemo - > group by ProductName; The following is the output +-------------+-------+------------+ | ProductName | Color | Desciption | +-------------+-------+------------+ | Product-1 | 1 | 0 | | Product-2 | 0 | 2 | | Product-3 | 0 | 1 | | Product-4 | 0 | 0 | +-------------+-------+------------+ 4 rows in set (0.12 sec)
[ { "code": null, "e": 1238, "s": 1062, "text": "You can use CASE statement to count two different columns in a single query. To understand the concept, let us first create a table. The query to create a table is as follows." }, { "code": null, "e": 1494, "s": 1238, "text": "mysql> create table CountDifferentDemo\n - > (\n - > ProductId int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n - > ProductName varchar(20),\n - > ProductColor varchar(20),\n - > ProductDescription varchar(20)\n - > );\nQuery OK, 0 rows affected (1.06 sec)" }, { "code": null, "e": 1549, "s": 1494, "text": "Insert some records in the table using insert command." }, { "code": null, "e": 1573, "s": 1549, "text": "The query is as follows" }, { "code": null, "e": 2495, "s": 1573, "text": "mysql> insert into CountDifferentDemo(ProductName,ProductColor,ProductDescription) values('Product-1','Red','Used');\nQuery OK, 1 row affected (0.46 sec)\nmysql> insert into CountDifferentDemo(ProductName,ProductColor,ProductDescription) values('Product-1','Blue','Used');\nQuery OK, 1 row affected (0.17 sec)\nmysql> insert into CountDifferentDemo(ProductName,ProductColor,ProductDescription) values('Product-2','Green','New');\nQuery OK, 1 row affected (0.12 sec)\nmysql> insert into CountDifferentDemo(ProductName,ProductColor,ProductDescription) values('Product-2','Blue','New');\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into CountDifferentDemo(ProductName,ProductColor,ProductDescription) values('Product-3','Green','New');\nQuery OK, 1 row affected (0.21 sec)\nmysql> insert into CountDifferentDemo(ProductName,ProductColor,ProductDescription) values('Product-4','Blue','Used');\nQuery OK, 1 row affected (0.20 sec)" }, { "code": null, "e": 2554, "s": 2495, "text": "Display all records from the table using select statement." }, { "code": null, "e": 2578, "s": 2554, "text": "The query is as follows" }, { "code": null, "e": 2618, "s": 2578, "text": "mysql> select *from CountDifferentDemo;" }, { "code": null, "e": 2646, "s": 2618, "text": "The following is the output" }, { "code": null, "e": 3311, "s": 2646, "text": "+-----------+-------------+--------------+--------------------+\n| ProductId | ProductName | ProductColor | ProductDescription |\n+-----------+-------------+--------------+--------------------+\n| 1 | Product-1 | Red | Used |\n| 2 | Product-1 | Blue | Used |\n| 3 | Product-2 | Green | New |\n| 4 | Product-2 | Blue | New |\n| 5 | Product-3 | Green | New |\n| 6 | Product-4 | Blue | Used |\n+-----------+-------------+--------------+--------------------+\n6 rows in set (0.01 sec)" }, { "code": null, "e": 3464, "s": 3311, "text": "Here is the query to count two different columns in a single query i.e. we are counting the occurrence of a particular color β€œRed” and description β€œNew”" }, { "code": null, "e": 3703, "s": 3464, "text": "mysql> select ProductName,\n - > SUM(CASE WHEN ProductColor = 'Red' THEN 1 ELSE 0 END) AS Color,\n - > SUM(CASE WHEN ProductDescription = 'New' THEN 1 ELSE 0 END) AS Desciption\n - > from CountDifferentDemo\n - > group by ProductName;" }, { "code": null, "e": 3731, "s": 3703, "text": "The following is the output" }, { "code": null, "e": 4052, "s": 3731, "text": "+-------------+-------+------------+\n| ProductName | Color | Desciption |\n+-------------+-------+------------+\n| Product-1 | 1 | 0 |\n| Product-2 | 0 | 2 |\n| Product-3 | 0 | 1 |\n| Product-4 | 0 | 0 |\n+-------------+-------+------------+\n4 rows in set (0.12 sec)" } ]
How to set the background color of a column in a matplotlib table?
To set the background color of a column in a matplotlib table, we can take the following steps βˆ’ Set the figure size and adjust the padding between and around the subplots. Set the figure size and adjust the padding between and around the subplots. Make a tuple for columns attribute. Make a tuple for columns attribute. Make a list of lists, i.e., list of records. Make a list of lists, i.e., list of records. Make a list of lists, i.e., color of each cell. Make a list of lists, i.e., color of each cell. Create a figure and a set of subplots. Create a figure and a set of subplots. Add a table to an axes, ax. Add a table to an axes, ax. Turn off the axes. Turn off the axes. To display the figure, use show() method. To display the figure, use show() method. import matplotlib.pyplot as plt plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True columns = ('name', 'age', 'marks', 'salary') cell_text = [["John", "23", "98", "234"], ["James", "24", "90", "239"]] colors = [["red", "yellow", "blue", "green"], ["blue", "green", "yellow", "red"]] fig, ax = plt.subplots() the_table = ax.table(cellText=cell_text, cellColours=colors, colLabels=columns, loc='center') ax.axis('off') plt.show()
[ { "code": null, "e": 1159, "s": 1062, "text": "To set the background color of a column in a matplotlib table, we can take the following steps βˆ’" }, { "code": null, "e": 1235, "s": 1159, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1311, "s": 1235, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1347, "s": 1311, "text": "Make a tuple for columns attribute." }, { "code": null, "e": 1383, "s": 1347, "text": "Make a tuple for columns attribute." }, { "code": null, "e": 1428, "s": 1383, "text": "Make a list of lists, i.e., list of records." }, { "code": null, "e": 1473, "s": 1428, "text": "Make a list of lists, i.e., list of records." }, { "code": null, "e": 1521, "s": 1473, "text": "Make a list of lists, i.e., color of each cell." }, { "code": null, "e": 1569, "s": 1521, "text": "Make a list of lists, i.e., color of each cell." }, { "code": null, "e": 1608, "s": 1569, "text": "Create a figure and a set of subplots." }, { "code": null, "e": 1647, "s": 1608, "text": "Create a figure and a set of subplots." }, { "code": null, "e": 1675, "s": 1647, "text": "Add a table to an axes, ax." }, { "code": null, "e": 1703, "s": 1675, "text": "Add a table to an axes, ax." }, { "code": null, "e": 1722, "s": 1703, "text": "Turn off the axes." }, { "code": null, "e": 1741, "s": 1722, "text": "Turn off the axes." }, { "code": null, "e": 1783, "s": 1741, "text": "To display the figure, use show() method." }, { "code": null, "e": 1825, "s": 1783, "text": "To display the figure, use show() method." }, { "code": null, "e": 2296, "s": 1825, "text": "import matplotlib.pyplot as plt\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\ncolumns = ('name', 'age', 'marks', 'salary')\n\ncell_text = [[\"John\", \"23\", \"98\", \"234\"], [\"James\", \"24\", \"90\", \"239\"]]\n\ncolors = [[\"red\", \"yellow\", \"blue\", \"green\"], [\"blue\", \"green\", \"yellow\", \"red\"]]\n\nfig, ax = plt.subplots()\n\nthe_table = ax.table(cellText=cell_text, cellColours=colors, colLabels=columns, loc='center')\n\nax.axis('off')\n\nplt.show()" } ]
Reverse Level Order Traversal | Practice | GeeksforGeeks
Given a binary tree of size N, find its reverse level order traversal. ie- the traversal must begin from the last level. Example 1: Input : 1 / \ 3 2 Output: 3 2 1 Explanation: Traversing level 1 : 3 2 Traversing level 0 : 1 Example 2: Input : 10 / \ 20 30 / \ 40 60 Output: 40 60 20 30 10 Explanation: Traversing level 2 : 40 60 Traversing level 1 : 20 30 Traversing level 0 : 10 Your Task: You dont need to read input or print anything. Complete the function reverseLevelOrder() which takes the root of the tree as input parameter and returns a list containing the reverse level order traversal of the given tree. Expected Time Complexity: O(N) Expected Auxiliary Space: O(N) Constraints: 1 ≀ N ≀ 10^4 0 sibajit1176be20 This comment was deleted. 0 namangoel8016 days ago EASIEST SOLUTION SMALL CHANGE IN NORMAL LEVEL ORDER TRAVERSAL class Tree { public ArrayList<Integer> reverseLevelOrder(Node node) { Queue<Node> q = new LinkedList<>(); ArrayList<Integer> al = new ArrayList<>(); q.add(node); while(q.size()!=0){ Node rem = q.remove(); al.add(0,rem.data); if(rem.right!=null) q.add(rem.right); if(rem.left!=null) q.add(rem.left); } return al; } } 0 aishapervin032 weeks ago vector<int> reverseLevelOrder(Node *root) { vector<int>ans; stack<vector<int>>st; queue<Node*>q; q.push(root); vector<int>t; while(q.size()>0) { int n=q.size(); while(n--) { Node* temp=q.front(); q.pop(); t.push_back(temp->data); if(temp->left) q.push(temp->left); if(temp->right) q.push(temp->right); } st.push(t); t.clear(); } while(st.size()>0) { for(int i=0;i<st.top().size();i++) ans.push_back(st.top()[i]); st.pop(); } return ans; } 0 rawatchirag7122 weeks ago vector<int> reverseLevelOrder(Node *root){ vector<int>v; queue<Node *>q; q.push(root); while(!q.empty()){ Node *temp=q.front(); q.pop(); if(temp->right) { q.push(temp->right); } if(temp->left) { q.push(temp->left); } v.push_back(temp->data); } reverse(v.begin(),v.end()); return v;} -1 mnsjhansi3 weeks ago def reverseLevelOrder(root): # code here queue = [] ans = [] queue.append(root) while len(queue) > 0: node = queue.pop(0) ans.append(node.data) if node.right is not None: queue.append(node.right) if node.left is not None: queue.append(node.left) return ans[::-1] 0 jainmuskan5653 weeks ago vector<int> reverseLevelOrder(Node *root){ queue<Node *> q; stack<Node *> s; q.push(root); while(!q.empty()){ Node * temp= q.front(); q.pop(); s.push(temp); if(temp->right){ q.push(temp->right); } if(temp->left){ q.push(temp->left); } } vector<int>v; while(!s.empty()){ Node *temp= s.top(); s.pop(); v.push_back(temp->data); } return v; +2 sagrikasoni3 weeks ago class Tree { public ArrayList<Integer> reverseLevelOrder(Node node) { ArrayList<Integer> arr = new ArrayList<Integer>(); if(node==null) return arr; Queue<Node> q = new LinkedList<Node>(); q.add(node); while(!q.isEmpty()){ Node curr = q.poll(); arr.add(curr.data); if(curr.right!=null) q.add(curr.right); if(curr.left!=null) q.add(curr.left); } Collections.reverse(arr); return arr; 0 betulaltindis1 month ago //Java Solution class Tree{ public ArrayList<Integer> reverseLevelOrder(Node node) { ArrayList<Integer> list = new ArrayList<>(); Stack<Node> s= new Stack<Node>(); Queue<Node> q= new LinkedList<Node>(); q.add(node); while(q.size()!=0){ Node tempNode = q.poll(); s.push(tempNode); if(tempNode.right!= null) q.add(tempNode.right); if(tempNode.left!= null) q.add(tempNode.left); } while(s.size()!=0) list.add(s.pop().data); return list; }} 0 balkishanjaipal1 month ago C++ Solution vector<int> reverseLevelOrder(Node *root){ // code here //Your code here vector<int> v; queue<Node*> q; q.push(root); while(!q.empty()) { Node *f =q.front(); q.pop(); v.push_back(f->data); if(f->right) { q.push(f->right); } if(f->left) { q.push(f->left); } } reverse(v.begin() ,v.end()); return v;} 0 shkoli1 month ago void rotUtil(Node* root, vector<int> &vec) { if (root->left == NULL || root->right == NULL){ return; } rotUtil(root->left, vec); rotUtil(root->right, vec); vec.push_back(root->left->data); vec.push_back(root->right->data); } vector<int> reverseLevelOrder(Node *root) { // code here vector<int> vec; rotUtil(root, vec); vec.push_back(root->data); return vec; } 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": 360, "s": 238, "text": "Given a binary tree of size N, find its reverse level order traversal. ie- the traversal must begin from the last level. " }, { "code": null, "e": 371, "s": 360, "text": "Example 1:" }, { "code": null, "e": 490, "s": 371, "text": "Input :\n 1\n / \\\n 3 2\n\nOutput: 3 2 1\nExplanation:\nTraversing level 1 : 3 2\nTraversing level 0 : 1" }, { "code": null, "e": 501, "s": 490, "text": "Example 2:" }, { "code": null, "e": 677, "s": 501, "text": "Input :\n 10\n / \\\n 20 30\n / \\ \n 40 60\n\nOutput: 40 60 20 30 10\nExplanation:\nTraversing level 2 : 40 60\nTraversing level 1 : 20 30\nTraversing level 0 : 10" }, { "code": null, "e": 915, "s": 677, "text": "\nYour Task: \nYou dont need to read input or print anything. Complete the function reverseLevelOrder() which takes the root of the tree as input parameter and returns a list containing the reverse level order traversal of the given tree." }, { "code": null, "e": 978, "s": 915, "text": "\nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(N)" }, { "code": null, "e": 1005, "s": 978, "text": "\nConstraints:\n1 ≀ N ≀ 10^4" }, { "code": null, "e": 1007, "s": 1005, "text": "0" }, { "code": null, "e": 1023, "s": 1007, "text": "sibajit1176be20" }, { "code": null, "e": 1049, "s": 1023, "text": "This comment was deleted." }, { "code": null, "e": 1051, "s": 1049, "text": "0" }, { "code": null, "e": 1074, "s": 1051, "text": "namangoel8016 days ago" }, { "code": null, "e": 1568, "s": 1074, "text": "EASIEST SOLUTION\nSMALL CHANGE IN NORMAL LEVEL ORDER TRAVERSAL\n\nclass Tree\n{\n public ArrayList<Integer> reverseLevelOrder(Node node) \n {\n Queue<Node> q = new LinkedList<>();\n ArrayList<Integer> al = new ArrayList<>();\n q.add(node);\n while(q.size()!=0){\n Node rem = q.remove();\n al.add(0,rem.data);\n if(rem.right!=null) q.add(rem.right);\n if(rem.left!=null) q.add(rem.left);\n }\n return al;\n }\n} " }, { "code": null, "e": 1570, "s": 1568, "text": "0" }, { "code": null, "e": 1595, "s": 1570, "text": "aishapervin032 weeks ago" }, { "code": null, "e": 2384, "s": 1595, "text": "vector<int> reverseLevelOrder(Node *root)\n{\n vector<int>ans;\n stack<vector<int>>st;\n queue<Node*>q;\n q.push(root);\n vector<int>t;\n while(q.size()>0)\n {\n int n=q.size();\n \n while(n--)\n { \n \n Node* temp=q.front();\n q.pop();\n t.push_back(temp->data);\n \n if(temp->left)\n q.push(temp->left);\n \n if(temp->right)\n q.push(temp->right);\n \n }\n st.push(t);\n t.clear();\n }\n while(st.size()>0)\n {\n for(int i=0;i<st.top().size();i++)\n ans.push_back(st.top()[i]);\n st.pop();\n \n }\n return ans;\n}" }, { "code": null, "e": 2386, "s": 2384, "text": "0" }, { "code": null, "e": 2412, "s": 2386, "text": "rawatchirag7122 weeks ago" }, { "code": null, "e": 2570, "s": 2412, "text": "vector<int> reverseLevelOrder(Node *root){ vector<int>v; queue<Node *>q; q.push(root); while(!q.empty()){ Node *temp=q.front();" }, { "code": null, "e": 2857, "s": 2570, "text": " q.pop(); if(temp->right) { q.push(temp->right); } if(temp->left) { q.push(temp->left); } v.push_back(temp->data); } reverse(v.begin(),v.end()); return v;}" }, { "code": null, "e": 2860, "s": 2857, "text": "-1" }, { "code": null, "e": 2881, "s": 2860, "text": "mnsjhansi3 weeks ago" }, { "code": null, "e": 3234, "s": 2881, "text": "def reverseLevelOrder(root):\n # code here\n queue = []\n ans = []\n queue.append(root)\n \n while len(queue) > 0:\n node = queue.pop(0)\n ans.append(node.data)\n if node.right is not None:\n queue.append(node.right)\n if node.left is not None:\n queue.append(node.left)\n \n return ans[::-1]" }, { "code": null, "e": 3236, "s": 3234, "text": "0" }, { "code": null, "e": 3261, "s": 3236, "text": "jainmuskan5653 weeks ago" }, { "code": null, "e": 3703, "s": 3261, "text": "vector<int> reverseLevelOrder(Node *root){ queue<Node *> q; stack<Node *> s; q.push(root); while(!q.empty()){ Node * temp= q.front(); q.pop(); s.push(temp); if(temp->right){ q.push(temp->right); } if(temp->left){ q.push(temp->left); } } vector<int>v; while(!s.empty()){ Node *temp= s.top(); s.pop(); v.push_back(temp->data); } return v;" }, { "code": null, "e": 3706, "s": 3703, "text": "+2" }, { "code": null, "e": 3729, "s": 3706, "text": "sagrikasoni3 weeks ago" }, { "code": null, "e": 4240, "s": 3729, "text": "class Tree\n{\n public ArrayList<Integer> reverseLevelOrder(Node node) \n {\n ArrayList<Integer> arr = new ArrayList<Integer>();\n if(node==null) return arr;\n Queue<Node> q = new LinkedList<Node>();\n q.add(node);\n while(!q.isEmpty()){\n Node curr = q.poll();\n arr.add(curr.data);\n if(curr.right!=null)\n q.add(curr.right);\n if(curr.left!=null)\n q.add(curr.left);\n }\n Collections.reverse(arr);\n return arr;" }, { "code": null, "e": 4242, "s": 4240, "text": "0" }, { "code": null, "e": 4267, "s": 4242, "text": "betulaltindis1 month ago" }, { "code": null, "e": 4283, "s": 4267, "text": "//Java Solution" }, { "code": null, "e": 4881, "s": 4285, "text": "class Tree{ public ArrayList<Integer> reverseLevelOrder(Node node) { ArrayList<Integer> list = new ArrayList<>(); Stack<Node> s= new Stack<Node>(); Queue<Node> q= new LinkedList<Node>(); q.add(node); while(q.size()!=0){ Node tempNode = q.poll(); s.push(tempNode); if(tempNode.right!= null) q.add(tempNode.right); if(tempNode.left!= null) q.add(tempNode.left); } while(s.size()!=0) list.add(s.pop().data); return list; }} " }, { "code": null, "e": 4883, "s": 4881, "text": "0" }, { "code": null, "e": 4910, "s": 4883, "text": "balkishanjaipal1 month ago" }, { "code": null, "e": 4925, "s": 4912, "text": "C++ Solution" }, { "code": null, "e": 5411, "s": 4925, "text": "vector<int> reverseLevelOrder(Node *root){ // code here //Your code here vector<int> v; queue<Node*> q; q.push(root); while(!q.empty()) { Node *f =q.front(); q.pop(); v.push_back(f->data); if(f->right) { q.push(f->right); } if(f->left) { q.push(f->left); } } reverse(v.begin() ,v.end()); return v;}" }, { "code": null, "e": 5413, "s": 5411, "text": "0" }, { "code": null, "e": 5431, "s": 5413, "text": "shkoli1 month ago" }, { "code": null, "e": 5474, "s": 5431, "text": "void rotUtil(Node* root, vector<int> &vec)" }, { "code": null, "e": 5476, "s": 5474, "text": "{" }, { "code": null, "e": 5528, "s": 5476, "text": " if (root->left == NULL || root->right == NULL){" }, { "code": null, "e": 5544, "s": 5528, "text": " return;" }, { "code": null, "e": 5550, "s": 5544, "text": " }" }, { "code": null, "e": 5580, "s": 5550, "text": " rotUtil(root->left, vec);" }, { "code": null, "e": 5611, "s": 5580, "text": " rotUtil(root->right, vec);" }, { "code": null, "e": 5648, "s": 5611, "text": " vec.push_back(root->left->data);" }, { "code": null, "e": 5686, "s": 5648, "text": " vec.push_back(root->right->data);" }, { "code": null, "e": 5692, "s": 5690, "text": "}" }, { "code": null, "e": 5736, "s": 5694, "text": "vector<int> reverseLevelOrder(Node *root)" }, { "code": null, "e": 5738, "s": 5736, "text": "{" }, { "code": null, "e": 5755, "s": 5738, "text": " // code here" }, { "code": null, "e": 5776, "s": 5755, "text": " vector<int> vec;" }, { "code": null, "e": 5799, "s": 5776, "text": " rotUtil(root, vec);" }, { "code": null, "e": 5829, "s": 5799, "text": " vec.push_back(root->data);" }, { "code": null, "e": 5845, "s": 5829, "text": " return vec;" }, { "code": null, "e": 5847, "s": 5845, "text": "}" }, { "code": null, "e": 5993, "s": 5847, "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": 6029, "s": 5993, "text": " Login to access your submissions. " }, { "code": null, "e": 6039, "s": 6029, "text": "\nProblem\n" }, { "code": null, "e": 6049, "s": 6039, "text": "\nContest\n" }, { "code": null, "e": 6112, "s": 6049, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 6260, "s": 6112, "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": 6468, "s": 6260, "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": 6574, "s": 6468, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
PostgreSQL – LEFT JOIN
28 Aug, 2020 The PostgreSQL LEFT JOIN returns all the rows of the table on the left side of the join and matching rows for the table on the right side of the join. The rows for which there is no matching row on the right side, the result-set will contain null. LEFT JOIN is also known as LEFT OUTER JOIN. Syntax: SELECT table1.column1, table1.column2, table2.column1, .... FROM table1 LEFT JOIN table2 ON table1.matching_column = table2.matching_column; table1: First table. table2: Second table matching_column: Column common to both the tables. Let’s analyze the above syntax: Firstly, using the SELECT statement we specify the tables from where we want the data to be selected. Second, we specify the main table. Third, we specify the table that the main table joins to. The below Venn Diagram illustrates the working of PostgreSQL LEFT JOIN clause: For the sake of this article we will be using the sample DVD rental database, which is explained here and can be downloaded by clicking on this link in our examples. Now, let’s look into a few examples. Example 1:Here we will use the LEFT JOIN clause to join the β€œfilm” table to the β€œinventory” table. SELECT film.film_id, film.title, inventory_id FROM film LEFT JOIN inventory ON inventory.film_id = film.film_id; Output: Example 2:Here we will use the LEFT JOIN clause to join the β€œfilm” table to the β€œinventory” table and use the WHERE clause to filter out films that are not in the inventory supply. SELECT film.film_id, film.title, inventory_id FROM film LEFT JOIN inventory ON inventory.film_id = film.film_id WHERE inventory.film_id IS NULL; Output: postgreSQL-joins PostgreSQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Aug, 2020" }, { "code": null, "e": 320, "s": 28, "text": "The PostgreSQL LEFT JOIN returns all the rows of the table on the left side of the join and matching rows for the table on the right side of the join. The rows for which there is no matching row on the right side, the result-set will contain null. LEFT JOIN is also known as LEFT OUTER JOIN." }, { "code": null, "e": 565, "s": 320, "text": "Syntax:\nSELECT table1.column1, table1.column2, table2.column1, ....\nFROM table1 \nLEFT JOIN table2\nON table1.matching_column = table2.matching_column;\n\n\ntable1: First table.\ntable2: Second table\nmatching_column: Column common to both the tables." }, { "code": null, "e": 597, "s": 565, "text": "Let’s analyze the above syntax:" }, { "code": null, "e": 699, "s": 597, "text": "Firstly, using the SELECT statement we specify the tables from where we want the data to be selected." }, { "code": null, "e": 734, "s": 699, "text": "Second, we specify the main table." }, { "code": null, "e": 792, "s": 734, "text": "Third, we specify the table that the main table joins to." }, { "code": null, "e": 871, "s": 792, "text": "The below Venn Diagram illustrates the working of PostgreSQL LEFT JOIN clause:" }, { "code": null, "e": 1037, "s": 871, "text": "For the sake of this article we will be using the sample DVD rental database, which is explained here and can be downloaded by clicking on this link in our examples." }, { "code": null, "e": 1074, "s": 1037, "text": "Now, let’s look into a few examples." }, { "code": null, "e": 1173, "s": 1074, "text": "Example 1:Here we will use the LEFT JOIN clause to join the β€œfilm” table to the β€œinventory” table." }, { "code": null, "e": 1302, "s": 1173, "text": "SELECT\n film.film_id,\n film.title,\n inventory_id\nFROM\n film\nLEFT JOIN inventory ON inventory.film_id = film.film_id;" }, { "code": null, "e": 1310, "s": 1302, "text": "Output:" }, { "code": null, "e": 1491, "s": 1310, "text": "Example 2:Here we will use the LEFT JOIN clause to join the β€œfilm” table to the β€œinventory” table and use the WHERE clause to filter out films that are not in the inventory supply." }, { "code": null, "e": 1656, "s": 1491, "text": "SELECT\n film.film_id,\n film.title,\n inventory_id\nFROM\n film\nLEFT JOIN inventory ON inventory.film_id = film.film_id\nWHERE\n inventory.film_id IS NULL;" }, { "code": null, "e": 1664, "s": 1656, "text": "Output:" }, { "code": null, "e": 1681, "s": 1664, "text": "postgreSQL-joins" }, { "code": null, "e": 1692, "s": 1681, "text": "PostgreSQL" } ]
Moment.js isBefore() Function
24 Jul, 2020 It is used to check whether a date is before a particular date in Node.js using the isBefore() function that checks if a moment is before another moment. The first argument will be parsed as a moment, if not already so. Syntax: moment().isBefore(Moment|String|Number|Date|Array); moment().isBefore(Moment|String|Number|Date|Array, String); Parameter: It can holds either Moment|String|Number|Date|Array. Returns: True or False Installation of moment module: You can visit the link to Install moment module. You can install this package by using this command.npm install momentAfter installing the moment module, you can check your moment version in command prompt using the command.npm version momentAfter that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js You can visit the link to Install moment module. You can install this package by using this command.npm install moment npm install moment After installing the moment module, you can check your moment version in command prompt using the command.npm version moment npm version moment After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js node index.js Example 1: Filename: index.js // Requiring moduleconst moment = require('moment'); var bool1 = moment('2010-10-20') .isBefore('2010-10-21'); // trueconsole.log(bool1); var bool2 = moment('2010-10-20') .isBefore('2010-12-31', 'year'); // falseconsole.log(bool2); Steps to run the program: The project structure will look like this:Make sure you have installed moment module using the following command:npm install momentRun index.js file using below command:node index.jsOutput:true false The project structure will look like this: Make sure you have installed moment module using the following command:npm install moment npm install moment Run index.js file using below command:node index.jsOutput:true false node index.js Output: true false Example 2: Filename: index.js // Requiring moduleconst moment = require('moment'); function checkIsBefore(date1, date2) { return moment(date1).isBefore(date2); } var bool = checkIsBefore('2010-10-20', '2010-10-21');console.log(bool); Run index.js file using below command: node index.js Output: true Reference: https://momentjs.com/docs/#/query/is-before/ Moment.js Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Node.js fs.writeFile() Method How to install the previous version of node.js and npm ? Difference between promise and async await in Node.js Mongoose | findByIdAndUpdate() Function JWT Authentication with Node.js Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Jul, 2020" }, { "code": null, "e": 248, "s": 28, "text": "It is used to check whether a date is before a particular date in Node.js using the isBefore() function that checks if a moment is before another moment. The first argument will be parsed as a moment, if not already so." }, { "code": null, "e": 256, "s": 248, "text": "Syntax:" }, { "code": null, "e": 369, "s": 256, "text": "moment().isBefore(Moment|String|Number|Date|Array);\nmoment().isBefore(Moment|String|Number|Date|Array, String);\n" }, { "code": null, "e": 433, "s": 369, "text": "Parameter: It can holds either Moment|String|Number|Date|Array." }, { "code": null, "e": 456, "s": 433, "text": "Returns: True or False" }, { "code": null, "e": 487, "s": 456, "text": "Installation of moment module:" }, { "code": null, "e": 877, "s": 487, "text": "You can visit the link to Install moment module. You can install this package by using this command.npm install momentAfter installing the moment module, you can check your moment version in command prompt using the command.npm version momentAfter that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js" }, { "code": null, "e": 996, "s": 877, "text": "You can visit the link to Install moment module. You can install this package by using this command.npm install moment" }, { "code": null, "e": 1015, "s": 996, "text": "npm install moment" }, { "code": null, "e": 1140, "s": 1015, "text": "After installing the moment module, you can check your moment version in command prompt using the command.npm version moment" }, { "code": null, "e": 1159, "s": 1140, "text": "npm version moment" }, { "code": null, "e": 1307, "s": 1159, "text": "After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js" }, { "code": null, "e": 1321, "s": 1307, "text": "node index.js" }, { "code": null, "e": 1351, "s": 1321, "text": "Example 1: Filename: index.js" }, { "code": "// Requiring moduleconst moment = require('moment'); var bool1 = moment('2010-10-20') .isBefore('2010-10-21'); // trueconsole.log(bool1); var bool2 = moment('2010-10-20') .isBefore('2010-12-31', 'year'); // falseconsole.log(bool2);", "e": 1591, "s": 1351, "text": null }, { "code": null, "e": 1617, "s": 1591, "text": "Steps to run the program:" }, { "code": null, "e": 1818, "s": 1617, "text": "The project structure will look like this:Make sure you have installed moment module using the following command:npm install momentRun index.js file using below command:node index.jsOutput:true\nfalse\n" }, { "code": null, "e": 1861, "s": 1818, "text": "The project structure will look like this:" }, { "code": null, "e": 1951, "s": 1861, "text": "Make sure you have installed moment module using the following command:npm install moment" }, { "code": null, "e": 1970, "s": 1951, "text": "npm install moment" }, { "code": null, "e": 2040, "s": 1970, "text": "Run index.js file using below command:node index.jsOutput:true\nfalse\n" }, { "code": null, "e": 2054, "s": 2040, "text": "node index.js" }, { "code": null, "e": 2062, "s": 2054, "text": "Output:" }, { "code": null, "e": 2074, "s": 2062, "text": "true\nfalse\n" }, { "code": null, "e": 2104, "s": 2074, "text": "Example 2: Filename: index.js" }, { "code": "// Requiring moduleconst moment = require('moment'); function checkIsBefore(date1, date2) { return moment(date1).isBefore(date2); } var bool = checkIsBefore('2010-10-20', '2010-10-21');console.log(bool);", "e": 2313, "s": 2104, "text": null }, { "code": null, "e": 2352, "s": 2313, "text": "Run index.js file using below command:" }, { "code": null, "e": 2366, "s": 2352, "text": "node index.js" }, { "code": null, "e": 2374, "s": 2366, "text": "Output:" }, { "code": null, "e": 2380, "s": 2374, "text": "true\n" }, { "code": null, "e": 2436, "s": 2380, "text": "Reference: https://momentjs.com/docs/#/query/is-before/" }, { "code": null, "e": 2446, "s": 2436, "text": "Moment.js" }, { "code": null, "e": 2454, "s": 2446, "text": "Node.js" }, { "code": null, "e": 2471, "s": 2454, "text": "Web Technologies" }, { "code": null, "e": 2569, "s": 2471, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2599, "s": 2569, "text": "Node.js fs.writeFile() Method" }, { "code": null, "e": 2656, "s": 2599, "text": "How to install the previous version of node.js and npm ?" }, { "code": null, "e": 2710, "s": 2656, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 2750, "s": 2710, "text": "Mongoose | findByIdAndUpdate() Function" }, { "code": null, "e": 2782, "s": 2750, "text": "JWT Authentication with Node.js" }, { "code": null, "e": 2844, "s": 2782, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2905, "s": 2844, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2955, "s": 2905, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 2998, "s": 2955, "text": "How to fetch data from an API in ReactJS ?" } ]
Namespacing in JavaScript
22 Feb, 2021 JavaScript by default lacks namespaces however, we can use objects to create namespaces. A nested namespace is a namespace inside another namespace. In JavaScript, we can define a nested namespace by creating an object inside another object. JavaScript Namespaces: Namespace refers to the programming paradigm of providing scope to the identifiers (names of types, functions, variables, etc) to prevent collisions between them. For instance, the same variable name might be required in a program in different contexts. Example: An HTML file, in which we are calling two JavaScript files, namespace1.js, and namespace2.js where. namespace1.js Handling an event of changing the background color to β€˜yellow’ and text color to β€˜grey’ on pointing the mouse pointer to the <div> element. namespace1.js Handling an event of changing the background color to β€˜yellow’ and text color to β€˜grey’ on pointing the mouse pointer to the <div> element. namespace2.js Handling an event of changing the background color to β€˜pink’ and text color to β€˜charcoal’ on moving the mouse pointer away from the <div> element. namespace2.js Handling an event of changing the background color to β€˜pink’ and text color to β€˜charcoal’ on moving the mouse pointer away from the <div> element. HTML <!DOCTYPE html><html> <head> <meta charset="UTF-8" /> <title>Namespacing in JavaScript</title> </head> <body> <div id="output">This is the div</div> <script src="./namespace1.js"></script> <script src="./namespace2.js"></script> </body></html> namespace1.js let MAC = { colorDiv: function(ev){ let target = ev.currentTarget; target.style.backgroundColor = 'yellow'; target.style.color = '#808080'; }, init: function(){ let divA = document.getElementById('output'); divA.addEventListener('mouseover', MAC.colorDiv); }} MAC.init(); namespace2.js let WIN = { colorDiv: function(ev){ let target = ev.currentTarget; target.style.backgroundColor = 'pink'; target.style.color = '#36454F'; }, init: function(){ let divB = document.getElementById('output'); divB.addEventListener('mouseout', this.colorDiv); }} WIN.init(); Output: On pointing the mouse pointer to the <div> element. On pointing the mouse pointer to the <div> element. On moving the mouse pointer away from the <div> element. On moving the mouse pointer away from the <div> element. If namespaces are not used then there occurs an error of using the same function in two or more JavaScript files because functions in JavaScript are declared globally. In our case, β€˜colorDiv’ function is used both in namespace1.js and namespace2.js. If namespaces are not used in the above example then it will throw an error: β€œUncaught SyntaxError: Identifier β€˜colorDiv’ has already been declared at namespace2.js”. JavaScript-Questions Picked JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Remove elements from a JavaScript Array Difference Between PUT and PATCH Request Roadmap to Learn JavaScript For Beginners JavaScript | Promises Top 10 Projects For Beginners To Practice HTML and CSS Skills Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Feb, 2021" }, { "code": null, "e": 270, "s": 28, "text": "JavaScript by default lacks namespaces however, we can use objects to create namespaces. A nested namespace is a namespace inside another namespace. In JavaScript, we can define a nested namespace by creating an object inside another object." }, { "code": null, "e": 547, "s": 270, "text": "JavaScript Namespaces: Namespace refers to the programming paradigm of providing scope to the identifiers (names of types, functions, variables, etc) to prevent collisions between them. For instance, the same variable name might be required in a program in different contexts." }, { "code": null, "e": 656, "s": 547, "text": "Example: An HTML file, in which we are calling two JavaScript files, namespace1.js, and namespace2.js where." }, { "code": null, "e": 810, "s": 656, "text": "namespace1.js Handling an event of changing the background color to β€˜yellow’ and text color to β€˜grey’ on pointing the mouse pointer to the <div> element." }, { "code": null, "e": 964, "s": 810, "text": "namespace1.js Handling an event of changing the background color to β€˜yellow’ and text color to β€˜grey’ on pointing the mouse pointer to the <div> element." }, { "code": null, "e": 1125, "s": 964, "text": "namespace2.js Handling an event of changing the background color to β€˜pink’ and text color to β€˜charcoal’ on moving the mouse pointer away from the <div> element." }, { "code": null, "e": 1286, "s": 1125, "text": "namespace2.js Handling an event of changing the background color to β€˜pink’ and text color to β€˜charcoal’ on moving the mouse pointer away from the <div> element." }, { "code": null, "e": 1291, "s": 1286, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <meta charset=\"UTF-8\" /> <title>Namespacing in JavaScript</title> </head> <body> <div id=\"output\">This is the div</div> <script src=\"./namespace1.js\"></script> <script src=\"./namespace2.js\"></script> </body></html>", "e": 1548, "s": 1291, "text": null }, { "code": null, "e": 1562, "s": 1548, "text": "namespace1.js" }, { "code": "let MAC = { colorDiv: function(ev){ let target = ev.currentTarget; target.style.backgroundColor = 'yellow'; target.style.color = '#808080'; }, init: function(){ let divA = document.getElementById('output'); divA.addEventListener('mouseover', MAC.colorDiv); }} MAC.init();", "e": 1890, "s": 1562, "text": null }, { "code": null, "e": 1904, "s": 1890, "text": "namespace2.js" }, { "code": "let WIN = { colorDiv: function(ev){ let target = ev.currentTarget; target.style.backgroundColor = 'pink'; target.style.color = '#36454F'; }, init: function(){ let divB = document.getElementById('output'); divB.addEventListener('mouseout', this.colorDiv); }} WIN.init();", "e": 2230, "s": 1904, "text": null }, { "code": null, "e": 2238, "s": 2230, "text": "Output:" }, { "code": null, "e": 2290, "s": 2238, "text": "On pointing the mouse pointer to the <div> element." }, { "code": null, "e": 2342, "s": 2290, "text": "On pointing the mouse pointer to the <div> element." }, { "code": null, "e": 2399, "s": 2342, "text": "On moving the mouse pointer away from the <div> element." }, { "code": null, "e": 2456, "s": 2399, "text": "On moving the mouse pointer away from the <div> element." }, { "code": null, "e": 2873, "s": 2456, "text": "If namespaces are not used then there occurs an error of using the same function in two or more JavaScript files because functions in JavaScript are declared globally. In our case, β€˜colorDiv’ function is used both in namespace1.js and namespace2.js. If namespaces are not used in the above example then it will throw an error: β€œUncaught SyntaxError: Identifier β€˜colorDiv’ has already been declared at namespace2.js”." }, { "code": null, "e": 2894, "s": 2873, "text": "JavaScript-Questions" }, { "code": null, "e": 2901, "s": 2894, "text": "Picked" }, { "code": null, "e": 2912, "s": 2901, "text": "JavaScript" }, { "code": null, "e": 2929, "s": 2912, "text": "Web Technologies" }, { "code": null, "e": 3027, "s": 2929, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3088, "s": 3027, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3128, "s": 3088, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 3169, "s": 3128, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 3211, "s": 3169, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 3233, "s": 3211, "text": "JavaScript | Promises" }, { "code": null, "e": 3295, "s": 3233, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3328, "s": 3295, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 3389, "s": 3328, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3439, "s": 3389, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Python | Multiply all numbers in the list (4 different ways)
14 Jun, 2022 Given a list, print the value obtained after multiplying all numbers in a list. Examples: Input : list1 = [1, 2, 3] Output : 6 Explanation: 1*2*3=6 Input : list1 = [3, 2, 4] Output : 24 Method 1: Traversal Initialize the value of the product to 1(not 0 as 0 multiplied with anything returns zero). Traverse till the end of the list, multiply every number with the product. The value stored in the product at the end will give you your final answer.Below is the Python implementation of the above approach: Python # Python program to multiply all values in the# list using traversal def multiplyList(myList) : # Multiply elements one by one result = 1 for x in myList: result = result * x return result # Driver codelist1 = [1, 2, 3]list2 = [3, 2, 4]print(multiplyList(list1))print(multiplyList(list2)) Output: 6 24 Method 2: Using numpy.prod() We can use numpy.prod() from import numpy to get the multiplication of all the numbers in the list. It returns an integer or a float value depending on the multiplication result.Below is the Python3 implementation of the above approach: Python3 # Python3 program to multiply all values in the# list using numpy.prod() import numpylist1 = [1, 2, 3]list2 = [3, 2, 4] # using numpy.prod() to get the multiplicationsresult1 = numpy.prod(list1)result2 = numpy.prod(list2)print(result1)print(result2) Output: 6 24 Method 3 Using lambda function: Using numpy.array Lambda’s definition does not include a β€œreturn” statement, it always contains an expression that is returned. We can also put a lambda definition anywhere a function is expected, and we don’t have to assign it to a variable at all. This is the simplicity of lambda functions. The reduce() function in Python takes in a function and a list as an argument. The function is called with a lambda function and a list and a new reduced result is returned. This performs a repetitive operation over the pairs of the list.Below is the Python3 implementation of the above approach: Python3 # Python3 program to multiply all values in the# list using lambda function and reduce() from functools import reducelist1 = [1, 2, 3]list2 = [3, 2, 4] result1 = reduce((lambda x, y: x * y), list1)result2 = reduce((lambda x, y: x * y), list2)print(result1)print(result2) Output: 6 24 Method 4 Using prod function of math library: Using math.prod Starting Python 3.8, a prod function has been included in the math module in the standard library, thus no need to install external libraries.Below is the Python3 implementation of the above approach: Python3 # Python3 program to multiply all values in the# list using math.prod import mathlist1 = [1, 2, 3]list2 = [3, 2, 4] result1 = math.prod(list1)result2 = math.prod(list2)print(result1)print(result2) Output: 6 24 Method 5: Using mul() function of operator module. First we have to import the operator module then using the mul() function of operator module multiplying the all values in the list. Python3 # Python 3 program to multiply all numbers in# the given list by importing operator module from operator import*list1 = [1, 2, 3]m = 0for i in list1: # multiplying all elements in the given list # using mul function of operator module m = mul(i, 1)+m# printing the resultprint(m) 6 naumannaeem414 hapa18ec laxmigangarajula03 Python list-programs python-list Python-numpy Python python-list 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 Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Convert integer to string in Python Introduction To PYTHON
[ { "code": null, "e": 52, "s": 24, "text": "\n14 Jun, 2022" }, { "code": null, "e": 144, "s": 52, "text": "Given a list, print the value obtained after multiplying all numbers in a list. Examples: " }, { "code": null, "e": 247, "s": 144, "text": "Input : list1 = [1, 2, 3] \nOutput : 6 \nExplanation: 1*2*3=6 \n\nInput : list1 = [3, 2, 4] \nOutput : 24 " }, { "code": null, "e": 271, "s": 251, "text": "Method 1: Traversal" }, { "code": null, "e": 573, "s": 271, "text": "Initialize the value of the product to 1(not 0 as 0 multiplied with anything returns zero). Traverse till the end of the list, multiply every number with the product. The value stored in the product at the end will give you your final answer.Below is the Python implementation of the above approach: " }, { "code": null, "e": 580, "s": 573, "text": "Python" }, { "code": "# Python program to multiply all values in the# list using traversal def multiplyList(myList) : # Multiply elements one by one result = 1 for x in myList: result = result * x return result # Driver codelist1 = [1, 2, 3]list2 = [3, 2, 4]print(multiplyList(list1))print(multiplyList(list2))", "e": 898, "s": 580, "text": null }, { "code": null, "e": 908, "s": 898, "text": "Output: " }, { "code": null, "e": 914, "s": 908, "text": "6\n24 " }, { "code": null, "e": 945, "s": 916, "text": "Method 2: Using numpy.prod()" }, { "code": null, "e": 1184, "s": 945, "text": "We can use numpy.prod() from import numpy to get the multiplication of all the numbers in the list. It returns an integer or a float value depending on the multiplication result.Below is the Python3 implementation of the above approach: " }, { "code": null, "e": 1192, "s": 1184, "text": "Python3" }, { "code": "# Python3 program to multiply all values in the# list using numpy.prod() import numpylist1 = [1, 2, 3]list2 = [3, 2, 4] # using numpy.prod() to get the multiplicationsresult1 = numpy.prod(list1)result2 = numpy.prod(list2)print(result1)print(result2)", "e": 1442, "s": 1192, "text": null }, { "code": null, "e": 1452, "s": 1442, "text": "Output: " }, { "code": null, "e": 1458, "s": 1452, "text": "6\n24 " }, { "code": null, "e": 1510, "s": 1460, "text": "Method 3 Using lambda function: Using numpy.array" }, { "code": null, "e": 2085, "s": 1510, "text": "Lambda’s definition does not include a β€œreturn” statement, it always contains an expression that is returned. We can also put a lambda definition anywhere a function is expected, and we don’t have to assign it to a variable at all. This is the simplicity of lambda functions. The reduce() function in Python takes in a function and a list as an argument. The function is called with a lambda function and a list and a new reduced result is returned. This performs a repetitive operation over the pairs of the list.Below is the Python3 implementation of the above approach: " }, { "code": null, "e": 2093, "s": 2085, "text": "Python3" }, { "code": "# Python3 program to multiply all values in the# list using lambda function and reduce() from functools import reducelist1 = [1, 2, 3]list2 = [3, 2, 4] result1 = reduce((lambda x, y: x * y), list1)result2 = reduce((lambda x, y: x * y), list2)print(result1)print(result2)", "e": 2365, "s": 2093, "text": null }, { "code": null, "e": 2375, "s": 2365, "text": "Output: " }, { "code": null, "e": 2381, "s": 2375, "text": "6\n24 " }, { "code": null, "e": 2445, "s": 2383, "text": "Method 4 Using prod function of math library: Using math.prod" }, { "code": null, "e": 2648, "s": 2445, "text": "Starting Python 3.8, a prod function has been included in the math module in the standard library, thus no need to install external libraries.Below is the Python3 implementation of the above approach: " }, { "code": null, "e": 2656, "s": 2648, "text": "Python3" }, { "code": "# Python3 program to multiply all values in the# list using math.prod import mathlist1 = [1, 2, 3]list2 = [3, 2, 4] result1 = math.prod(list1)result2 = math.prod(list2)print(result1)print(result2)", "e": 2854, "s": 2656, "text": null }, { "code": null, "e": 2864, "s": 2854, "text": "Output: " }, { "code": null, "e": 2870, "s": 2864, "text": "6\n24 " }, { "code": null, "e": 2922, "s": 2870, "text": "Method 5: Using mul() function of operator module. " }, { "code": null, "e": 3056, "s": 2922, "text": "First we have to import the operator module then using the mul() function of operator module multiplying the all values in the list. " }, { "code": null, "e": 3064, "s": 3056, "text": "Python3" }, { "code": "# Python 3 program to multiply all numbers in# the given list by importing operator module from operator import*list1 = [1, 2, 3]m = 0for i in list1: # multiplying all elements in the given list # using mul function of operator module m = mul(i, 1)+m# printing the resultprint(m)", "e": 3349, "s": 3064, "text": null }, { "code": null, "e": 3351, "s": 3349, "text": "6" }, { "code": null, "e": 3368, "s": 3353, "text": "naumannaeem414" }, { "code": null, "e": 3377, "s": 3368, "text": "hapa18ec" }, { "code": null, "e": 3396, "s": 3377, "text": "laxmigangarajula03" }, { "code": null, "e": 3417, "s": 3396, "text": "Python list-programs" }, { "code": null, "e": 3429, "s": 3417, "text": "python-list" }, { "code": null, "e": 3442, "s": 3429, "text": "Python-numpy" }, { "code": null, "e": 3449, "s": 3442, "text": "Python" }, { "code": null, "e": 3461, "s": 3449, "text": "python-list" }, { "code": null, "e": 3559, "s": 3461, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3577, "s": 3559, "text": "Python Dictionary" }, { "code": null, "e": 3619, "s": 3577, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 3641, "s": 3619, "text": "Enumerate() in Python" }, { "code": null, "e": 3667, "s": 3641, "text": "Python String | replace()" }, { "code": null, "e": 3699, "s": 3667, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3728, "s": 3699, "text": "*args and **kwargs in Python" }, { "code": null, "e": 3755, "s": 3728, "text": "Python Classes and Objects" }, { "code": null, "e": 3776, "s": 3755, "text": "Python OOPs Concepts" }, { "code": null, "e": 3812, "s": 3776, "text": "Convert integer to string in Python" } ]
How to Set Color of Progress Bar using HTML and CSS ?
06 Sep, 2020 The progress bar is an important element on the web, the progress bar can be used for downloading, marks obtained, skill measuring unit, etc. To create a progress bar we can use HTML and CSS. The progress bar is used to represent the progress of a task. It is also defined how much work is done and how much is left to download a thing. It is not used to represent the disk space or relevant query. Example 1: In this example, we will set the color of progress bar. HTML <!DOCTYPE html><html> <head> <title> How to Set Background Color of Progress Bar using HTML and CSS? </title> <style> /* For Firefox */ progress::-moz-progress-bar { background: green; } /* For Chrome or Safari */ progress::-webkit-progress-value { background: green; } /* For IE10 */ progress { background: green; } </style></head> <body> <h1 style="color:green;"> GeeksforGeeks </h1> <h4> Set Background Color of Progress Bar using HTML and CSS </h4> <progress value="40" max="100"></progress></body> </html> Output: Example 2: In this example, we will set the color and background color of progress bar. HTML <!DOCTYPE html><html> <head> <title> How to Set Background Color of Progress Bar using HTML and CSS? </title> <style> /* For Chrome or Safari */ progress::-webkit-progress-bar { background-color: #eeeeee; } progress::-webkit-progress-value { background-color: #039603 !important; } /* For Firefox */ progress { background-color: #eee; } progress::-moz-progress-bar { background-color: #039603 !important; } /* For IE10 */ progress { background-color: #eee; } progress { background-color: #039603; } </style></head> <body> <h1 style="color:green;"> GeeksforGeeks </h1> <h4> Set Background Color of Progress Bar using HTML and CSS? </h4> <progress value="40" max="100"></progress></body> </html> Output: CSS-Misc HTML-Misc CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Design a Tribute Page using HTML & CSS How to set space between the flexbox ? Build a Survey Form using HTML and CSS Form validation using jQuery Design a web page using HTML and CSS REST API (Introduction) Hide or show elements in HTML using display property How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? Design a Tribute Page using HTML & CSS
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Sep, 2020" }, { "code": null, "e": 221, "s": 28, "text": "The progress bar is an important element on the web, the progress bar can be used for downloading, marks obtained, skill measuring unit, etc. To create a progress bar we can use HTML and CSS. " }, { "code": null, "e": 428, "s": 221, "text": "The progress bar is used to represent the progress of a task. It is also defined how much work is done and how much is left to download a thing. It is not used to represent the disk space or relevant query." }, { "code": null, "e": 495, "s": 428, "text": "Example 1: In this example, we will set the color of progress bar." }, { "code": null, "e": 500, "s": 495, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title> How to Set Background Color of Progress Bar using HTML and CSS? </title> <style> /* For Firefox */ progress::-moz-progress-bar { background: green; } /* For Chrome or Safari */ progress::-webkit-progress-value { background: green; } /* For IE10 */ progress { background: green; } </style></head> <body> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <h4> Set Background Color of Progress Bar using HTML and CSS </h4> <progress value=\"40\" max=\"100\"></progress></body> </html>", "e": 1186, "s": 500, "text": null }, { "code": null, "e": 1194, "s": 1186, "text": "Output:" }, { "code": null, "e": 1282, "s": 1194, "text": "Example 2: In this example, we will set the color and background color of progress bar." }, { "code": null, "e": 1287, "s": 1282, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title> How to Set Background Color of Progress Bar using HTML and CSS? </title> <style> /* For Chrome or Safari */ progress::-webkit-progress-bar { background-color: #eeeeee; } progress::-webkit-progress-value { background-color: #039603 !important; } /* For Firefox */ progress { background-color: #eee; } progress::-moz-progress-bar { background-color: #039603 !important; } /* For IE10 */ progress { background-color: #eee; } progress { background-color: #039603; } </style></head> <body> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <h4> Set Background Color of Progress Bar using HTML and CSS? </h4> <progress value=\"40\" max=\"100\"></progress></body> </html>", "e": 2235, "s": 1287, "text": null }, { "code": null, "e": 2243, "s": 2235, "text": "Output:" }, { "code": null, "e": 2252, "s": 2243, "text": "CSS-Misc" }, { "code": null, "e": 2262, "s": 2252, "text": "HTML-Misc" }, { "code": null, "e": 2266, "s": 2262, "text": "CSS" }, { "code": null, "e": 2271, "s": 2266, "text": "HTML" }, { "code": null, "e": 2288, "s": 2271, "text": "Web Technologies" }, { "code": null, "e": 2293, "s": 2288, "text": "HTML" }, { "code": null, "e": 2391, "s": 2293, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2430, "s": 2391, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 2469, "s": 2430, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 2508, "s": 2469, "text": "Build a Survey Form using HTML and CSS" }, { "code": null, "e": 2537, "s": 2508, "text": "Form validation using jQuery" }, { "code": null, "e": 2574, "s": 2537, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 2598, "s": 2574, "text": "REST API (Introduction)" }, { "code": null, "e": 2651, "s": 2598, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 2711, "s": 2651, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 2772, "s": 2711, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" } ]
Rust Basics
04 Jul, 2022 In last 2 decades the computers and the internet has made an increasing demand, and with evolution of new technologies, devices and protocols the programming languages also being updated regularly but still most of the early programming languages like C, C++ have shown some drawbacks. These drawbacks motivated others to create new programming languages like Go, Rust, Python and more. In these tutorials we will talk about one of these programming languages.Rust language is intended for highly concurrent and highly safe system. Rust language has an emphasis on safety, control of memory layout and concurrency. Rust is a multi-paradigm programming language like C++ syntax was designed for performance and safety, especially safe concurrency by using a borrow checker and ownership to validate references. Rust was developed byGraydon Hoare at Mozilla research with contributions from Dave Herman, Brendan Eich and others. Which achieves memory safety without garbage collection. Rust is a compiled system programming language. Rust has many reasons for being popular among programmers. Below are the reasons are : Rust is Fast: Rust Programming Language is a multi-paradigm programming language similar to C++ syntax. Thus it becomes very easy to learn Rust for anyone. Across multiple platforms Rust code compiles to native machine code. Rust is Memory Safe: Rust inspires developer to write safe code. Unlike C, it does not provide memory unsafe thing like dangling pointer, uninitialized pointer and NULL pointer. Rust is Low-Overhead: InRust Programming Language all values have a unique owner, and the scope of the value is same as scope of the owner That’s why It has an ownership system. Rust is flexible: Rust is designed for performance and safety, especially safe concurrency by using a borrow checker and ownership to validate references. Rust is easy to use: Rust Programming Language syntax is similar to C++ language syntax so it is easy to use or easy to understand. Rust is statically and strongly typed: Rust is built in such a way that the code can is checked at compile time and if the compilation fails then there would be no accompanying extra memory usage. An example program in rust, saved with extension .rs RUST fn main() { println!("geeks for geeks");} Output: geeks for geeks We can Install Rust by using terminal. For linux and macOS open our terminal and use the curl which can automatically install rust for us, we can refer Rust docs for windows installation $ curl –proto β€˜=https’ –tlsv1.2 https://sh.rustup.rs -sSf | sh We can check whether we have Rust installed correctly, open a shell and enter this command $ rustc –version Rust Programming Language creating and maintaining boundaries that preserve large-system integrity. Rust is a multi-paradigm programming language. it is designed for safety and performance. There are some features which makes it different. Ownership: InRust Programming Language all values have a unique owner, and the scope of the value is same as scope of the owner That’s why It has an ownership system. Values can be passed by immutable reference and mutable reference, using &T and &mut T, or by value, using T. there are either be multiple immutable references or one mutable reference.Memory Safety: When it comes to memory safety, Rust inspires developer to write safe code. Unlike C, it does not provide memory unsafe thing like dangling pointer, uninitialized pointer and NULL pointer. Which in result, code becomes more safe and stable. It has define format to initialize data value. And similar to C, it does provide control to handle lifetime of a variable through added syntax. Apart from this it also provide flexibility to write unsafe code with unsafe keyword which Ideally should be avoided until there is no other way.Memory Management: A programmer’s performance also depends on how language manage memory internally. Rust works on RAII , unlike java’s garbage collection. Add on to this reference counting is also available to developer but that is optional. Ownership: InRust Programming Language all values have a unique owner, and the scope of the value is same as scope of the owner That’s why It has an ownership system. Values can be passed by immutable reference and mutable reference, using &T and &mut T, or by value, using T. there are either be multiple immutable references or one mutable reference. Memory Safety: When it comes to memory safety, Rust inspires developer to write safe code. Unlike C, it does not provide memory unsafe thing like dangling pointer, uninitialized pointer and NULL pointer. Which in result, code becomes more safe and stable. It has define format to initialize data value. And similar to C, it does provide control to handle lifetime of a variable through added syntax. Apart from this it also provide flexibility to write unsafe code with unsafe keyword which Ideally should be avoided until there is no other way. Memory Management: A programmer’s performance also depends on how language manage memory internally. Rust works on RAII , unlike java’s garbage collection. Add on to this reference counting is also available to developer but that is optional. Cargo is the Rust’s build system and package manager, like pip for Python, gem for Ruby and npm for Javascript. Cargo handles a lot of tasks, such as building and compiling your code, downloading the libraries your code depends on, and building those libraries(dependencies). Cargo mostly comes pre installed with Rust. You can check cargo from the below command, if you don’t see version number that means you haven’t installed cargo $ cargo –version We can create a new rust project using cargo, for that use the below commands. cargo new gfg cd gfg cargo new command creates a new cargo project in the specified directory. the directory contains, cargo.lock, cargo.toml, src files of the project. cargo.lock – lock file for the project cargo.toml – contains details and dependencies of the project, am example file is shown below. [package] name = β€œgfg” version = β€œ0.1.0” authors = [β€œYour Name <you@example.com>”] edition = β€œ2018” [dependencies] src – directory containing the source files of the project, main.rs file is main file for the project which will be created by default We can run the project using any of the below commands. // compiled out put cargo build // runs the compiled output cargo run // check the output cargo check rust and cargo sayanc170 Rust-basics Rust Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Generate Random Numbers in Rust Language? Rust - HashMaps Rust - Creating a Library Variables in Rust Standard I/O in Rust How to Install Rust on Termux? Rust - Array Rust - Traits How to Install Rust in MacOS? Rust - Generic Function
[ { "code": null, "e": 28, "s": 0, "text": "\n04 Jul, 2022" }, { "code": null, "e": 643, "s": 28, "text": "In last 2 decades the computers and the internet has made an increasing demand, and with evolution of new technologies, devices and protocols the programming languages also being updated regularly but still most of the early programming languages like C, C++ have shown some drawbacks. These drawbacks motivated others to create new programming languages like Go, Rust, Python and more. In these tutorials we will talk about one of these programming languages.Rust language is intended for highly concurrent and highly safe system. Rust language has an emphasis on safety, control of memory layout and concurrency." }, { "code": null, "e": 1061, "s": 643, "text": "Rust is a multi-paradigm programming language like C++ syntax was designed for performance and safety, especially safe concurrency by using a borrow checker and ownership to validate references. Rust was developed byGraydon Hoare at Mozilla research with contributions from Dave Herman, Brendan Eich and others. Which achieves memory safety without garbage collection. Rust is a compiled system programming language." }, { "code": null, "e": 1148, "s": 1061, "text": "Rust has many reasons for being popular among programmers. Below are the reasons are :" }, { "code": null, "e": 1373, "s": 1148, "text": "Rust is Fast: Rust Programming Language is a multi-paradigm programming language similar to C++ syntax. Thus it becomes very easy to learn Rust for anyone. Across multiple platforms Rust code compiles to native machine code." }, { "code": null, "e": 1551, "s": 1373, "text": "Rust is Memory Safe: Rust inspires developer to write safe code. Unlike C, it does not provide memory unsafe thing like dangling pointer, uninitialized pointer and NULL pointer." }, { "code": null, "e": 1729, "s": 1551, "text": "Rust is Low-Overhead: InRust Programming Language all values have a unique owner, and the scope of the value is same as scope of the owner That’s why It has an ownership system." }, { "code": null, "e": 1886, "s": 1729, "text": "Rust is flexible: Rust is designed for performance and safety, especially safe concurrency by using a borrow checker and ownership to validate references. " }, { "code": null, "e": 2018, "s": 1886, "text": "Rust is easy to use: Rust Programming Language syntax is similar to C++ language syntax so it is easy to use or easy to understand." }, { "code": null, "e": 2216, "s": 2018, "text": "Rust is statically and strongly typed: Rust is built in such a way that the code can is checked at compile time and if the compilation fails then there would be no accompanying extra memory usage." }, { "code": null, "e": 2269, "s": 2216, "text": "An example program in rust, saved with extension .rs" }, { "code": null, "e": 2274, "s": 2269, "text": "RUST" }, { "code": "fn main() { println!(\"geeks for geeks\");}", "e": 2319, "s": 2274, "text": null }, { "code": null, "e": 2327, "s": 2319, "text": "Output:" }, { "code": null, "e": 2343, "s": 2327, "text": "geeks for geeks" }, { "code": null, "e": 2530, "s": 2343, "text": "We can Install Rust by using terminal. For linux and macOS open our terminal and use the curl which can automatically install rust for us, we can refer Rust docs for windows installation" }, { "code": null, "e": 2593, "s": 2530, "text": "$ curl –proto β€˜=https’ –tlsv1.2 https://sh.rustup.rs -sSf | sh" }, { "code": null, "e": 2684, "s": 2593, "text": "We can check whether we have Rust installed correctly, open a shell and enter this command" }, { "code": null, "e": 2701, "s": 2684, "text": "$ rustc –version" }, { "code": null, "e": 2941, "s": 2701, "text": "Rust Programming Language creating and maintaining boundaries that preserve large-system integrity. Rust is a multi-paradigm programming language. it is designed for safety and performance. There are some features which makes it different." }, { "code": null, "e": 4081, "s": 2941, "text": "Ownership: InRust Programming Language all values have a unique owner, and the scope of the value is same as scope of the owner That’s why It has an ownership system. Values can be passed by immutable reference and mutable reference, using &T and &mut T, or by value, using T. there are either be multiple immutable references or one mutable reference.Memory Safety: When it comes to memory safety, Rust inspires developer to write safe code. Unlike C, it does not provide memory unsafe thing like dangling pointer, uninitialized pointer and NULL pointer. Which in result, code becomes more safe and stable. It has define format to initialize data value. And similar to C, it does provide control to handle lifetime of a variable through added syntax. Apart from this it also provide flexibility to write unsafe code with unsafe keyword which Ideally should be avoided until there is no other way.Memory Management: A programmer’s performance also depends on how language manage memory internally. Rust works on RAII , unlike java’s garbage collection. Add on to this reference counting is also available to developer but that is optional." }, { "code": null, "e": 4434, "s": 4081, "text": "Ownership: InRust Programming Language all values have a unique owner, and the scope of the value is same as scope of the owner That’s why It has an ownership system. Values can be passed by immutable reference and mutable reference, using &T and &mut T, or by value, using T. there are either be multiple immutable references or one mutable reference." }, { "code": null, "e": 4980, "s": 4434, "text": "Memory Safety: When it comes to memory safety, Rust inspires developer to write safe code. Unlike C, it does not provide memory unsafe thing like dangling pointer, uninitialized pointer and NULL pointer. Which in result, code becomes more safe and stable. It has define format to initialize data value. And similar to C, it does provide control to handle lifetime of a variable through added syntax. Apart from this it also provide flexibility to write unsafe code with unsafe keyword which Ideally should be avoided until there is no other way." }, { "code": null, "e": 5223, "s": 4980, "text": "Memory Management: A programmer’s performance also depends on how language manage memory internally. Rust works on RAII , unlike java’s garbage collection. Add on to this reference counting is also available to developer but that is optional." }, { "code": null, "e": 5543, "s": 5223, "text": "Cargo is the Rust’s build system and package manager, like pip for Python, gem for Ruby and npm for Javascript. Cargo handles a lot of tasks, such as building and compiling your code, downloading the libraries your code depends on, and building those libraries(dependencies). Cargo mostly comes pre installed with Rust." }, { "code": null, "e": 5658, "s": 5543, "text": "You can check cargo from the below command, if you don’t see version number that means you haven’t installed cargo" }, { "code": null, "e": 5675, "s": 5658, "text": "$ cargo –version" }, { "code": null, "e": 5754, "s": 5675, "text": "We can create a new rust project using cargo, for that use the below commands." }, { "code": null, "e": 5768, "s": 5754, "text": "cargo new gfg" }, { "code": null, "e": 5775, "s": 5768, "text": "cd gfg" }, { "code": null, "e": 5923, "s": 5775, "text": "cargo new command creates a new cargo project in the specified directory. the directory contains, cargo.lock, cargo.toml, src files of the project." }, { "code": null, "e": 5962, "s": 5923, "text": "cargo.lock – lock file for the project" }, { "code": null, "e": 6057, "s": 5962, "text": "cargo.toml – contains details and dependencies of the project, am example file is shown below." }, { "code": null, "e": 6067, "s": 6057, "text": "[package]" }, { "code": null, "e": 6080, "s": 6067, "text": "name = β€œgfg”" }, { "code": null, "e": 6098, "s": 6080, "text": "version = β€œ0.1.0”" }, { "code": null, "e": 6140, "s": 6098, "text": "authors = [β€œYour Name <you@example.com>”]" }, { "code": null, "e": 6157, "s": 6140, "text": "edition = β€œ2018”" }, { "code": null, "e": 6172, "s": 6157, "text": "[dependencies]" }, { "code": null, "e": 6307, "s": 6172, "text": "src – directory containing the source files of the project, main.rs file is main file for the project which will be created by default" }, { "code": null, "e": 6363, "s": 6307, "text": "We can run the project using any of the below commands." }, { "code": null, "e": 6383, "s": 6363, "text": "// compiled out put" }, { "code": null, "e": 6395, "s": 6383, "text": "cargo build" }, { "code": null, "e": 6423, "s": 6395, "text": "// runs the compiled output" }, { "code": null, "e": 6433, "s": 6423, "text": "cargo run" }, { "code": null, "e": 6453, "s": 6433, "text": "// check the output" }, { "code": null, "e": 6465, "s": 6453, "text": "cargo check" }, { "code": null, "e": 6480, "s": 6465, "text": "rust and cargo" }, { "code": null, "e": 6490, "s": 6480, "text": "sayanc170" }, { "code": null, "e": 6502, "s": 6490, "text": "Rust-basics" }, { "code": null, "e": 6507, "s": 6502, "text": "Rust" }, { "code": null, "e": 6605, "s": 6507, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6654, "s": 6605, "text": "How to Generate Random Numbers in Rust Language?" }, { "code": null, "e": 6670, "s": 6654, "text": "Rust - HashMaps" }, { "code": null, "e": 6696, "s": 6670, "text": "Rust - Creating a Library" }, { "code": null, "e": 6714, "s": 6696, "text": "Variables in Rust" }, { "code": null, "e": 6735, "s": 6714, "text": "Standard I/O in Rust" }, { "code": null, "e": 6766, "s": 6735, "text": "How to Install Rust on Termux?" }, { "code": null, "e": 6779, "s": 6766, "text": "Rust - Array" }, { "code": null, "e": 6793, "s": 6779, "text": "Rust - Traits" }, { "code": null, "e": 6823, "s": 6793, "text": "How to Install Rust in MacOS?" } ]
Subset Sum Problem | DP-25
21 Jun, 2022 Given a set of non-negative integers, and a value sum, determine if there is a subset of the given set with sum equal to given sum. Example: Input: set[] = {3, 34, 4, 12, 5, 2}, sum = 9 Output: True There is a subset (4, 5) with sum 9. Input: set[] = {3, 34, 4, 12, 5, 2}, sum = 30 Output: False There is no subset that add up to 30. Method 1: Recursion.Approach: For the recursive approach we will consider two cases. Consider the last element and now the required sum = target sum – value of β€˜last’ element and number of elements = total elements – 1Leave the β€˜last’ element and now the required sum = target sum and number of elements = total elements – 1 Consider the last element and now the required sum = target sum – value of β€˜last’ element and number of elements = total elements – 1 Leave the β€˜last’ element and now the required sum = target sum and number of elements = total elements – 1 Following is the recursive formula for isSubsetSum() problem. isSubsetSum(set, n, sum) = isSubsetSum(set, n-1, sum) || isSubsetSum(set, n-1, sum-set[n-1]) Base Cases: isSubsetSum(set, n, sum) = false, if sum > 0 and n == 0 isSubsetSum(set, n, sum) = true, if sum == 0 Let’s take a look at the simulation of above approach-: set[]={3, 4, 5, 2} sum=9 (x, y)= 'x' is the left number of elements, 'y' is the required sum (4, 9) {True} / \ (3, 6) (3, 9) / \ / \ (2, 2) (2, 6) (2, 5) (2, 9) {True} / \ (1, -3) (1, 2) {False} {True} / \ (0, 0) (0, 2) {True} {False} C++ C Java Python3 C# PHP Javascript // A recursive solution for subset sum problem#include <iostream>using namespace std; // Returns true if there is a subset// of set[] with sum equal to given sumbool isSubsetSum(int set[], int n, int sum){ // Base Cases if (sum == 0) return true; if (n == 0) return false; // If last element is greater than sum, // then ignore it if (set[n - 1] > sum) return isSubsetSum(set, n - 1, sum); /* else, check if sum can be obtained by any of the following: (a) including the last element (b) excluding the last element */ return isSubsetSum(set, n - 1, sum) || isSubsetSum(set, n - 1, sum - set[n - 1]);} // Driver codeint main(){ int set[] = { 3, 34, 4, 12, 5, 2 }; int sum = 9; int n = sizeof(set) / sizeof(set[0]); if (isSubsetSum(set, n, sum) == true) cout <<"Found a subset with given sum"; else cout <<"No subset with given sum"; return 0;} // This code is contributed by shivanisinghss2110 // A recursive solution for subset sum problem#include <stdio.h> // Returns true if there is a subset// of set[] with sum equal to given sumbool isSubsetSum(int set[], int n, int sum){ // Base Cases if (sum == 0) return true; if (n == 0) return false; // If last element is greater than sum, // then ignore it if (set[n - 1] > sum) return isSubsetSum(set, n - 1, sum); /* else, check if sum can be obtained by any of the following: (a) including the last element (b) excluding the last element */ return isSubsetSum(set, n - 1, sum) || isSubsetSum(set, n - 1, sum - set[n - 1]);} // Driver codeint main(){ int set[] = { 3, 34, 4, 12, 5, 2 }; int sum = 9; int n = sizeof(set) / sizeof(set[0]); if (isSubsetSum(set, n, sum) == true) printf("Found a subset with given sum"); else printf("No subset with given sum"); return 0;} // A recursive solution for subset sum// problemclass GFG { // Returns true if there is a subset // of set[] with sum equal to given sum static boolean isSubsetSum(int set[], int n, int sum) { // Base Cases if (sum == 0) return true; if (n == 0) return false; // If last element is greater than // sum, then ignore it if (set[n - 1] > sum) return isSubsetSum(set, n - 1, sum); /* else, check if sum can be obtained by any of the following (a) including the last element (b) excluding the last element */ return isSubsetSum(set, n - 1, sum) || isSubsetSum(set, n - 1, sum - set[n - 1]); } /* Driver code */ public static void main(String args[]) { int set[] = { 3, 34, 4, 12, 5, 2 }; int sum = 9; int n = set.length; if (isSubsetSum(set, n, sum) == true) System.out.println("Found a subset" + " with given sum"); else System.out.println("No subset with" + " given sum"); }} /* This code is contributed by Rajat Mishra */ # A recursive solution for subset sum# problem # Returns true if there is a subset# of set[] with sun equal to given sum def isSubsetSum(set, n, sum): # Base Cases if (sum == 0): return True if (n == 0): return False # If last element is greater than # sum, then ignore it if (set[n - 1] > sum): return isSubsetSum(set, n - 1, sum) # else, check if sum can be obtained # by any of the following # (a) including the last element # (b) excluding the last element return isSubsetSum( set, n-1, sum) or isSubsetSum( set, n-1, sum-set[n-1]) # Driver codeset = [3, 34, 4, 12, 5, 2]sum = 9n = len(set)if (isSubsetSum(set, n, sum) == True): print("Found a subset with given sum")else: print("No subset with given sum") # This code is contributed by Nikita Tiwari. // A recursive solution for subset sum problemusing System; class GFG { // Returns true if there is a subset of set[] with sum // equal to given sum static bool isSubsetSum(int[] set, int n, int sum) { // Base Cases if (sum == 0) return true; if (n == 0) return false; // If last element is greater than sum, // then ignore it if (set[n - 1] > sum) return isSubsetSum(set, n - 1, sum); /* else, check if sum can be obtained by any of the following (a) including the last element (b) excluding the last element */ return isSubsetSum(set, n - 1, sum) || isSubsetSum(set, n - 1, sum - set[n - 1]); } // Driver code public static void Main() { int[] set = { 3, 34, 4, 12, 5, 2 }; int sum = 9; int n = set.Length; if (isSubsetSum(set, n, sum) == true) Console.WriteLine("Found a subset with given sum"); else Console.WriteLine("No subset with given sum"); }} // This code is contributed by Sam007 <?php// A recursive solution for subset sum problem // Returns true if there is a subset of set// with sun equal to given sumfunction isSubsetSum($set, $n, $sum){ // Base Cases if ($sum == 0) return true; if ($n == 0) return false; // If last element is greater // than sum, then ignore it if ($set[$n - 1] > $sum) return isSubsetSum($set, $n - 1, $sum); /* else, check if sum can be obtained by any of the following (a) including the last element (b) excluding the last element */ return isSubsetSum($set, $n - 1, $sum) || isSubsetSum($set, $n - 1, $sum - $set[$n - 1]);} // Driver Code$set = array(3, 34, 4, 12, 5, 2);$sum = 9;$n = 6; if (isSubsetSum($set, $n, $sum) == true) echo"Found a subset with given sum";else echo "No subset with given sum"; // This code is contributed by Anuj_67 ?> <script> // A recursive solution for subset sum problem // Returns true if there is a subset of set[] with sum // equal to given sum function isSubsetSum(set, n, sum) { // Base Cases if (sum == 0) return true; if (n == 0) return false; // If last element is greater than sum, // then ignore it if (set[n - 1] > sum) return isSubsetSum(set, n - 1, sum); /* else, check if sum can be obtained by any of the following (a) including the last element (b) excluding the last element */ return isSubsetSum(set, n - 1, sum) || isSubsetSum(set, n - 1, sum - set[n - 1]); } let set = [ 3, 34, 4, 12, 5, 2 ]; let sum = 9; let n = set.length; if (isSubsetSum(set, n, sum) == true) document.write("Found a subset with given sum"); else document.write("No subset with given sum"); // This code is contributed by mukesh07.</script> Found a subset with given sum Complexity Analysis: The above solution may try all subsets of given set in worst case. Therefore time complexity of the above solution is exponential. The problem is in-fact NP-Complete (There is no known polynomial time solution for this problem). Method 2: To solve the problem in Pseudo-polynomial time use the Dynamic programming.So we will create a 2D array of size (arr.size() + 1) * (target + 1) of type boolean. The state DP[i][j] will be true if there exists a subset of elements from A[0....i] with sum value = β€˜j’. The approach for the problem is: if (A[i-1] > j) DP[i][j] = DP[i-1][j] else DP[i][j] = DP[i-1][j] OR DP[i-1][j-A[i-1]] This means that if current element has value greater than β€˜current sum value’ we will copy the answer for previous casesAnd if the current sum value is greater than the β€˜ith’ element we will see if any of previous states have already experienced the sum=’j’ OR any previous states experienced a value β€˜j – A[i]’ which will solve our purpose. This means that if current element has value greater than β€˜current sum value’ we will copy the answer for previous cases And if the current sum value is greater than the β€˜ith’ element we will see if any of previous states have already experienced the sum=’j’ OR any previous states experienced a value β€˜j – A[i]’ which will solve our purpose. The below simulation will clarify the above approach: set[]={3, 4, 5, 2} target=6 0 1 2 3 4 5 6 0 T F F F F F F 3 T F F T F F F 4 T F F T T F F 5 T F F T T T F 2 T F T T T T T Below is the implementation of the above approach: C C++ Java Python3 C# PHP Javascript // A Dynamic Programming solution// for subset sum problem#include <stdio.h> // Returns true if there is a subset of set[]// with sum equal to given sumbool isSubsetSum(int set[], int n, int sum){ // The value of subset[i][j] will be true if // there is a subset of set[0..j-1] with sum // equal to i bool subset[n + 1][sum + 1]; // If sum is 0, then answer is true for (int i = 0; i <= n; i++) subset[i][0] = true; // If sum is not 0 and set is empty, // then answer is false for (int i = 1; i <= sum; i++) subset[0][i] = false; // Fill the subset table in bottom up manner for (int i = 1; i <= n; i++) { for (int j = 1; j <= sum; j++) { if (j < set[i - 1]) subset[i][j] = subset[i - 1][j]; if (j >= set[i - 1]) subset[i][j] = subset[i - 1][j] || subset[i - 1][j - set[i - 1]]; } } /* // uncomment this code to print table for (int i = 0; i <= n; i++) { for (int j = 0; j <= sum; j++) printf ("%4d", subset[i][j]); printf("\n"); }*/ return subset[n][sum];} // Driver codeint main(){ int set[] = { 3, 34, 4, 12, 5, 2 }; int sum = 9; int n = sizeof(set) / sizeof(set[0]); if (isSubsetSum(set, n, sum) == true) printf("Found a subset with given sum"); else printf("No subset with given sum"); return 0;}// This code is contributed by Arjun Tyagi. // A Dynamic Programming solution// for subset sum problem#include <iostream>using namespace std; // Returns true if there is a subset of set[]// with sum equal to given sumbool isSubsetSum(int set[], int n, int sum){ // The value of subset[i][j] will be true if // there is a subset of set[0..j-1] with sum // equal to i bool subset[n + 1][sum + 1]; // If sum is 0, then answer is true for (int i = 0; i <= n; i++) subset[i][0] = true; // If sum is not 0 and set is empty, // then answer is false for (int i = 1; i <= sum; i++) subset[0][i] = false; // Fill the subset table in bottom up manner for (int i = 1; i <= n; i++) { for (int j = 1; j <= sum; j++) { if (j < set[i - 1]) subset[i][j] = subset[i - 1][j]; if (j >= set[i - 1]) subset[i][j] = subset[i - 1][j] || subset[i - 1][j - set[i - 1]]; } } /* // uncomment this code to print table for (int i = 0; i <= n; i++) { for (int j = 0; j <= sum; j++) printf ("%4d", subset[i][j]); cout <<"\n"; }*/ return subset[n][sum];} // Driver codeint main(){ int set[] = { 3, 34, 4, 12, 5, 2 }; int sum = 9; int n = sizeof(set) / sizeof(set[0]); if (isSubsetSum(set, n, sum) == true) cout <<"Found a subset with given sum"; else cout <<"No subset with given sum"; return 0;}// This code is contributed by shivanisinghss2110 // A Dynamic Programming solution for subset// sum problemclass GFG { // Returns true if there is a subset of // set[] with sum equal to given sum static boolean isSubsetSum(int set[], int n, int sum) { // The value of subset[i][j] will be // true if there is a subset of // set[0..j-1] with sum equal to i boolean subset[][] = new boolean[sum + 1][n + 1]; // If sum is 0, then answer is true for (int i = 0; i <= n; i++) subset[0][i] = true; // If sum is not 0 and set is empty, // then answer is false for (int i = 1; i <= sum; i++) subset[i][0] = false; // Fill the subset table in bottom // up manner for (int i = 1; i <= sum; i++) { for (int j = 1; j <= n; j++) { subset[i][j] = subset[i][j - 1]; if (i >= set[j - 1]) subset[i][j] = subset[i][j] || subset[i - set[j - 1]][j - 1]; } } /* // uncomment this code to print table for (int i = 0; i <= sum; i++) { for (int j = 0; j <= n; j++) System.out.println (subset[i][j]); } */ return subset[sum][n]; } /* Driver code*/ public static void main(String args[]) { int set[] = { 3, 34, 4, 12, 5, 2 }; int sum = 9; int n = set.length; if (isSubsetSum(set, n, sum) == true) System.out.println("Found a subset" + " with given sum"); else System.out.println("No subset with" + " given sum"); }} /* This code is contributed by Rajat Mishra */ # A Dynamic Programming solution for subset # sum problem Returns true if there is a subset of # set[] with sun equal to given sum # Returns true if there is a subset of set[] # with sum equal to given sumdef isSubsetSum(set, n, sum): # The value of subset[i][j] will be # true if there is a # subset of set[0..j-1] with sum equal to i subset =([[False for i in range(sum + 1)] for i in range(n + 1)]) # If sum is 0, then answer is true for i in range(n + 1): subset[i][0] = True # If sum is not 0 and set is empty, # then answer is false for i in range(1, sum + 1): subset[0][i]= False # Fill the subset table in bottom up manner for i in range(1, n + 1): for j in range(1, sum + 1): if j<set[i-1]: subset[i][j] = subset[i-1][j] if j>= set[i-1]: subset[i][j] = (subset[i-1][j] or subset[i - 1][j-set[i-1]]) # uncomment this code to print table # for i in range(n + 1): # for j in range(sum + 1): # print (subset[i][j], end =" ") # print() return subset[n][sum] # Driver codeif __name__=='__main__': set = [3, 34, 4, 12, 5, 2] sum = 9 n = len(set) if (isSubsetSum(set, n, sum) == True): print("Found a subset with given sum") else: print("No subset with given sum") # This code is contributed by # sahil shelangia. // A Dynamic Programming solution for// subset sum problemusing System; class GFG { // Returns true if there is a subset // of set[] with sum equal to given sum static bool isSubsetSum(int[] set, int n, int sum) { // The value of subset[i][j] will be true if there // is a subset of set[0..j-1] with sum equal to i bool[, ] subset = new bool[sum + 1, n + 1]; // If sum is 0, then answer is true for (int i = 0; i <= n; i++) subset[0, i] = true; // If sum is not 0 and set is empty, // then answer is false for (int i = 1; i <= sum; i++) subset[i, 0] = false; // Fill the subset table in bottom up manner for (int i = 1; i <= sum; i++) { for (int j = 1; j <= n; j++) { subset[i, j] = subset[i, j - 1]; if (i >= set[j - 1]) subset[i, j] = subset[i, j] || subset[i - set[j - 1], j - 1]; } } return subset[sum, n]; } // Driver code public static void Main() { int[] set = { 3, 34, 4, 12, 5, 2 }; int sum = 9; int n = set.Length; if (isSubsetSum(set, n, sum) == true) Console.WriteLine("Found a subset with given sum"); else Console.WriteLine("No subset with given sum"); }}// This code is contributed by Sam007 <?php// A Dynamic Programming solution for // subset sum problem // Returns true if there is a subset of// set[] with sum equal to given sumfunction isSubsetSum( $set, $n, $sum){ // The value of subset[i][j] will // be true if there is a subset of // set[0..j-1] with sum equal to i $subset = array(array()); // If sum is 0, then answer is true for ( $i = 0; $i <= $n; $i++) $subset[$i][0] = true; // If sum is not 0 and set is empty, // then answer is false for ( $i = 1; $i <= $sum; $i++) $subset[0][$i] = false; // Fill the subset table in bottom // up manner for ($i = 1; $i <= $n; $i++) { for ($j = 1; $j <= $sum; $j++) { if($j < $set[$i-1]) $subset[$i][$j] = $subset[$i-1][$j]; if ($j >= $set[$i-1]) $subset[$i][$j] = $subset[$i-1][$j] || $subset[$i - 1][$j - $set[$i-1]]; } } /* // uncomment this code to print table for (int i = 0; i <= n; i++) { for (int j = 0; j <= sum; j++) printf ("%4d", subset[i][j]); printf("n"); }*/ return $subset[$n][$sum];} // Driver code$set = array(3, 34, 4, 12, 5, 2);$sum = 9;$n = count($set); if (isSubsetSum($set, $n, $sum) == true) echo "Found a subset with given sum";else echo "No subset with given sum"; // This code is contributed by anuj_67.?> <script> // A Dynamic Programming solution for subset sum problem // Returns true if there is a subset of // set[] with sum equal to given sum function isSubsetSum(set, n, sum) { // The value of subset[i][j] will be // true if there is a subset of // set[0..j-1] with sum equal to i let subset = new Array(sum + 1); for(let i = 0; i < sum + 1; i++) { subset[i] = new Array(sum + 1); for(let j = 0; j < n + 1; j++) { subset[i][j] = 0; } } // If sum is 0, then answer is true for (let i = 0; i <= n; i++) subset[0][i] = true; // If sum is not 0 and set is empty, // then answer is false for (let i = 1; i <= sum; i++) subset[i][0] = false; // Fill the subset table in bottom // up manner for (let i = 1; i <= sum; i++) { for (let j = 1; j <= n; j++) { subset[i][j] = subset[i][j - 1]; if (i >= set[j - 1]) subset[i][j] = subset[i][j] || subset[i - set[j - 1]][j - 1]; } } /* // uncomment this code to print table for (int i = 0; i <= sum; i++) { for (int j = 0; j <= n; j++) System.out.println (subset[i][j]); } */ return subset[sum][n]; } let set = [ 3, 34, 4, 12, 5, 2 ]; let sum = 9; let n = set.length; if (isSubsetSum(set, n, sum) == true) document.write("Found a subset" + " with given sum"); else document.write("No subset with" + " given sum"); // This code is contributed by decode2207.</script> Found a subset with given sum Complexity Analysis: Time Complexity: O(sum*n), where sum is the β€˜target sum’ and β€˜n’ is the size of array.Auxiliary Space: O(sum*n), as the size of 2-D array is sum*n. + O(n) for recursive stack space Memoization Technique for finding Subset Sum: Method: In this method, we also follow the recursive approach but In this method, we use another 2-D matrix in we first initialize with -1 or any negative value.In this method, we avoid the few of the recursive call which is repeated itself that’s why we use 2-D matrix. In this matrix we store the value of the previous call value. In this method, we also follow the recursive approach but In this method, we use another 2-D matrix in we first initialize with -1 or any negative value. In this method, we avoid the few of the recursive call which is repeated itself that’s why we use 2-D matrix. In this matrix we store the value of the previous call value. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // CPP program for the above approach#include <bits/stdc++.h>using namespace std; // Taking the matrix as globallyint tab[2000][2000]; // Check if possible subset with // given sum is possible or notint subsetSum(int a[], int n, int sum){ // If the sum is zero it means // we got our expected sum if (sum == 0) return 1; if (n <= 0) return 0; // If the value is not -1 it means it // already call the function // with the same value. // it will save our from the repetition. if (tab[n - 1][sum] != -1) return tab[n - 1][sum]; // if the value of a[n-1] is // greater than the sum. // we call for the next value if (a[n - 1] > sum) return tab[n - 1][sum] = subsetSum(a, n - 1, sum); else { // Here we do two calls because we // don't know which value is // full-fill our criteria // that's why we doing two calls return tab[n - 1][sum] = subsetSum(a, n - 1, sum) || subsetSum(a, n - 1, sum - a[n - 1]); }} // Driver Codeint main(){ // Storing the value -1 to the matrix memset(tab, -1, sizeof(tab)); int n = 5; int a[] = {1, 5, 3, 7, 4}; int sum = 12; if (subsetSum(a, n, sum)) { cout << "YES" << endl; } else cout << "NO" << endl; /* This Code is Contributed by Ankit Kumar*/} // Java program for the above approachclass GFG { // Check if possible subset with // given sum is possible or not static int subsetSum(int a[], int n, int sum) { // Storing the value -1 to the matrix int tab[][] = new int[n + 1][sum + 1]; for (int i = 1; i <= n; i++) { for (int j = 1; j <= sum; j++) { tab[i][j] = -1; } } // If the sum is zero it means // we got our expected sum if (sum == 0) return 1; if (n <= 0) return 0; // If the value is not -1 it means it // already call the function // with the same value. // it will save our from the repetition. if (tab[n - 1][sum] != -1) return tab[n - 1][sum]; // if the value of a[n-1] is // greater than the sum. // we call for the next value if (a[n - 1] > sum) return tab[n - 1][sum] = subsetSum(a, n - 1, sum); else { // Here we do two calls because we // don't know which value is // full-fill our criteria // that's why we doing two calls if (subsetSum(a, n - 1, sum) != 0 || subsetSum(a, n - 1, sum - a[n - 1]) != 0) { return tab[n - 1][sum] = 1; } else return tab[n - 1][sum] = 0; } } // Driver Code public static void main(String[] args) { int n = 5; int a[] = { 1, 5, 3, 7, 4 }; int sum = 12; if (subsetSum(a, n, sum) != 0) { System.out.println("YES\n"); } else System.out.println("NO\n"); }} // This code is contributed by rajsanghavi9. # Python program for the above approach # Taking the matrix as globallytab = [[-1 for i in range(2000)] for j in range(2000)] # Check if possible subset with # given sum is possible or notdef subsetSum(a, n, sum): # If the sum is zero it means # we got our expected sum if (sum == 0): return 1 if (n <= 0): return 0 # If the value is not -1 it means it # already call the function # with the same value. # it will save our from the repetition. if (tab[n - 1][sum] != -1): return tab[n - 1][sum] # if the value of a[n-1] is # greater than the sum. # we call for the next value if (a[n - 1] > sum): tab[n - 1][sum] = subsetSum(a, n - 1, sum) return tab[n - 1][sum] else: # Here we do two calls because we # don't know which value is # full-fill our criteria # that's why we doing two calls tab[n - 1][sum] = subsetSum(a, n - 1, sum) return tab[n - 1][sum] or subsetSum(a, n - 1, sum - a[n - 1]) # Driver Code n = 5a = [1, 5, 3, 7, 4]sum = 12 if (subsetSum(a, n, sum)): print("YES")else: print("NO") # This code is contributed by shivani. // C# program for the above approachusing System;class GFG { // Check if possible subset with // given sum is possible or not static int subsetSum(int []a, int n, int sum) { // Storing the value -1 to the matrix int [,]tab = new int[n + 1,sum + 1]; for (int i = 1; i <= n; i++) { for (int j = 1; j <= sum; j++) { tab[i,j] = -1; } } // If the sum is zero it means // we got our expected sum if (sum == 0) return 1; if (n <= 0) return 0; // If the value is not -1 it means it // already call the function // with the same value. // it will save our from the repetition. if (tab[n - 1,sum] != -1) return tab[n - 1,sum]; // if the value of a[n-1] is // greater than the sum. // we call for the next value if (a[n - 1] > sum) return tab[n - 1,sum] = subsetSum(a, n - 1, sum); else { // Here we do two calls because we // don't know which value is // full-fill our criteria // that's why we doing two calls if (subsetSum(a, n - 1, sum) != 0 || subsetSum(a, n - 1, sum - a[n - 1]) != 0) { return tab[n - 1,sum] = 1; } else return tab[n - 1,sum] = 0; } } // Driver Code public static void Main(String[] args) { int n = 5; int []a = { 1, 5, 3, 7, 4 }; int sum = 12; if (subsetSum(a, n, sum) != 0) { Console.Write("YES\n"); } else Console.Write("NO\n"); }} // This code is contributed by shivanisinghss2110 <script> // JavaScript Program for the above approach // Check if possible subset with // given sum is possible or not function subsetSum(a, n, sum) { // If the sum is zero it means // we got our expected sum if (sum == 0) return 1; if (n <= 0) return 0; // If the value is not -1 it means it // already call the function // with the same value. // it will save our from the repetition. if (tab[n - 1][sum] != -1) return tab[n - 1][sum]; // if the value of a[n-1] is // greater than the sum. // we call for the next value if (a[n - 1] > sum) return tab[n - 1][sum] = subsetSum(a, n - 1, sum); else { // Here we do two calls because we // don't know which value is // full-fill our criteria // that's why we doing two calls return tab[n - 1][sum] = subsetSum(a, n - 1, sum) || subsetSum(a, n - 1, sum - a[n - 1]); } } // Driver Code // Storing the value -1 to the matrix let tab = Array(2000).fill().map(() => Array(2000).fill(-1)); let n = 5; let a = [1, 5, 3, 7, 4]; let sum = 12; if (subsetSum(a, n, sum)) { document.write("YES" + "<br>"); } else { document.write("NO" + "<br>"); } // This code is contributed by Potta Lokesh </script> YES Complexity Analysis: Time Complexity: O(sum*n), where sum is the β€˜target sum’ and β€˜n’ is the size of array. Auxiliary Space: O(sum*n) + O(n) -> O(sum*n) = the size of 2-D array is sum*n and O(n)=auxiliary stack space. Subset Sum Problem in O(sum) space Perfect Sum Problem (Print all subsets with given sum)Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. vt_m sahilshelangia pallagolladwarakesh ayushmaanj kevinjoseph61 bidibaaz123 shethnisarg1998 Dhananjay_Kumar sguptashivang kaushal kishore 1 ankitkumar774 18ucs175 mukesh07 decode2207 shree_hari lokeshpotta20 rajsanghavi9 shivanisinghss2110 arorakashish0911 sanskar84 r_c Adobe Adobe-Question Amazon Drishti-Soft subset Arrays Dynamic Programming Amazon Adobe Drishti-Soft Arrays Dynamic Programming subset Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Arrays in Java Write a program to reverse an array or string Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Largest Sum Contiguous Subarray Largest Sum Contiguous Subarray Program for Fibonacci numbers Longest Increasing Subsequence | DP-3 Longest Palindromic Substring | Set 1 Sieve of Eratosthenes
[ { "code": null, "e": 54, "s": 26, "text": "\n21 Jun, 2022" }, { "code": null, "e": 187, "s": 54, "text": "Given a set of non-negative integers, and a value sum, determine if there is a subset of the given set with sum equal to given sum. " }, { "code": null, "e": 197, "s": 187, "text": "Example: " }, { "code": null, "e": 393, "s": 197, "text": "Input: set[] = {3, 34, 4, 12, 5, 2}, sum = 9\nOutput: True \nThere is a subset (4, 5) with sum 9.\n\nInput: set[] = {3, 34, 4, 12, 5, 2}, sum = 30\nOutput: False\nThere is no subset that add up to 30." }, { "code": null, "e": 479, "s": 393, "text": "Method 1: Recursion.Approach: For the recursive approach we will consider two cases. " }, { "code": null, "e": 719, "s": 479, "text": "Consider the last element and now the required sum = target sum – value of β€˜last’ element and number of elements = total elements – 1Leave the β€˜last’ element and now the required sum = target sum and number of elements = total elements – 1" }, { "code": null, "e": 853, "s": 719, "text": "Consider the last element and now the required sum = target sum – value of β€˜last’ element and number of elements = total elements – 1" }, { "code": null, "e": 960, "s": 853, "text": "Leave the β€˜last’ element and now the required sum = target sum and number of elements = total elements – 1" }, { "code": null, "e": 1023, "s": 960, "text": "Following is the recursive formula for isSubsetSum() problem. " }, { "code": null, "e": 1234, "s": 1023, "text": "isSubsetSum(set, n, sum) \n= isSubsetSum(set, n-1, sum) || \n isSubsetSum(set, n-1, sum-set[n-1])\nBase Cases:\nisSubsetSum(set, n, sum) = false, if sum > 0 and n == 0\nisSubsetSum(set, n, sum) = true, if sum == 0 " }, { "code": null, "e": 1291, "s": 1234, "text": "Let’s take a look at the simulation of above approach-: " }, { "code": null, "e": 1690, "s": 1291, "text": "set[]={3, 4, 5, 2}\nsum=9\n(x, y)= 'x' is the left number of elements,\n'y' is the required sum\n \n (4, 9)\n {True}\n / \\ \n (3, 6) (3, 9)\n \n / \\ / \\ \n (2, 2) (2, 6) (2, 5) (2, 9)\n {True} \n / \\ \n (1, -3) (1, 2) \n{False} {True} \n / \\\n (0, 0) (0, 2)\n {True} {False} " }, { "code": null, "e": 1694, "s": 1690, "text": "C++" }, { "code": null, "e": 1696, "s": 1694, "text": "C" }, { "code": null, "e": 1701, "s": 1696, "text": "Java" }, { "code": null, "e": 1709, "s": 1701, "text": "Python3" }, { "code": null, "e": 1712, "s": 1709, "text": "C#" }, { "code": null, "e": 1716, "s": 1712, "text": "PHP" }, { "code": null, "e": 1727, "s": 1716, "text": "Javascript" }, { "code": "// A recursive solution for subset sum problem#include <iostream>using namespace std; // Returns true if there is a subset// of set[] with sum equal to given sumbool isSubsetSum(int set[], int n, int sum){ // Base Cases if (sum == 0) return true; if (n == 0) return false; // If last element is greater than sum, // then ignore it if (set[n - 1] > sum) return isSubsetSum(set, n - 1, sum); /* else, check if sum can be obtained by any of the following: (a) including the last element (b) excluding the last element */ return isSubsetSum(set, n - 1, sum) || isSubsetSum(set, n - 1, sum - set[n - 1]);} // Driver codeint main(){ int set[] = { 3, 34, 4, 12, 5, 2 }; int sum = 9; int n = sizeof(set) / sizeof(set[0]); if (isSubsetSum(set, n, sum) == true) cout <<\"Found a subset with given sum\"; else cout <<\"No subset with given sum\"; return 0;} // This code is contributed by shivanisinghss2110", "e": 2731, "s": 1727, "text": null }, { "code": "// A recursive solution for subset sum problem#include <stdio.h> // Returns true if there is a subset// of set[] with sum equal to given sumbool isSubsetSum(int set[], int n, int sum){ // Base Cases if (sum == 0) return true; if (n == 0) return false; // If last element is greater than sum, // then ignore it if (set[n - 1] > sum) return isSubsetSum(set, n - 1, sum); /* else, check if sum can be obtained by any of the following: (a) including the last element (b) excluding the last element */ return isSubsetSum(set, n - 1, sum) || isSubsetSum(set, n - 1, sum - set[n - 1]);} // Driver codeint main(){ int set[] = { 3, 34, 4, 12, 5, 2 }; int sum = 9; int n = sizeof(set) / sizeof(set[0]); if (isSubsetSum(set, n, sum) == true) printf(\"Found a subset with given sum\"); else printf(\"No subset with given sum\"); return 0;}", "e": 3660, "s": 2731, "text": null }, { "code": "// A recursive solution for subset sum// problemclass GFG { // Returns true if there is a subset // of set[] with sum equal to given sum static boolean isSubsetSum(int set[], int n, int sum) { // Base Cases if (sum == 0) return true; if (n == 0) return false; // If last element is greater than // sum, then ignore it if (set[n - 1] > sum) return isSubsetSum(set, n - 1, sum); /* else, check if sum can be obtained by any of the following (a) including the last element (b) excluding the last element */ return isSubsetSum(set, n - 1, sum) || isSubsetSum(set, n - 1, sum - set[n - 1]); } /* Driver code */ public static void main(String args[]) { int set[] = { 3, 34, 4, 12, 5, 2 }; int sum = 9; int n = set.length; if (isSubsetSum(set, n, sum) == true) System.out.println(\"Found a subset\" + \" with given sum\"); else System.out.println(\"No subset with\" + \" given sum\"); }} /* This code is contributed by Rajat Mishra */", "e": 4893, "s": 3660, "text": null }, { "code": "# A recursive solution for subset sum# problem # Returns true if there is a subset# of set[] with sun equal to given sum def isSubsetSum(set, n, sum): # Base Cases if (sum == 0): return True if (n == 0): return False # If last element is greater than # sum, then ignore it if (set[n - 1] > sum): return isSubsetSum(set, n - 1, sum) # else, check if sum can be obtained # by any of the following # (a) including the last element # (b) excluding the last element return isSubsetSum( set, n-1, sum) or isSubsetSum( set, n-1, sum-set[n-1]) # Driver codeset = [3, 34, 4, 12, 5, 2]sum = 9n = len(set)if (isSubsetSum(set, n, sum) == True): print(\"Found a subset with given sum\")else: print(\"No subset with given sum\") # This code is contributed by Nikita Tiwari.", "e": 5737, "s": 4893, "text": null }, { "code": "// A recursive solution for subset sum problemusing System; class GFG { // Returns true if there is a subset of set[] with sum // equal to given sum static bool isSubsetSum(int[] set, int n, int sum) { // Base Cases if (sum == 0) return true; if (n == 0) return false; // If last element is greater than sum, // then ignore it if (set[n - 1] > sum) return isSubsetSum(set, n - 1, sum); /* else, check if sum can be obtained by any of the following (a) including the last element (b) excluding the last element */ return isSubsetSum(set, n - 1, sum) || isSubsetSum(set, n - 1, sum - set[n - 1]); } // Driver code public static void Main() { int[] set = { 3, 34, 4, 12, 5, 2 }; int sum = 9; int n = set.Length; if (isSubsetSum(set, n, sum) == true) Console.WriteLine(\"Found a subset with given sum\"); else Console.WriteLine(\"No subset with given sum\"); }} // This code is contributed by Sam007", "e": 6842, "s": 5737, "text": null }, { "code": "<?php// A recursive solution for subset sum problem // Returns true if there is a subset of set// with sun equal to given sumfunction isSubsetSum($set, $n, $sum){ // Base Cases if ($sum == 0) return true; if ($n == 0) return false; // If last element is greater // than sum, then ignore it if ($set[$n - 1] > $sum) return isSubsetSum($set, $n - 1, $sum); /* else, check if sum can be obtained by any of the following (a) including the last element (b) excluding the last element */ return isSubsetSum($set, $n - 1, $sum) || isSubsetSum($set, $n - 1, $sum - $set[$n - 1]);} // Driver Code$set = array(3, 34, 4, 12, 5, 2);$sum = 9;$n = 6; if (isSubsetSum($set, $n, $sum) == true) echo\"Found a subset with given sum\";else echo \"No subset with given sum\"; // This code is contributed by Anuj_67 ?>", "e": 7756, "s": 6842, "text": null }, { "code": "<script> // A recursive solution for subset sum problem // Returns true if there is a subset of set[] with sum // equal to given sum function isSubsetSum(set, n, sum) { // Base Cases if (sum == 0) return true; if (n == 0) return false; // If last element is greater than sum, // then ignore it if (set[n - 1] > sum) return isSubsetSum(set, n - 1, sum); /* else, check if sum can be obtained by any of the following (a) including the last element (b) excluding the last element */ return isSubsetSum(set, n - 1, sum) || isSubsetSum(set, n - 1, sum - set[n - 1]); } let set = [ 3, 34, 4, 12, 5, 2 ]; let sum = 9; let n = set.length; if (isSubsetSum(set, n, sum) == true) document.write(\"Found a subset with given sum\"); else document.write(\"No subset with given sum\"); // This code is contributed by mukesh07.</script>", "e": 8762, "s": 7756, "text": null }, { "code": null, "e": 8792, "s": 8762, "text": "Found a subset with given sum" }, { "code": null, "e": 9042, "s": 8792, "text": "Complexity Analysis: The above solution may try all subsets of given set in worst case. Therefore time complexity of the above solution is exponential. The problem is in-fact NP-Complete (There is no known polynomial time solution for this problem)." }, { "code": null, "e": 9353, "s": 9042, "text": "Method 2: To solve the problem in Pseudo-polynomial time use the Dynamic programming.So we will create a 2D array of size (arr.size() + 1) * (target + 1) of type boolean. The state DP[i][j] will be true if there exists a subset of elements from A[0....i] with sum value = β€˜j’. The approach for the problem is: " }, { "code": null, "e": 9440, "s": 9353, "text": "if (A[i-1] > j)\nDP[i][j] = DP[i-1][j]\nelse \nDP[i][j] = DP[i-1][j] OR DP[i-1][j-A[i-1]]" }, { "code": null, "e": 9782, "s": 9440, "text": "This means that if current element has value greater than β€˜current sum value’ we will copy the answer for previous casesAnd if the current sum value is greater than the β€˜ith’ element we will see if any of previous states have already experienced the sum=’j’ OR any previous states experienced a value β€˜j – A[i]’ which will solve our purpose." }, { "code": null, "e": 9903, "s": 9782, "text": "This means that if current element has value greater than β€˜current sum value’ we will copy the answer for previous cases" }, { "code": null, "e": 10125, "s": 9903, "text": "And if the current sum value is greater than the β€˜ith’ element we will see if any of previous states have already experienced the sum=’j’ OR any previous states experienced a value β€˜j – A[i]’ which will solve our purpose." }, { "code": null, "e": 10180, "s": 10125, "text": "The below simulation will clarify the above approach: " }, { "code": null, "e": 10445, "s": 10180, "text": "set[]={3, 4, 5, 2}\ntarget=6\n \n 0 1 2 3 4 5 6\n\n0 T F F F F F F\n\n3 T F F T F F F\n \n4 T F F T T F F \n \n5 T F F T T T F\n\n2 T F T T T T T" }, { "code": null, "e": 10497, "s": 10445, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 10499, "s": 10497, "text": "C" }, { "code": null, "e": 10503, "s": 10499, "text": "C++" }, { "code": null, "e": 10508, "s": 10503, "text": "Java" }, { "code": null, "e": 10516, "s": 10508, "text": "Python3" }, { "code": null, "e": 10519, "s": 10516, "text": "C#" }, { "code": null, "e": 10523, "s": 10519, "text": "PHP" }, { "code": null, "e": 10534, "s": 10523, "text": "Javascript" }, { "code": "// A Dynamic Programming solution// for subset sum problem#include <stdio.h> // Returns true if there is a subset of set[]// with sum equal to given sumbool isSubsetSum(int set[], int n, int sum){ // The value of subset[i][j] will be true if // there is a subset of set[0..j-1] with sum // equal to i bool subset[n + 1][sum + 1]; // If sum is 0, then answer is true for (int i = 0; i <= n; i++) subset[i][0] = true; // If sum is not 0 and set is empty, // then answer is false for (int i = 1; i <= sum; i++) subset[0][i] = false; // Fill the subset table in bottom up manner for (int i = 1; i <= n; i++) { for (int j = 1; j <= sum; j++) { if (j < set[i - 1]) subset[i][j] = subset[i - 1][j]; if (j >= set[i - 1]) subset[i][j] = subset[i - 1][j] || subset[i - 1][j - set[i - 1]]; } } /* // uncomment this code to print table for (int i = 0; i <= n; i++) { for (int j = 0; j <= sum; j++) printf (\"%4d\", subset[i][j]); printf(\"\\n\"); }*/ return subset[n][sum];} // Driver codeint main(){ int set[] = { 3, 34, 4, 12, 5, 2 }; int sum = 9; int n = sizeof(set) / sizeof(set[0]); if (isSubsetSum(set, n, sum) == true) printf(\"Found a subset with given sum\"); else printf(\"No subset with given sum\"); return 0;}// This code is contributed by Arjun Tyagi.", "e": 12010, "s": 10534, "text": null }, { "code": "// A Dynamic Programming solution// for subset sum problem#include <iostream>using namespace std; // Returns true if there is a subset of set[]// with sum equal to given sumbool isSubsetSum(int set[], int n, int sum){ // The value of subset[i][j] will be true if // there is a subset of set[0..j-1] with sum // equal to i bool subset[n + 1][sum + 1]; // If sum is 0, then answer is true for (int i = 0; i <= n; i++) subset[i][0] = true; // If sum is not 0 and set is empty, // then answer is false for (int i = 1; i <= sum; i++) subset[0][i] = false; // Fill the subset table in bottom up manner for (int i = 1; i <= n; i++) { for (int j = 1; j <= sum; j++) { if (j < set[i - 1]) subset[i][j] = subset[i - 1][j]; if (j >= set[i - 1]) subset[i][j] = subset[i - 1][j] || subset[i - 1][j - set[i - 1]]; } } /* // uncomment this code to print table for (int i = 0; i <= n; i++) { for (int j = 0; j <= sum; j++) printf (\"%4d\", subset[i][j]); cout <<\"\\n\"; }*/ return subset[n][sum];} // Driver codeint main(){ int set[] = { 3, 34, 4, 12, 5, 2 }; int sum = 9; int n = sizeof(set) / sizeof(set[0]); if (isSubsetSum(set, n, sum) == true) cout <<\"Found a subset with given sum\"; else cout <<\"No subset with given sum\"; return 0;}// This code is contributed by shivanisinghss2110", "e": 13510, "s": 12010, "text": null }, { "code": "// A Dynamic Programming solution for subset// sum problemclass GFG { // Returns true if there is a subset of // set[] with sum equal to given sum static boolean isSubsetSum(int set[], int n, int sum) { // The value of subset[i][j] will be // true if there is a subset of // set[0..j-1] with sum equal to i boolean subset[][] = new boolean[sum + 1][n + 1]; // If sum is 0, then answer is true for (int i = 0; i <= n; i++) subset[0][i] = true; // If sum is not 0 and set is empty, // then answer is false for (int i = 1; i <= sum; i++) subset[i][0] = false; // Fill the subset table in bottom // up manner for (int i = 1; i <= sum; i++) { for (int j = 1; j <= n; j++) { subset[i][j] = subset[i][j - 1]; if (i >= set[j - 1]) subset[i][j] = subset[i][j] || subset[i - set[j - 1]][j - 1]; } } /* // uncomment this code to print table for (int i = 0; i <= sum; i++) { for (int j = 0; j <= n; j++) System.out.println (subset[i][j]); } */ return subset[sum][n]; } /* Driver code*/ public static void main(String args[]) { int set[] = { 3, 34, 4, 12, 5, 2 }; int sum = 9; int n = set.length; if (isSubsetSum(set, n, sum) == true) System.out.println(\"Found a subset\" + \" with given sum\"); else System.out.println(\"No subset with\" + \" given sum\"); }} /* This code is contributed by Rajat Mishra */", "e": 15258, "s": 13510, "text": null }, { "code": "# A Dynamic Programming solution for subset # sum problem Returns true if there is a subset of # set[] with sun equal to given sum # Returns true if there is a subset of set[] # with sum equal to given sumdef isSubsetSum(set, n, sum): # The value of subset[i][j] will be # true if there is a # subset of set[0..j-1] with sum equal to i subset =([[False for i in range(sum + 1)] for i in range(n + 1)]) # If sum is 0, then answer is true for i in range(n + 1): subset[i][0] = True # If sum is not 0 and set is empty, # then answer is false for i in range(1, sum + 1): subset[0][i]= False # Fill the subset table in bottom up manner for i in range(1, n + 1): for j in range(1, sum + 1): if j<set[i-1]: subset[i][j] = subset[i-1][j] if j>= set[i-1]: subset[i][j] = (subset[i-1][j] or subset[i - 1][j-set[i-1]]) # uncomment this code to print table # for i in range(n + 1): # for j in range(sum + 1): # print (subset[i][j], end =\" \") # print() return subset[n][sum] # Driver codeif __name__=='__main__': set = [3, 34, 4, 12, 5, 2] sum = 9 n = len(set) if (isSubsetSum(set, n, sum) == True): print(\"Found a subset with given sum\") else: print(\"No subset with given sum\") # This code is contributed by # sahil shelangia. ", "e": 16739, "s": 15258, "text": null }, { "code": "// A Dynamic Programming solution for// subset sum problemusing System; class GFG { // Returns true if there is a subset // of set[] with sum equal to given sum static bool isSubsetSum(int[] set, int n, int sum) { // The value of subset[i][j] will be true if there // is a subset of set[0..j-1] with sum equal to i bool[, ] subset = new bool[sum + 1, n + 1]; // If sum is 0, then answer is true for (int i = 0; i <= n; i++) subset[0, i] = true; // If sum is not 0 and set is empty, // then answer is false for (int i = 1; i <= sum; i++) subset[i, 0] = false; // Fill the subset table in bottom up manner for (int i = 1; i <= sum; i++) { for (int j = 1; j <= n; j++) { subset[i, j] = subset[i, j - 1]; if (i >= set[j - 1]) subset[i, j] = subset[i, j] || subset[i - set[j - 1], j - 1]; } } return subset[sum, n]; } // Driver code public static void Main() { int[] set = { 3, 34, 4, 12, 5, 2 }; int sum = 9; int n = set.Length; if (isSubsetSum(set, n, sum) == true) Console.WriteLine(\"Found a subset with given sum\"); else Console.WriteLine(\"No subset with given sum\"); }}// This code is contributed by Sam007", "e": 18152, "s": 16739, "text": null }, { "code": "<?php// A Dynamic Programming solution for // subset sum problem // Returns true if there is a subset of// set[] with sum equal to given sumfunction isSubsetSum( $set, $n, $sum){ // The value of subset[i][j] will // be true if there is a subset of // set[0..j-1] with sum equal to i $subset = array(array()); // If sum is 0, then answer is true for ( $i = 0; $i <= $n; $i++) $subset[$i][0] = true; // If sum is not 0 and set is empty, // then answer is false for ( $i = 1; $i <= $sum; $i++) $subset[0][$i] = false; // Fill the subset table in bottom // up manner for ($i = 1; $i <= $n; $i++) { for ($j = 1; $j <= $sum; $j++) { if($j < $set[$i-1]) $subset[$i][$j] = $subset[$i-1][$j]; if ($j >= $set[$i-1]) $subset[$i][$j] = $subset[$i-1][$j] || $subset[$i - 1][$j - $set[$i-1]]; } } /* // uncomment this code to print table for (int i = 0; i <= n; i++) { for (int j = 0; j <= sum; j++) printf (\"%4d\", subset[i][j]); printf(\"n\"); }*/ return $subset[$n][$sum];} // Driver code$set = array(3, 34, 4, 12, 5, 2);$sum = 9;$n = count($set); if (isSubsetSum($set, $n, $sum) == true) echo \"Found a subset with given sum\";else echo \"No subset with given sum\"; // This code is contributed by anuj_67.?>", "e": 19620, "s": 18152, "text": null }, { "code": "<script> // A Dynamic Programming solution for subset sum problem // Returns true if there is a subset of // set[] with sum equal to given sum function isSubsetSum(set, n, sum) { // The value of subset[i][j] will be // true if there is a subset of // set[0..j-1] with sum equal to i let subset = new Array(sum + 1); for(let i = 0; i < sum + 1; i++) { subset[i] = new Array(sum + 1); for(let j = 0; j < n + 1; j++) { subset[i][j] = 0; } } // If sum is 0, then answer is true for (let i = 0; i <= n; i++) subset[0][i] = true; // If sum is not 0 and set is empty, // then answer is false for (let i = 1; i <= sum; i++) subset[i][0] = false; // Fill the subset table in bottom // up manner for (let i = 1; i <= sum; i++) { for (let j = 1; j <= n; j++) { subset[i][j] = subset[i][j - 1]; if (i >= set[j - 1]) subset[i][j] = subset[i][j] || subset[i - set[j - 1]][j - 1]; } } /* // uncomment this code to print table for (int i = 0; i <= sum; i++) { for (int j = 0; j <= n; j++) System.out.println (subset[i][j]); } */ return subset[sum][n]; } let set = [ 3, 34, 4, 12, 5, 2 ]; let sum = 9; let n = set.length; if (isSubsetSum(set, n, sum) == true) document.write(\"Found a subset\" + \" with given sum\"); else document.write(\"No subset with\" + \" given sum\"); // This code is contributed by decode2207.</script>", "e": 21363, "s": 19620, "text": null }, { "code": null, "e": 21393, "s": 21363, "text": "Found a subset with given sum" }, { "code": null, "e": 21414, "s": 21393, "text": "Complexity Analysis:" }, { "code": null, "e": 21595, "s": 21414, "text": "Time Complexity: O(sum*n), where sum is the β€˜target sum’ and β€˜n’ is the size of array.Auxiliary Space: O(sum*n), as the size of 2-D array is sum*n. + O(n) for recursive stack space" }, { "code": null, "e": 21641, "s": 21595, "text": "Memoization Technique for finding Subset Sum:" }, { "code": null, "e": 21649, "s": 21641, "text": "Method:" }, { "code": null, "e": 21975, "s": 21649, "text": "In this method, we also follow the recursive approach but In this method, we use another 2-D matrix in we first initialize with -1 or any negative value.In this method, we avoid the few of the recursive call which is repeated itself that’s why we use 2-D matrix. In this matrix we store the value of the previous call value." }, { "code": null, "e": 22130, "s": 21975, "text": "In this method, we also follow the recursive approach but In this method, we use another 2-D matrix in we first initialize with -1 or any negative value." }, { "code": null, "e": 22302, "s": 22130, "text": "In this method, we avoid the few of the recursive call which is repeated itself that’s why we use 2-D matrix. In this matrix we store the value of the previous call value." }, { "code": null, "e": 22353, "s": 22302, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 22357, "s": 22353, "text": "C++" }, { "code": null, "e": 22362, "s": 22357, "text": "Java" }, { "code": null, "e": 22370, "s": 22362, "text": "Python3" }, { "code": null, "e": 22373, "s": 22370, "text": "C#" }, { "code": null, "e": 22384, "s": 22373, "text": "Javascript" }, { "code": "// CPP program for the above approach#include <bits/stdc++.h>using namespace std; // Taking the matrix as globallyint tab[2000][2000]; // Check if possible subset with // given sum is possible or notint subsetSum(int a[], int n, int sum){ // If the sum is zero it means // we got our expected sum if (sum == 0) return 1; if (n <= 0) return 0; // If the value is not -1 it means it // already call the function // with the same value. // it will save our from the repetition. if (tab[n - 1][sum] != -1) return tab[n - 1][sum]; // if the value of a[n-1] is // greater than the sum. // we call for the next value if (a[n - 1] > sum) return tab[n - 1][sum] = subsetSum(a, n - 1, sum); else { // Here we do two calls because we // don't know which value is // full-fill our criteria // that's why we doing two calls return tab[n - 1][sum] = subsetSum(a, n - 1, sum) || subsetSum(a, n - 1, sum - a[n - 1]); }} // Driver Codeint main(){ // Storing the value -1 to the matrix memset(tab, -1, sizeof(tab)); int n = 5; int a[] = {1, 5, 3, 7, 4}; int sum = 12; if (subsetSum(a, n, sum)) { cout << \"YES\" << endl; } else cout << \"NO\" << endl; /* This Code is Contributed by Ankit Kumar*/}", "e": 23786, "s": 22384, "text": null }, { "code": "// Java program for the above approachclass GFG { // Check if possible subset with // given sum is possible or not static int subsetSum(int a[], int n, int sum) { // Storing the value -1 to the matrix int tab[][] = new int[n + 1][sum + 1]; for (int i = 1; i <= n; i++) { for (int j = 1; j <= sum; j++) { tab[i][j] = -1; } } // If the sum is zero it means // we got our expected sum if (sum == 0) return 1; if (n <= 0) return 0; // If the value is not -1 it means it // already call the function // with the same value. // it will save our from the repetition. if (tab[n - 1][sum] != -1) return tab[n - 1][sum]; // if the value of a[n-1] is // greater than the sum. // we call for the next value if (a[n - 1] > sum) return tab[n - 1][sum] = subsetSum(a, n - 1, sum); else { // Here we do two calls because we // don't know which value is // full-fill our criteria // that's why we doing two calls if (subsetSum(a, n - 1, sum) != 0 || subsetSum(a, n - 1, sum - a[n - 1]) != 0) { return tab[n - 1][sum] = 1; } else return tab[n - 1][sum] = 0; } } // Driver Code public static void main(String[] args) { int n = 5; int a[] = { 1, 5, 3, 7, 4 }; int sum = 12; if (subsetSum(a, n, sum) != 0) { System.out.println(\"YES\\n\"); } else System.out.println(\"NO\\n\"); }} // This code is contributed by rajsanghavi9.", "e": 25570, "s": 23786, "text": null }, { "code": "# Python program for the above approach # Taking the matrix as globallytab = [[-1 for i in range(2000)] for j in range(2000)] # Check if possible subset with # given sum is possible or notdef subsetSum(a, n, sum): # If the sum is zero it means # we got our expected sum if (sum == 0): return 1 if (n <= 0): return 0 # If the value is not -1 it means it # already call the function # with the same value. # it will save our from the repetition. if (tab[n - 1][sum] != -1): return tab[n - 1][sum] # if the value of a[n-1] is # greater than the sum. # we call for the next value if (a[n - 1] > sum): tab[n - 1][sum] = subsetSum(a, n - 1, sum) return tab[n - 1][sum] else: # Here we do two calls because we # don't know which value is # full-fill our criteria # that's why we doing two calls tab[n - 1][sum] = subsetSum(a, n - 1, sum) return tab[n - 1][sum] or subsetSum(a, n - 1, sum - a[n - 1]) # Driver Code n = 5a = [1, 5, 3, 7, 4]sum = 12 if (subsetSum(a, n, sum)): print(\"YES\")else: print(\"NO\") # This code is contributed by shivani.", "e": 26784, "s": 25570, "text": null }, { "code": "// C# program for the above approachusing System;class GFG { // Check if possible subset with // given sum is possible or not static int subsetSum(int []a, int n, int sum) { // Storing the value -1 to the matrix int [,]tab = new int[n + 1,sum + 1]; for (int i = 1; i <= n; i++) { for (int j = 1; j <= sum; j++) { tab[i,j] = -1; } } // If the sum is zero it means // we got our expected sum if (sum == 0) return 1; if (n <= 0) return 0; // If the value is not -1 it means it // already call the function // with the same value. // it will save our from the repetition. if (tab[n - 1,sum] != -1) return tab[n - 1,sum]; // if the value of a[n-1] is // greater than the sum. // we call for the next value if (a[n - 1] > sum) return tab[n - 1,sum] = subsetSum(a, n - 1, sum); else { // Here we do two calls because we // don't know which value is // full-fill our criteria // that's why we doing two calls if (subsetSum(a, n - 1, sum) != 0 || subsetSum(a, n - 1, sum - a[n - 1]) != 0) { return tab[n - 1,sum] = 1; } else return tab[n - 1,sum] = 0; } } // Driver Code public static void Main(String[] args) { int n = 5; int []a = { 1, 5, 3, 7, 4 }; int sum = 12; if (subsetSum(a, n, sum) != 0) { Console.Write(\"YES\\n\"); } else Console.Write(\"NO\\n\"); }} // This code is contributed by shivanisinghss2110", "e": 28574, "s": 26784, "text": null }, { "code": "<script> // JavaScript Program for the above approach // Check if possible subset with // given sum is possible or not function subsetSum(a, n, sum) { // If the sum is zero it means // we got our expected sum if (sum == 0) return 1; if (n <= 0) return 0; // If the value is not -1 it means it // already call the function // with the same value. // it will save our from the repetition. if (tab[n - 1][sum] != -1) return tab[n - 1][sum]; // if the value of a[n-1] is // greater than the sum. // we call for the next value if (a[n - 1] > sum) return tab[n - 1][sum] = subsetSum(a, n - 1, sum); else { // Here we do two calls because we // don't know which value is // full-fill our criteria // that's why we doing two calls return tab[n - 1][sum] = subsetSum(a, n - 1, sum) || subsetSum(a, n - 1, sum - a[n - 1]); } } // Driver Code // Storing the value -1 to the matrix let tab = Array(2000).fill().map(() => Array(2000).fill(-1)); let n = 5; let a = [1, 5, 3, 7, 4]; let sum = 12; if (subsetSum(a, n, sum)) { document.write(\"YES\" + \"<br>\"); } else { document.write(\"NO\" + \"<br>\"); } // This code is contributed by Potta Lokesh </script>", "e": 30195, "s": 28574, "text": null }, { "code": null, "e": 30199, "s": 30195, "text": "YES" }, { "code": null, "e": 30221, "s": 30199, "text": "Complexity Analysis: " }, { "code": null, "e": 30308, "s": 30221, "text": "Time Complexity: O(sum*n), where sum is the β€˜target sum’ and β€˜n’ is the size of array." }, { "code": null, "e": 30418, "s": 30308, "text": "Auxiliary Space: O(sum*n) + O(n) -> O(sum*n) = the size of 2-D array is sum*n and O(n)=auxiliary stack space." }, { "code": null, "e": 30632, "s": 30418, "text": "Subset Sum Problem in O(sum) space Perfect Sum Problem (Print all subsets with given sum)Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 30637, "s": 30632, "text": "vt_m" }, { "code": null, "e": 30652, "s": 30637, "text": "sahilshelangia" }, { "code": null, "e": 30672, "s": 30652, "text": "pallagolladwarakesh" }, { "code": null, "e": 30683, "s": 30672, "text": "ayushmaanj" }, { "code": null, "e": 30697, "s": 30683, "text": "kevinjoseph61" }, { "code": null, "e": 30709, "s": 30697, "text": "bidibaaz123" }, { "code": null, "e": 30725, "s": 30709, "text": "shethnisarg1998" }, { "code": null, "e": 30741, "s": 30725, "text": "Dhananjay_Kumar" }, { "code": null, "e": 30755, "s": 30741, "text": "sguptashivang" }, { "code": null, "e": 30773, "s": 30755, "text": "kaushal kishore 1" }, { "code": null, "e": 30787, "s": 30773, "text": "ankitkumar774" }, { "code": null, "e": 30796, "s": 30787, "text": "18ucs175" }, { "code": null, "e": 30805, "s": 30796, "text": "mukesh07" }, { "code": null, "e": 30816, "s": 30805, "text": "decode2207" }, { "code": null, "e": 30827, "s": 30816, "text": "shree_hari" }, { "code": null, "e": 30841, "s": 30827, "text": "lokeshpotta20" }, { "code": null, "e": 30854, "s": 30841, "text": "rajsanghavi9" }, { "code": null, "e": 30873, "s": 30854, "text": "shivanisinghss2110" }, { "code": null, "e": 30890, "s": 30873, "text": "arorakashish0911" }, { "code": null, "e": 30900, "s": 30890, "text": "sanskar84" }, { "code": null, "e": 30904, "s": 30900, "text": "r_c" }, { "code": null, "e": 30910, "s": 30904, "text": "Adobe" }, { "code": null, "e": 30925, "s": 30910, "text": "Adobe-Question" }, { "code": null, "e": 30932, "s": 30925, "text": "Amazon" }, { "code": null, "e": 30945, "s": 30932, "text": "Drishti-Soft" }, { "code": null, "e": 30952, "s": 30945, "text": "subset" }, { "code": null, "e": 30959, "s": 30952, "text": "Arrays" }, { "code": null, "e": 30979, "s": 30959, "text": "Dynamic Programming" }, { "code": null, "e": 30986, "s": 30979, "text": "Amazon" }, { "code": null, "e": 30992, "s": 30986, "text": "Adobe" }, { "code": null, "e": 31005, "s": 30992, "text": "Drishti-Soft" }, { "code": null, "e": 31012, "s": 31005, "text": "Arrays" }, { "code": null, "e": 31032, "s": 31012, "text": "Dynamic Programming" }, { "code": null, "e": 31039, "s": 31032, "text": "subset" }, { "code": null, "e": 31137, "s": 31039, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31152, "s": 31137, "text": "Arrays in Java" }, { "code": null, "e": 31198, "s": 31152, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 31266, "s": 31198, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 31310, "s": 31266, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 31342, "s": 31310, "text": "Largest Sum Contiguous Subarray" }, { "code": null, "e": 31374, "s": 31342, "text": "Largest Sum Contiguous Subarray" }, { "code": null, "e": 31404, "s": 31374, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 31442, "s": 31404, "text": "Longest Increasing Subsequence | DP-3" }, { "code": null, "e": 31480, "s": 31442, "text": "Longest Palindromic Substring | Set 1" } ]
Subtract minutes from current time using Calendar.add() method in Java
Import the following package for Calendar class in Java. import java.util.Calendar; Firstly, create a Calendar object and display the current date and time. Calendar calendar = Calendar.getInstance(); System.out.println("Current Date and Time = " + calendar.getTime()); Now, let us decrement the minutes using the calendar.add() method and Calendar.MINUTE constant. Set a negative value since you want to decrease the minutes. calendar.add(Calendar.MINUTE, -15); Live Demo import java.util.Calendar; public class Demo { public static void main(String[] args) { Calendar calendar = Calendar.getInstance(); System.out.println("Current Date = " + calendar.getTime()); // Subtract 15 minutes from current date calendar.add(Calendar.MINUTE, -15); System.out.println("Updated Date = " + calendar.getTime()); } } Current Date = Thu Nov 22 16:26:19 UTC 2018 Updated Date = Thu Nov 22 16:11:19 UTC 2018
[ { "code": null, "e": 1244, "s": 1187, "text": "Import the following package for Calendar class in Java." }, { "code": null, "e": 1271, "s": 1244, "text": "import java.util.Calendar;" }, { "code": null, "e": 1344, "s": 1271, "text": "Firstly, create a Calendar object and display the current date and time." }, { "code": null, "e": 1457, "s": 1344, "text": "Calendar calendar = Calendar.getInstance();\nSystem.out.println(\"Current Date and Time = \" + calendar.getTime());" }, { "code": null, "e": 1614, "s": 1457, "text": "Now, let us decrement the minutes using the calendar.add() method and Calendar.MINUTE constant. Set a negative value since you want to decrease the minutes." }, { "code": null, "e": 1650, "s": 1614, "text": "calendar.add(Calendar.MINUTE, -15);" }, { "code": null, "e": 1661, "s": 1650, "text": " Live Demo" }, { "code": null, "e": 2030, "s": 1661, "text": "import java.util.Calendar;\npublic class Demo {\n public static void main(String[] args) {\n Calendar calendar = Calendar.getInstance();\n System.out.println(\"Current Date = \" + calendar.getTime());\n // Subtract 15 minutes from current date\n calendar.add(Calendar.MINUTE, -15);\n System.out.println(\"Updated Date = \" + calendar.getTime());\n }\n}" }, { "code": null, "e": 2118, "s": 2030, "text": "Current Date = Thu Nov 22 16:26:19 UTC 2018\nUpdated Date = Thu Nov 22 16:11:19 UTC 2018" } ]
Friend class and function in C++ - GeeksforGeeks
15 Mar, 2021 Friend Class A friend class can access private and protected members of other class in which it is declared as friend. It is sometimes useful to allow a particular class to access private members of other class. For example, a LinkedList class may be allowed to access private members of Node. CPP class Node {private: int key; Node* next; /* Other members of Node Class */ // Now class LinkedList can // access private members of Node friend class LinkedList;}; Friend Function Like friend class, a friend function can be given a special grant to access private and protected members. A friend function can be: a) A member of another class b) A global function CPP class Node {private: int key; Node* next; /* Other members of Node Class */ friend int LinkedList::search(); // Only search() of linkedList // can access internal members}; Following are some important points about friend functions and classes: 1) Friends should be used only for limited purpose. too many functions or external classes are declared as friends of a class with protected or private data, it lessens the value of encapsulation of separate classes in object-oriented programming.2) Friendship is not mutual. If class A is a friend of B, then B doesn’t become a friend of A automatically.3) Friendship is not inherited (See this for more details)4) The concept of friends is not there in Java. A simple and complete C++ program to demonstrate friend Class CPP #include <iostream>class A {private: int a; public: A() { a = 0; } friend class B; // Friend Class}; class B {private: int b; public: void showA(A& x) { // Since B is friend of A, it can access // private members of A std::cout << "A::a=" << x.a; }}; int main(){ A a; B b; b.showA(a); return 0;} Output: A::a=0 A simple and complete C++ program to demonstrate friend function of another class CPP #include <iostream> class B; class A {public: void showB(B&);}; class B {private: int b; public: B() { b = 0; } friend void A::showB(B& x); // Friend function}; void A::showB(B& x){ // Since showB() is friend of B, it can // access private members of B std::cout << "B::b = " << x.b;} int main(){ A a; B x; a.showB(x); return 0;} Output: B::b = 0 A simple and complete C++ program to demonstrate global friend CPP #include <iostream> class A { int a; public: A() { a = 0; } // global friend function friend void showA(A&);}; void showA(A& x){ // Since showA() is a friend, it can access // private members of A std::cout << "A::a=" << x.a;} int main(){ A a; showA(a); return 0;} Output: A::a = 0 References: http://en.wikipedia.org/wiki/Friend_class http://en.wikipedia.org/wiki/Friend_function http://www.cprogramming.com/tutorial/friends.html http://www.parashift.com/c++-faq/friends-and-encap.htmlPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above. ajith211 jeevanyasa cpp-friend C++ School Programming CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Socket Programming in C/C++ Operator Overloading in C++ Multidimensional Arrays in C / C++ vector erase() and clear() in C++ rand() and srand() in C/C++ Python Dictionary Reverse a string in Java Interfaces in Java Operator Overloading in C++ C++ Data Types
[ { "code": null, "e": 23759, "s": 23731, "text": "\n15 Mar, 2021" }, { "code": null, "e": 24055, "s": 23759, "text": "Friend Class A friend class can access private and protected members of other class in which it is declared as friend. It is sometimes useful to allow a particular class to access private members of other class. For example, a LinkedList class may be allowed to access private members of Node. " }, { "code": null, "e": 24059, "s": 24055, "text": "CPP" }, { "code": "class Node {private: int key; Node* next; /* Other members of Node Class */ // Now class LinkedList can // access private members of Node friend class LinkedList;};", "e": 24244, "s": 24059, "text": null }, { "code": null, "e": 24445, "s": 24244, "text": "Friend Function Like friend class, a friend function can be given a special grant to access private and protected members. A friend function can be: a) A member of another class b) A global function " }, { "code": null, "e": 24449, "s": 24445, "text": "CPP" }, { "code": "class Node {private: int key; Node* next; /* Other members of Node Class */ friend int LinkedList::search(); // Only search() of linkedList // can access internal members};", "e": 24641, "s": 24449, "text": null }, { "code": null, "e": 25238, "s": 24641, "text": "Following are some important points about friend functions and classes: 1) Friends should be used only for limited purpose. too many functions or external classes are declared as friends of a class with protected or private data, it lessens the value of encapsulation of separate classes in object-oriented programming.2) Friendship is not mutual. If class A is a friend of B, then B doesn’t become a friend of A automatically.3) Friendship is not inherited (See this for more details)4) The concept of friends is not there in Java. A simple and complete C++ program to demonstrate friend Class " }, { "code": null, "e": 25242, "s": 25238, "text": "CPP" }, { "code": "#include <iostream>class A {private: int a; public: A() { a = 0; } friend class B; // Friend Class}; class B {private: int b; public: void showA(A& x) { // Since B is friend of A, it can access // private members of A std::cout << \"A::a=\" << x.a; }}; int main(){ A a; B b; b.showA(a); return 0;}", "e": 25592, "s": 25242, "text": null }, { "code": null, "e": 25601, "s": 25592, "text": "Output: " }, { "code": null, "e": 25608, "s": 25601, "text": "A::a=0" }, { "code": null, "e": 25692, "s": 25608, "text": "A simple and complete C++ program to demonstrate friend function of another class " }, { "code": null, "e": 25696, "s": 25692, "text": "CPP" }, { "code": "#include <iostream> class B; class A {public: void showB(B&);}; class B {private: int b; public: B() { b = 0; } friend void A::showB(B& x); // Friend function}; void A::showB(B& x){ // Since showB() is friend of B, it can // access private members of B std::cout << \"B::b = \" << x.b;} int main(){ A a; B x; a.showB(x); return 0;}", "e": 26059, "s": 25696, "text": null }, { "code": null, "e": 26068, "s": 26059, "text": "Output: " }, { "code": null, "e": 26077, "s": 26068, "text": "B::b = 0" }, { "code": null, "e": 26142, "s": 26077, "text": "A simple and complete C++ program to demonstrate global friend " }, { "code": null, "e": 26146, "s": 26142, "text": "CPP" }, { "code": "#include <iostream> class A { int a; public: A() { a = 0; } // global friend function friend void showA(A&);}; void showA(A& x){ // Since showA() is a friend, it can access // private members of A std::cout << \"A::a=\" << x.a;} int main(){ A a; showA(a); return 0;}", "e": 26442, "s": 26146, "text": null }, { "code": null, "e": 26451, "s": 26442, "text": "Output: " }, { "code": null, "e": 26460, "s": 26451, "text": "A::a = 0" }, { "code": null, "e": 26790, "s": 26460, "text": "References: http://en.wikipedia.org/wiki/Friend_class http://en.wikipedia.org/wiki/Friend_function http://www.cprogramming.com/tutorial/friends.html http://www.parashift.com/c++-faq/friends-and-encap.htmlPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 26799, "s": 26790, "text": "ajith211" }, { "code": null, "e": 26810, "s": 26799, "text": "jeevanyasa" }, { "code": null, "e": 26821, "s": 26810, "text": "cpp-friend" }, { "code": null, "e": 26825, "s": 26821, "text": "C++" }, { "code": null, "e": 26844, "s": 26825, "text": "School Programming" }, { "code": null, "e": 26848, "s": 26844, "text": "CPP" }, { "code": null, "e": 26946, "s": 26848, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26955, "s": 26946, "text": "Comments" }, { "code": null, "e": 26968, "s": 26955, "text": "Old Comments" }, { "code": null, "e": 26996, "s": 26968, "text": "Socket Programming in C/C++" }, { "code": null, "e": 27024, "s": 26996, "text": "Operator Overloading in C++" }, { "code": null, "e": 27059, "s": 27024, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 27093, "s": 27059, "text": "vector erase() and clear() in C++" }, { "code": null, "e": 27121, "s": 27093, "text": "rand() and srand() in C/C++" }, { "code": null, "e": 27139, "s": 27121, "text": "Python Dictionary" }, { "code": null, "e": 27164, "s": 27139, "text": "Reverse a string in Java" }, { "code": null, "e": 27183, "s": 27164, "text": "Interfaces in Java" }, { "code": null, "e": 27211, "s": 27183, "text": "Operator Overloading in C++" } ]
K’th Non-repeating Character in Python using List Comprehension and OrderedDict
In this article, we will learn about K’th Non-repeating Character in Python using List Comprehension and OrderedDict. To do so we take the help of inbuilt constructs available in Python. 1. First, we form a dictionary data from the input. 2. Now we count the frequency of each character. 3. Now we extract the list of all keys whose value equals 1. 4. Finally, we return k-1 character. from collections import OrderedDict import itertools def kthRepeating(inp,k): # returns a dictionary data dict=OrderedDict.fromkeys(inp,0) # frequency of each character for ch in inp: dict[ch]+=1 # now extract list of all keys whose value is 1 nonRepeatDict = [key for (key,value) in dict.items() if value==1] # returns (k-1)th character if len(nonRepeatDict) < k: return 'no ouput.' else: return nonRepeatDict[k-1] # Driver function if __name__ == "__main__": inp = "tutorialspoint" k = 3 print (kthRepeating(inp, k)) a In this article, we found the K’th Non-repeating Character in Python using List Comprehension and OrderedDict.
[ { "code": null, "e": 1249, "s": 1062, "text": "In this article, we will learn about K’th Non-repeating Character in Python using List Comprehension and OrderedDict. To do so we take the help of inbuilt constructs available in Python." }, { "code": null, "e": 1448, "s": 1249, "text": "1. First, we form a dictionary data from the input.\n2. Now we count the frequency of each character.\n3. Now we extract the list of all keys whose value equals 1.\n4. Finally, we return k-1 character." }, { "code": null, "e": 2024, "s": 1448, "text": "from collections import OrderedDict\nimport itertools\ndef kthRepeating(inp,k):\n # returns a dictionary data\n dict=OrderedDict.fromkeys(inp,0)\n # frequency of each character\n for ch in inp:\n dict[ch]+=1\n # now extract list of all keys whose value is 1\n nonRepeatDict = [key for (key,value) in dict.items() if value==1]\n # returns (k-1)th character\n if len(nonRepeatDict) < k:\n return 'no ouput.'\n else:\n return nonRepeatDict[k-1]\n# Driver function\nif __name__ == \"__main__\":\n inp = \"tutorialspoint\"\n k = 3\n print (kthRepeating(inp, k))" }, { "code": null, "e": 2026, "s": 2024, "text": "a" }, { "code": null, "e": 2137, "s": 2026, "text": "In this article, we found the K’th Non-repeating Character in Python using List Comprehension and OrderedDict." } ]
Apply function to every row in a Pandas DataFrame in Python
In this tutorial, we are going to learn about the most common methods of a list i.e.., append() and extend(). Let's see them one by one. It is used to apply a function to every row of a DataFrame. For example, if we want to multiply all the numbers from each and add it as a new column, then apply() method is beneficial. Let's see different ways to achieve it. # importing the pandas package import pandas as pd # function to multiply def multiply(x, y): return x * y # creating a dictionary for DataFrame data = { 'Maths': [10, 34, 53], 'Programming': [23, 12, 43] } # creating DataFrame using the data data_frame = pd.DataFrame(data) # displaying DataFrame print('--------------------Before------------------') print(data_frame) print() # applying the function multiply data_frame['Multiply'] = data_frame.apply(lambda row : multiply(row['Maths'], row[' Programming']), axis = 1) # displaying DataFrame print('--------------------After------------------') print(data_frame) If you run the above program, you will get the following results. --------------------Before------------------ Maths Programming 0 10 23 1 34 12 2 53 43 --------------------After------------------ Maths Programming Multiply 0 10 23 230 1 34 12 408 2 53 43 2279 We can also use predefined functions like sum, pow, etc.., # importing the pandas package import pandas as pd # creating a dictionary for DataFrame data = { 'Maths': [10, 34, 53], 'Programming': [23, 12, 43] } # creating DataFrame using the data data_frame = pd.DataFrame(data) # displaying DataFrame print('--------------------Before------------------') print(data_frame) print() # applying the function multiply # using built-in sum function data_frame['Multiply'] = data_frame.apply(sum, axis = 1) # displaying DataFrame print('--------------------After------------------') print(data_frame) If you run the above program, you will get the following results. --------------------Before------------------ Maths Programming 0 10 23 1 34 12 2 53 43 --------------------After------------------ Maths Programming Multiply 0 10 23 33 1 34 12 46 2 53 43 96 We can also use functions from the numpy module. Let's see one example. # importing the pandas package import pandas as pd # importing numpy module for functions import numpy as np # creating a dictionary for DataFrame data = { 'Maths': [10, 34, 53], 'Programming': [23, 12, 43] } # creating DataFrame using the data data_frame = pd.DataFrame(data) # displaying DataFrame print('--------------------Before------------------') print(data_frame) print() # applying the function multiply # using sum function from the numpy module data_frame['Multiply'] = data_frame.apply(np.sum, axis = 1) # displaying DataFrame print('--------------------After------------------') print(data_frame) If you run the above program, you will get the following results. --------------------Before------------------ Maths Programming 0 10 23 1 34 12 2 53 43 --------------------After------------------ Maths Programming Multiply 0 10 23 33 1 34 12 46 2 53 43 96 In the above ways, we can use apply() method of DataFrame to apply a function for all the rows. If you have any doubts regarding the tutorial, mention them in the comment section.
[ { "code": null, "e": 1199, "s": 1062, "text": "In this tutorial, we are going to learn about the most common methods of a list i.e.., append() and extend(). Let's see them one by one." }, { "code": null, "e": 1424, "s": 1199, "text": "It is used to apply a function to every row of a DataFrame. For example, if we want to multiply all the numbers from each and add it as a new column, then apply() method is beneficial. Let's see different ways to achieve it." }, { "code": null, "e": 2048, "s": 1424, "text": "# importing the pandas package\nimport pandas as pd\n# function to multiply\ndef multiply(x, y):\n return x * y\n# creating a dictionary for DataFrame\ndata = {\n 'Maths': [10, 34, 53],\n 'Programming': [23, 12, 43]\n}\n# creating DataFrame using the data\ndata_frame = pd.DataFrame(data)\n# displaying DataFrame\nprint('--------------------Before------------------')\nprint(data_frame)\nprint()\n# applying the function multiply\ndata_frame['Multiply'] = data_frame.apply(lambda row : multiply(row['Maths'], row['\nProgramming']), axis = 1)\n# displaying DataFrame\nprint('--------------------After------------------')\nprint(data_frame)" }, { "code": null, "e": 2114, "s": 2048, "text": "If you run the above program, you will get the following results." }, { "code": null, "e": 2309, "s": 2114, "text": "--------------------Before------------------\nMaths Programming\n0 10 23\n1 34 12\n2 53 43\n--------------------After------------------\nMaths Programming Multiply\n0 10 23 230\n1 34 12 408\n2 53 43 2279" }, { "code": null, "e": 2368, "s": 2309, "text": "We can also use predefined functions like sum, pow, etc..," }, { "code": null, "e": 2910, "s": 2368, "text": "# importing the pandas package\nimport pandas as pd\n# creating a dictionary for DataFrame\ndata = {\n 'Maths': [10, 34, 53],\n 'Programming': [23, 12, 43]\n}\n# creating DataFrame using the data\ndata_frame = pd.DataFrame(data)\n# displaying DataFrame\nprint('--------------------Before------------------')\nprint(data_frame)\nprint()\n# applying the function multiply\n# using built-in sum function\ndata_frame['Multiply'] = data_frame.apply(sum, axis = 1)\n# displaying DataFrame\nprint('--------------------After------------------')\nprint(data_frame)" }, { "code": null, "e": 2976, "s": 2910, "text": "If you run the above program, you will get the following results." }, { "code": null, "e": 3167, "s": 2976, "text": "--------------------Before------------------\nMaths Programming\n0 10 23\n1 34 12\n2 53 43\n--------------------After------------------\nMaths Programming Multiply\n0 10 23 33\n1 34 12 46\n2 53 43 96" }, { "code": null, "e": 3239, "s": 3167, "text": "We can also use functions from the numpy module. Let's see one example." }, { "code": null, "e": 3855, "s": 3239, "text": "# importing the pandas package\nimport pandas as pd\n# importing numpy module for functions\nimport numpy as np\n# creating a dictionary for DataFrame\ndata = {\n 'Maths': [10, 34, 53],\n 'Programming': [23, 12, 43]\n}\n# creating DataFrame using the data\ndata_frame = pd.DataFrame(data)\n# displaying DataFrame\nprint('--------------------Before------------------')\nprint(data_frame)\nprint()\n# applying the function multiply\n# using sum function from the numpy module\ndata_frame['Multiply'] = data_frame.apply(np.sum, axis = 1)\n# displaying DataFrame\nprint('--------------------After------------------')\nprint(data_frame)" }, { "code": null, "e": 3921, "s": 3855, "text": "If you run the above program, you will get the following results." }, { "code": null, "e": 4112, "s": 3921, "text": "--------------------Before------------------\nMaths Programming\n0 10 23\n1 34 12\n2 53 43\n--------------------After------------------\nMaths Programming Multiply\n0 10 23 33\n1 34 12 46\n2 53 43 96" }, { "code": null, "e": 4292, "s": 4112, "text": "In the above ways, we can use apply() method of DataFrame to apply a function for all the rows. If you have any doubts regarding the tutorial, mention them in the comment section." } ]
How to convert DateTime to a number in MySQL?
To convert the date time to a number in MySQL, the syntax is as follows βˆ’ SELECT UNIX_TIMESTAMP(yourColumnName) as anyVariableName FROM yourTableName; To understand the above syntax, let us create a table. The query to create a table is as follows βˆ’ mysql> create table DateTimeToNumberDemo -> ( -> Id int NOT NULL AUTO_INCREMENT, -> releasedDate datetime, -> PRIMARY KEY(Id) -> ); Query OK, 0 rows affected (0.46 sec) Insert some records in the table using insert command. The query is as follows βˆ’ mysql> insert into DateTimeToNumberDemo(releasedDate) values(now()); Query OK, 1 row affected (0.19 sec) mysql> insert into DateTimeToNumberDemo(releasedDate) values(curdate()); Query OK, 1 row affected (0.24 sec) mysql> insert into DateTimeToNumberDemo(releasedDate) values('1978-01-19'); Query OK, 1 row affected (0.55 sec) mysql> insert into DateTimeToNumberDemo(releasedDate) values('2016-09-13'); Query OK, 1 row affected (0.46 sec) mysql> insert into DateTimeToNumberDemo(releasedDate) values('2017-11-12'); Query OK, 1 row affected (0.22 sec) mysql> insert into DateTimeToNumberDemo(releasedDate) values('2018-12-09'); Query OK, 1 row affected (0.21 sec) Display all records from the table using select statement. The query is as follows βˆ’ mysql> select *from DateTimeToNumberDemo; The following is the output βˆ’ +----+---------------------+ | Id | releasedDate | +----+---------------------+ | 1 | 2019-01-12 21:20:57 | | 2 | 2019-01-12 00:00:00 | | 3 | 1978-01-19 00:00:00 | | 4 | 2016-09-13 00:00:00 | | 5 | 2017-11-12 00:00:00 | | 6 | 2018-12-09 00:00:00 | +----+---------------------+ 6 rows in set (0.00 sec) The following is the query to convert date time to a number βˆ’ mysql> select unix_timestamp(releasedDate) as DateToNumber from DateTimeToNumberDemo; The following is the output βˆ’ +--------------+ | DateToNumber | +--------------+ | 1547308257 | | 1547231400 | | 253996200 | | 1473705000 | | 1510425000 | | 1544293800 | +--------------+ 6 rows in set (0.00 sec)
[ { "code": null, "e": 1136, "s": 1062, "text": "To convert the date time to a number in MySQL, the syntax is as follows βˆ’" }, { "code": null, "e": 1213, "s": 1136, "text": "SELECT UNIX_TIMESTAMP(yourColumnName) as anyVariableName FROM yourTableName;" }, { "code": null, "e": 1312, "s": 1213, "text": "To understand the above syntax, let us create a table. The query to create a table is as follows βˆ’" }, { "code": null, "e": 1496, "s": 1312, "text": "mysql> create table DateTimeToNumberDemo\n -> (\n -> Id int NOT NULL AUTO_INCREMENT,\n -> releasedDate datetime,\n -> PRIMARY KEY(Id)\n -> );\nQuery OK, 0 rows affected (0.46 sec)" }, { "code": null, "e": 1577, "s": 1496, "text": "Insert some records in the table using insert command. The query is as follows βˆ’" }, { "code": null, "e": 2244, "s": 1577, "text": "mysql> insert into DateTimeToNumberDemo(releasedDate) values(now());\nQuery OK, 1 row affected (0.19 sec)\n\nmysql> insert into DateTimeToNumberDemo(releasedDate) values(curdate());\nQuery OK, 1 row affected (0.24 sec)\n\nmysql> insert into\nDateTimeToNumberDemo(releasedDate) values('1978-01-19');\nQuery OK, 1 row affected (0.55 sec)\n\nmysql> insert into DateTimeToNumberDemo(releasedDate) values('2016-09-13');\nQuery OK, 1 row affected (0.46 sec)\n\nmysql> insert into DateTimeToNumberDemo(releasedDate) values('2017-11-12');\nQuery OK, 1 row affected (0.22 sec)\n\nmysql> insert into DateTimeToNumberDemo(releasedDate) values('2018-12-09');\nQuery OK, 1 row affected (0.21 sec)" }, { "code": null, "e": 2329, "s": 2244, "text": "Display all records from the table using select statement. The query is as follows βˆ’" }, { "code": null, "e": 2371, "s": 2329, "text": "mysql> select *from DateTimeToNumberDemo;" }, { "code": null, "e": 2401, "s": 2371, "text": "The following is the output βˆ’" }, { "code": null, "e": 2709, "s": 2401, "text": "+----+---------------------+\n| Id | releasedDate |\n+----+---------------------+\n| 1 | 2019-01-12 21:20:57 |\n| 2 | 2019-01-12 00:00:00 |\n| 3 | 1978-01-19 00:00:00 |\n| 4 | 2016-09-13 00:00:00 |\n| 5 | 2017-11-12 00:00:00 |\n| 6 | 2018-12-09 00:00:00 |\n+----+---------------------+\n6 rows in set (0.00 sec)" }, { "code": null, "e": 2771, "s": 2709, "text": "The following is the query to convert date time to a number βˆ’" }, { "code": null, "e": 2857, "s": 2771, "text": "mysql> select unix_timestamp(releasedDate) as DateToNumber from DateTimeToNumberDemo;" }, { "code": null, "e": 2887, "s": 2857, "text": "The following is the output βˆ’" }, { "code": null, "e": 3082, "s": 2887, "text": "+--------------+\n| DateToNumber |\n+--------------+\n| 1547308257 |\n| 1547231400 |\n| 253996200 |\n| 1473705000 |\n| 1510425000 |\n| 1544293800 |\n+--------------+\n6 rows in set (0.00 sec)" } ]
Longest Bitonic Subsequence
A sequence is said to be bitonic if it is first increasing and then decreasing. In this problem, an array of all positive integers is given. We have to find a subsequence which is increasing first and then decreasing. To solve this problem, we will define two subsequences, they are the Longest Increasing Subsequence and the Longest Decreasing Subsequence. The LIS array will hold the length of increasing subsequence ending with array[i]. The LDS array will store the length of decreasing subsequence starting from array[i]. Using these two arrays, we can get the length of longest bitonic subsequence. Input: A sequence of numbers. {0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15} Output: The longest bitonic subsequence length. Here it is 7. longBitonicSub(array, size) Input: The array, the size of an array. Output βˆ’ Max length of longest bitonic subsequence. Begin define incSubSeq of size same as the array size initially fill all entries to 1 for incSubSeq for i := 1 to size -1, do for j := 0 to i-1, do if array[i] > array[j] and incSubSeq[i] < incSubSum[j] + 1, then incSubSum[i] := incSubSum[j] + 1 done done define decSubSeq of size same as the array size. initially fill all entries to 1 for incSubSeq for i := size - 2 down to 0, do for j := size - 1 down to i+1, do if array[i] > array[j] and decSubSeq[i] < decSubSum[j] + 1, then decSubSeq [i] := decSubSeq [j] + 1 done done max := incSubSeq[0] + decSubSeq[0] – 1 for i := 1 to size, do if incSubSeq[i] + decSubSeq[i] – 1 > max, then max := incSubSeq[i] + decSubSeq[i] – 1 done return max End #include<iostream> using namespace std; int longBitonicSub( int arr[], int size ) { int *increasingSubSeq = new int[size]; //create increasing sub sequence array for (int i = 0; i < size; i++) increasingSubSeq[i] = 1; //set all values to 1 for (int i = 1; i < size; i++) //compute values from left ot right for (int j = 0; j < i; j++) if (arr[i] > arr[j] && increasingSubSeq[i] < increasingSubSeq[j] + 1) increasingSubSeq[i] = increasingSubSeq[j] + 1; int *decreasingSubSeq = new int [size]; //create decreasing sub sequence array for (int i = 0; i < size; i++) decreasingSubSeq[i] = 1; //set all values to 1 for (int i = size-2; i >= 0; i--) //compute values from left ot right for (int j = size-1; j > i; j--) if (arr[i] > arr[j] && decreasingSubSeq[i] < decreasingSubSeq[j] + 1) decreasingSubSeq[i] = decreasingSubSeq[j] + 1; int max = increasingSubSeq[0] + decreasingSubSeq[0] - 1; for (int i = 1; i < size; i++) //find max length if (increasingSubSeq[i] + decreasingSubSeq[i] - 1 > max) max = increasingSubSeq[i] + decreasingSubSeq[i] - 1; return max; } int main() { int arr[] = {0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15}; int n = 16; cout << "Length of longest bitonic subsequence is " << longBitonicSub(arr, n); } Length of longest bitonic subsequence is 7
[ { "code": null, "e": 1280, "s": 1062, "text": "A sequence is said to be bitonic if it is first increasing and then decreasing. In this problem, an array of all positive integers is given. We have to find a subsequence which is increasing first and then decreasing." }, { "code": null, "e": 1667, "s": 1280, "text": "To solve this problem, we will define two subsequences, they are the Longest Increasing Subsequence and the Longest Decreasing Subsequence. The LIS array will hold the length of increasing subsequence ending with array[i]. The LDS array will store the length of decreasing subsequence starting from array[i]. Using these two arrays, we can get the length of longest bitonic subsequence." }, { "code": null, "e": 1814, "s": 1667, "text": "Input:\nA sequence of numbers. {0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15}\nOutput:\nThe longest bitonic subsequence length. Here it is 7." }, { "code": null, "e": 1842, "s": 1814, "text": "longBitonicSub(array, size)" }, { "code": null, "e": 1882, "s": 1842, "text": "Input: The array, the size of an array." }, { "code": null, "e": 1934, "s": 1882, "text": "Output βˆ’ Max length of longest bitonic subsequence." }, { "code": null, "e": 2718, "s": 1934, "text": "Begin\n define incSubSeq of size same as the array size\n initially fill all entries to 1 for incSubSeq\n\n for i := 1 to size -1, do\n for j := 0 to i-1, do\n if array[i] > array[j] and incSubSeq[i] < incSubSum[j] + 1, then incSubSum[i] := incSubSum[j] + 1\n done\n done\n\n define decSubSeq of size same as the array size.\n initially fill all entries to 1 for incSubSeq\n\n for i := size - 2 down to 0, do\n for j := size - 1 down to i+1, do\n if array[i] > array[j] and decSubSeq[i] < decSubSum[j] + 1, then decSubSeq [i] := decSubSeq [j] + 1\n done\n done\n\n max := incSubSeq[0] + decSubSeq[0] – 1\n for i := 1 to size, do\n if incSubSeq[i] + decSubSeq[i] – 1 > max, then max := incSubSeq[i] + decSubSeq[i] – 1\n done\n\n return max\nEnd" }, { "code": null, "e": 4134, "s": 2718, "text": "#include<iostream>\nusing namespace std;\n\nint longBitonicSub( int arr[], int size ) {\n int *increasingSubSeq = new int[size]; //create increasing sub sequence array\n for (int i = 0; i < size; i++)\n increasingSubSeq[i] = 1; //set all values to 1\n\n for (int i = 1; i < size; i++) //compute values from left ot right\n for (int j = 0; j < i; j++)\n if (arr[i] > arr[j] && increasingSubSeq[i] < increasingSubSeq[j] + 1)\n increasingSubSeq[i] = increasingSubSeq[j] + 1;\n\n int *decreasingSubSeq = new int [size]; //create decreasing sub sequence array\n for (int i = 0; i < size; i++)\n decreasingSubSeq[i] = 1; //set all values to 1\n\n for (int i = size-2; i >= 0; i--) //compute values from left ot right\n for (int j = size-1; j > i; j--)\n if (arr[i] > arr[j] && decreasingSubSeq[i] < decreasingSubSeq[j] + 1)\n decreasingSubSeq[i] = decreasingSubSeq[j] + 1;\n\n int max = increasingSubSeq[0] + decreasingSubSeq[0] - 1;\n for (int i = 1; i < size; i++) //find max length\n if (increasingSubSeq[i] + decreasingSubSeq[i] - 1 > max)\n max = increasingSubSeq[i] + decreasingSubSeq[i] - 1;\n return max;\n}\n\nint main() {\n int arr[] = {0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15};\n int n = 16;\n cout << \"Length of longest bitonic subsequence is \" << longBitonicSub(arr, n);\n}" }, { "code": null, "e": 4177, "s": 4134, "text": "Length of longest bitonic subsequence is 7" } ]
Apache Kafka - Integration With Spark
In this chapter, we will be discussing about how to integrate Apache Kafka with Spark Streaming API. Spark Streaming API enables scalable, high-throughput, fault-tolerant stream processing of live data streams. Data can be ingested from many sources like Kafka, Flume, Twitter, etc., and can be processed using complex algorithms such as high-level functions like map, reduce, join and window. Finally, processed data can be pushed out to filesystems, databases, and live dash-boards. Resilient Distributed Datasets (RDD) is a fundamental data structure of Spark. It is an immutable distributed collection of objects. Each dataset in RDD is divided into logical partitions, which may be computed on different nodes of the cluster. Kafka is a potential messaging and integration platform for Spark streaming. Kafka act as the central hub for real-time streams of data and are processed using complex algorithms in Spark Streaming. Once the data is processed, Spark Streaming could be publishing results into yet another Kafka topic or store in HDFS, databases or dashboards. The following diagram depicts the conceptual flow. Now, let us go through Kafka-Spark API’s in detail. It represents configuration for a Spark application. Used to set various Spark parameters as key-value pairs. SparkConf class has the following methods βˆ’ set(string key, string value) βˆ’ set configuration variable. set(string key, string value) βˆ’ set configuration variable. remove(string key) βˆ’ remove key from the configuration. remove(string key) βˆ’ remove key from the configuration. setAppName(string name) βˆ’ set application name for your application. setAppName(string name) βˆ’ set application name for your application. get(string key) βˆ’ get key get(string key) βˆ’ get key This is the main entry point for Spark functionality. A SparkContext represents the connection to a Spark cluster, and can be used to create RDDs, accumulators and broadcast variables on the cluster. The signature is defined as shown below. public StreamingContext(String master, String appName, Duration batchDuration, String sparkHome, scala.collection.Seq<String> jars, scala.collection.Map<String,String> environment) master βˆ’ cluster URL to connect to (e.g. mesos://host:port, spark://host:port, local[4]). master βˆ’ cluster URL to connect to (e.g. mesos://host:port, spark://host:port, local[4]). appName βˆ’ a name for your job, to display on the cluster web UI appName βˆ’ a name for your job, to display on the cluster web UI batchDuration βˆ’ the time interval at which streaming data will be divided into batches batchDuration βˆ’ the time interval at which streaming data will be divided into batches public StreamingContext(SparkConf conf, Duration batchDuration) Create a StreamingContext by providing the configuration necessary for a new SparkContext. conf βˆ’ Spark parameters conf βˆ’ Spark parameters batchDuration βˆ’ the time interval at which streaming data will be divided into batches batchDuration βˆ’ the time interval at which streaming data will be divided into batches KafkaUtils API is used to connect the Kafka cluster to Spark streaming. This API has the signifi-cant method createStream signature defined as below. public static ReceiverInputDStream<scala.Tuple2<String,String>> createStream( StreamingContext ssc, String zkQuorum, String groupId, scala.collection.immutable.Map<String,Object> topics, StorageLevel storageLevel) The above shown method is used to Create an input stream that pulls messages from Kafka Brokers. ssc βˆ’ StreamingContext object. ssc βˆ’ StreamingContext object. zkQuorum βˆ’ Zookeeper quorum. zkQuorum βˆ’ Zookeeper quorum. groupId βˆ’ The group id for this consumer. groupId βˆ’ The group id for this consumer. topics βˆ’ return a map of topics to consume. topics βˆ’ return a map of topics to consume. storageLevel βˆ’ Storage level to use for storing the received objects. storageLevel βˆ’ Storage level to use for storing the received objects. KafkaUtils API has another method createDirectStream, which is used to create an input stream that directly pulls messages from Kafka Brokers without using any receiver. This stream can guarantee that each message from Kafka is included in transformations exactly once. The sample application is done in Scala. To compile the application, please download and install sbt, scala build tool (similar to maven). The main application code is presented below. import java.util.HashMap import org.apache.kafka.clients.producer.{KafkaProducer, ProducerConfig, Produc-erRecord} import org.apache.spark.SparkConf import org.apache.spark.streaming._ import org.apache.spark.streaming.kafka._ object KafkaWordCount { def main(args: Array[String]) { if (args.length < 4) { System.err.println("Usage: KafkaWordCount <zkQuorum><group> <topics> <numThreads>") System.exit(1) } val Array(zkQuorum, group, topics, numThreads) = args val sparkConf = new SparkConf().setAppName("KafkaWordCount") val ssc = new StreamingContext(sparkConf, Seconds(2)) ssc.checkpoint("checkpoint") val topicMap = topics.split(",").map((_, numThreads.toInt)).toMap val lines = KafkaUtils.createStream(ssc, zkQuorum, group, topicMap).map(_._2) val words = lines.flatMap(_.split(" ")) val wordCounts = words.map(x => (x, 1L)) .reduceByKeyAndWindow(_ + _, _ - _, Minutes(10), Seconds(2), 2) wordCounts.print() ssc.start() ssc.awaitTermination() } } The spark-kafka integration depends on the spark, spark streaming and spark Kafka integration jar. Create a new file build.sbt and specify the application details and its dependency. The sbt will download the necessary jar while compiling and packing the application. name := "Spark Kafka Project" version := "1.0" scalaVersion := "2.10.5" libraryDependencies += "org.apache.spark" %% "spark-core" % "1.6.0" libraryDependencies += "org.apache.spark" %% "spark-streaming" % "1.6.0" libraryDependencies += "org.apache.spark" %% "spark-streaming-kafka" % "1.6.0" Run the following command to compile and package the jar file of the application. We need to submit the jar file into the spark console to run the application. sbt package Start Kafka Producer CLI (explained in the previous chapter), create a new topic called my-first-topic and provide some sample messages as shown below. Another spark test message Run the following command to submit the application to spark console. /usr/local/spark/bin/spark-submit --packages org.apache.spark:spark-streaming -kafka_2.10:1.6.0 --class "KafkaWordCount" --master local[4] target/scala-2.10/spark -kafka-project_2.10-1.0.jar localhost:2181 <group name> <topic name> <number of threads> The sample output of this application is shown below. spark console messages .. (Test,1) (spark,1) (another,1) (message,1) spark console message .. 46 Lectures 3.5 hours Arnab Chakraborty 23 Lectures 1.5 hours Mukund Kumar Mishra 16 Lectures 1 hours Nilay Mehta 52 Lectures 1.5 hours Bigdata Engineer 14 Lectures 1 hours Bigdata Engineer 23 Lectures 1 hours Bigdata Engineer Print Add Notes Bookmark this page
[ { "code": null, "e": 2068, "s": 1967, "text": "In this chapter, we will be discussing about how to integrate Apache Kafka with Spark Streaming API." }, { "code": null, "e": 2698, "s": 2068, "text": "Spark Streaming API enables scalable, high-throughput, fault-tolerant stream processing of live data streams. Data can be ingested from many sources like Kafka, Flume, Twitter, etc., and can be processed using complex algorithms such as high-level functions like map, reduce, join and window. Finally, processed data can be pushed out to filesystems, databases, and live dash-boards. Resilient Distributed Datasets (RDD) is a fundamental data structure of Spark. It is an immutable distributed collection of objects. Each dataset in RDD is divided into logical partitions, which may be computed on different nodes of the cluster." }, { "code": null, "e": 3092, "s": 2698, "text": "Kafka is a potential messaging and integration platform for Spark streaming. Kafka act as the central hub for real-time streams of data and are processed using complex algorithms in Spark Streaming. Once the data is processed, Spark Streaming could be publishing results into yet another Kafka topic or store in HDFS, databases or dashboards. The following diagram depicts the conceptual flow." }, { "code": null, "e": 3144, "s": 3092, "text": "Now, let us go through Kafka-Spark API’s in detail." }, { "code": null, "e": 3254, "s": 3144, "text": "It represents configuration for a Spark application. Used to set various Spark parameters as key-value pairs." }, { "code": null, "e": 3298, "s": 3254, "text": "SparkConf class has the following methods βˆ’" }, { "code": null, "e": 3358, "s": 3298, "text": "set(string key, string value) βˆ’ set configuration variable." }, { "code": null, "e": 3418, "s": 3358, "text": "set(string key, string value) βˆ’ set configuration variable." }, { "code": null, "e": 3474, "s": 3418, "text": "remove(string key) βˆ’ remove key from the configuration." }, { "code": null, "e": 3530, "s": 3474, "text": "remove(string key) βˆ’ remove key from the configuration." }, { "code": null, "e": 3599, "s": 3530, "text": "setAppName(string name) βˆ’ set application name for your application." }, { "code": null, "e": 3668, "s": 3599, "text": "setAppName(string name) βˆ’ set application name for your application." }, { "code": null, "e": 3694, "s": 3668, "text": "get(string key) βˆ’ get key" }, { "code": null, "e": 3720, "s": 3694, "text": "get(string key) βˆ’ get key" }, { "code": null, "e": 3961, "s": 3720, "text": "This is the main entry point for Spark functionality. A SparkContext represents the connection to a Spark cluster, and can be used to create RDDs, accumulators and broadcast variables on the cluster. The signature is defined as shown below." }, { "code": null, "e": 4150, "s": 3961, "text": "public StreamingContext(String master, String appName, Duration batchDuration, \n String sparkHome, scala.collection.Seq<String> jars, \n scala.collection.Map<String,String> environment)" }, { "code": null, "e": 4240, "s": 4150, "text": "master βˆ’ cluster URL to connect to (e.g. mesos://host:port, spark://host:port, local[4])." }, { "code": null, "e": 4330, "s": 4240, "text": "master βˆ’ cluster URL to connect to (e.g. mesos://host:port, spark://host:port, local[4])." }, { "code": null, "e": 4394, "s": 4330, "text": "appName βˆ’ a name for your job, to display on the cluster web UI" }, { "code": null, "e": 4458, "s": 4394, "text": "appName βˆ’ a name for your job, to display on the cluster web UI" }, { "code": null, "e": 4545, "s": 4458, "text": "batchDuration βˆ’ the time interval at which streaming data will be divided into batches" }, { "code": null, "e": 4632, "s": 4545, "text": "batchDuration βˆ’ the time interval at which streaming data will be divided into batches" }, { "code": null, "e": 4697, "s": 4632, "text": "public StreamingContext(SparkConf conf, Duration batchDuration)\n" }, { "code": null, "e": 4788, "s": 4697, "text": "Create a StreamingContext by providing the configuration necessary for a new SparkContext." }, { "code": null, "e": 4812, "s": 4788, "text": "conf βˆ’ Spark parameters" }, { "code": null, "e": 4836, "s": 4812, "text": "conf βˆ’ Spark parameters" }, { "code": null, "e": 4923, "s": 4836, "text": "batchDuration βˆ’ the time interval at which streaming data will be divided into batches" }, { "code": null, "e": 5010, "s": 4923, "text": "batchDuration βˆ’ the time interval at which streaming data will be divided into batches" }, { "code": null, "e": 5160, "s": 5010, "text": "KafkaUtils API is used to connect the Kafka cluster to Spark streaming. This API has the signifi-cant method createStream signature defined as below." }, { "code": null, "e": 5381, "s": 5160, "text": "public static ReceiverInputDStream<scala.Tuple2<String,String>> createStream(\n StreamingContext ssc, String zkQuorum, String groupId,\n scala.collection.immutable.Map<String,Object> topics, StorageLevel storageLevel)\n" }, { "code": null, "e": 5478, "s": 5381, "text": "The above shown method is used to Create an input stream that pulls messages from Kafka Brokers." }, { "code": null, "e": 5509, "s": 5478, "text": "ssc βˆ’ StreamingContext object." }, { "code": null, "e": 5540, "s": 5509, "text": "ssc βˆ’ StreamingContext object." }, { "code": null, "e": 5569, "s": 5540, "text": "zkQuorum βˆ’ Zookeeper quorum." }, { "code": null, "e": 5598, "s": 5569, "text": "zkQuorum βˆ’ Zookeeper quorum." }, { "code": null, "e": 5640, "s": 5598, "text": "groupId βˆ’ The group id for this consumer." }, { "code": null, "e": 5682, "s": 5640, "text": "groupId βˆ’ The group id for this consumer." }, { "code": null, "e": 5726, "s": 5682, "text": "topics βˆ’ return a map of topics to consume." }, { "code": null, "e": 5770, "s": 5726, "text": "topics βˆ’ return a map of topics to consume." }, { "code": null, "e": 5840, "s": 5770, "text": "storageLevel βˆ’ Storage level to use for storing the received objects." }, { "code": null, "e": 5910, "s": 5840, "text": "storageLevel βˆ’ Storage level to use for storing the received objects." }, { "code": null, "e": 6180, "s": 5910, "text": "KafkaUtils API has another method createDirectStream, which is used to create an input stream that directly pulls messages from Kafka Brokers without using any receiver. This stream can guarantee that each message from Kafka is included in transformations exactly once." }, { "code": null, "e": 6365, "s": 6180, "text": "The sample application is done in Scala. To compile the application, please download and install sbt, scala build tool (similar to maven). The main application code is presented below." }, { "code": null, "e": 7433, "s": 6365, "text": "import java.util.HashMap\n\nimport org.apache.kafka.clients.producer.{KafkaProducer, ProducerConfig, Produc-erRecord}\nimport org.apache.spark.SparkConf\nimport org.apache.spark.streaming._\nimport org.apache.spark.streaming.kafka._\n\nobject KafkaWordCount {\n def main(args: Array[String]) {\n if (args.length < 4) {\n System.err.println(\"Usage: KafkaWordCount <zkQuorum><group> <topics> <numThreads>\")\n System.exit(1)\n }\n\n val Array(zkQuorum, group, topics, numThreads) = args\n val sparkConf = new SparkConf().setAppName(\"KafkaWordCount\")\n val ssc = new StreamingContext(sparkConf, Seconds(2))\n ssc.checkpoint(\"checkpoint\")\n\n val topicMap = topics.split(\",\").map((_, numThreads.toInt)).toMap\n val lines = KafkaUtils.createStream(ssc, zkQuorum, group, topicMap).map(_._2)\n val words = lines.flatMap(_.split(\" \"))\n val wordCounts = words.map(x => (x, 1L))\n .reduceByKeyAndWindow(_ + _, _ - _, Minutes(10), Seconds(2), 2)\n wordCounts.print()\n\n ssc.start()\n ssc.awaitTermination()\n }\n}" }, { "code": null, "e": 7701, "s": 7433, "text": "The spark-kafka integration depends on the spark, spark streaming and spark Kafka integration jar. Create a new file build.sbt and specify the application details and its dependency. The sbt will download the necessary jar while compiling and packing the application." }, { "code": null, "e": 7994, "s": 7701, "text": "name := \"Spark Kafka Project\"\nversion := \"1.0\"\nscalaVersion := \"2.10.5\"\n\nlibraryDependencies += \"org.apache.spark\" %% \"spark-core\" % \"1.6.0\"\nlibraryDependencies += \"org.apache.spark\" %% \"spark-streaming\" % \"1.6.0\"\nlibraryDependencies += \"org.apache.spark\" %% \"spark-streaming-kafka\" % \"1.6.0\"" }, { "code": null, "e": 8154, "s": 7994, "text": "Run the following command to compile and package the jar file of the application. We need to submit the jar file into the spark console to run the application." }, { "code": null, "e": 8167, "s": 8154, "text": "sbt package\n" }, { "code": null, "e": 8319, "s": 8167, "text": "Start Kafka Producer CLI (explained in the previous chapter), create a new topic called my-first-topic and provide some sample messages as shown below." }, { "code": null, "e": 8347, "s": 8319, "text": "Another spark test message\n" }, { "code": null, "e": 8417, "s": 8347, "text": "Run the following command to submit the application to spark console." }, { "code": null, "e": 8669, "s": 8417, "text": "/usr/local/spark/bin/spark-submit --packages org.apache.spark:spark-streaming\n-kafka_2.10:1.6.0 --class \"KafkaWordCount\" --master local[4] target/scala-2.10/spark\n-kafka-project_2.10-1.0.jar localhost:2181 <group name> <topic name> <number of threads>" }, { "code": null, "e": 8723, "s": 8669, "text": "The sample output of this application is shown below." }, { "code": null, "e": 8818, "s": 8723, "text": "spark console messages ..\n(Test,1)\n(spark,1)\n(another,1)\n(message,1)\nspark console message ..\n" }, { "code": null, "e": 8853, "s": 8818, "text": "\n 46 Lectures \n 3.5 hours \n" }, { "code": null, "e": 8872, "s": 8853, "text": " Arnab Chakraborty" }, { "code": null, "e": 8907, "s": 8872, "text": "\n 23 Lectures \n 1.5 hours \n" }, { "code": null, "e": 8928, "s": 8907, "text": " Mukund Kumar Mishra" }, { "code": null, "e": 8961, "s": 8928, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 8974, "s": 8961, "text": " Nilay Mehta" }, { "code": null, "e": 9009, "s": 8974, "text": "\n 52 Lectures \n 1.5 hours \n" }, { "code": null, "e": 9027, "s": 9009, "text": " Bigdata Engineer" }, { "code": null, "e": 9060, "s": 9027, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 9078, "s": 9060, "text": " Bigdata Engineer" }, { "code": null, "e": 9111, "s": 9078, "text": "\n 23 Lectures \n 1 hours \n" }, { "code": null, "e": 9129, "s": 9111, "text": " Bigdata Engineer" }, { "code": null, "e": 9136, "s": 9129, "text": " Print" }, { "code": null, "e": 9147, "s": 9136, "text": " Add Notes" } ]
How to use .on and .hover in jQuery ? - GeeksforGeeks
23 Apr, 2020 jQuery .on() method: This method is used to attach an event listener to an element. This method is equivalent to the addEventListener in vanilla JavaScript. Syntax: $(element).on(event, childSelector, data, function) Parameter event: It specifies the event to attach (click, submit, etc.). childSelector: It is optional parameter and it specify the specific child to which given event handler can be used. data: It specifies optional data to be passed along with function. function: It specifies the function to be run while the attached event triggered. Example: <!DOCTYPE html><html> <head> <!-- Adding jQuery Library --> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.0/jquery.min.js"> </script> <style> /* Adding basic styling */ div { background-color: green; width: 100px; height: 100px; color: #fff; text-align: center; } </style></head> <body> <div>Normal</div> <script> $('div').on('click', function () { // Changing the content $(this).html('Clicked!'); }); </script></body> </html> Output: Before Clicking on div element: After Clicking on div element: jQuery .hover() method: This method is used to specify the styles of the element during mouseover and mouseout conditions. It takes two functions as an argument: mouseoverFunction: Triggers when mouse enters the element. mouseoutFunction: Triggers when mouse leaves the element. You can specify multiple styles inside these functions. Syntax: $(element).hover(mouseoverFunction, mouseoutFunction) Example: <!DOCTYPE html><html> <head> <!-- Adding jQuery Library --> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.0/jquery.min.js"> </script> <style> /* Adding basic styling */ div { background-color: green; width: 100px; height: 100px; color: #fff; text-align: center; } </style></head> <body> <div>Normal</div> <script> $('div').hover(function () { // mouse-in $(this).css("background-color", "blue"); $(this).html('Hovered!'); }, function () { // mouse-out $(this).css("background-color", "green"); $(this).html('Normal'); } ) </script></body> </html> Output: Before mouse move over: After mouse move over: Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. CSS-Misc HTML-Misc jQuery-Misc Picked CSS HTML JQuery Web Technologies Web technologies Questions Write From Home HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Design a web page using HTML and CSS Create a Responsive Navbar using ReactJS Form validation using jQuery How to set fixed width for <td> in a table ? How to apply style to parent if it has child with CSS? How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? How to Insert Form Data into Database using PHP ? REST API (Introduction) Hide or show elements in HTML using display property
[ { "code": null, "e": 25083, "s": 25055, "text": "\n23 Apr, 2020" }, { "code": null, "e": 25240, "s": 25083, "text": "jQuery .on() method: This method is used to attach an event listener to an element. This method is equivalent to the addEventListener in vanilla JavaScript." }, { "code": null, "e": 25248, "s": 25240, "text": "Syntax:" }, { "code": null, "e": 25301, "s": 25248, "text": "$(element).on(event, childSelector, data, function)\n" }, { "code": null, "e": 25311, "s": 25301, "text": "Parameter" }, { "code": null, "e": 25374, "s": 25311, "text": "event: It specifies the event to attach (click, submit, etc.)." }, { "code": null, "e": 25490, "s": 25374, "text": "childSelector: It is optional parameter and it specify the specific child to which given event handler can be used." }, { "code": null, "e": 25557, "s": 25490, "text": "data: It specifies optional data to be passed along with function." }, { "code": null, "e": 25639, "s": 25557, "text": "function: It specifies the function to be run while the attached event triggered." }, { "code": null, "e": 25648, "s": 25639, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <!-- Adding jQuery Library --> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.0/jquery.min.js\"> </script> <style> /* Adding basic styling */ div { background-color: green; width: 100px; height: 100px; color: #fff; text-align: center; } </style></head> <body> <div>Normal</div> <script> $('div').on('click', function () { // Changing the content $(this).html('Clicked!'); }); </script></body> </html>", "e": 26236, "s": 25648, "text": null }, { "code": null, "e": 26244, "s": 26236, "text": "Output:" }, { "code": null, "e": 26276, "s": 26244, "text": "Before Clicking on div element:" }, { "code": null, "e": 26307, "s": 26276, "text": "After Clicking on div element:" }, { "code": null, "e": 26469, "s": 26307, "text": "jQuery .hover() method: This method is used to specify the styles of the element during mouseover and mouseout conditions. It takes two functions as an argument:" }, { "code": null, "e": 26528, "s": 26469, "text": "mouseoverFunction: Triggers when mouse enters the element." }, { "code": null, "e": 26586, "s": 26528, "text": "mouseoutFunction: Triggers when mouse leaves the element." }, { "code": null, "e": 26642, "s": 26586, "text": "You can specify multiple styles inside these functions." }, { "code": null, "e": 26650, "s": 26642, "text": "Syntax:" }, { "code": null, "e": 26704, "s": 26650, "text": "$(element).hover(mouseoverFunction, mouseoutFunction)" }, { "code": null, "e": 26713, "s": 26704, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <!-- Adding jQuery Library --> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.0/jquery.min.js\"> </script> <style> /* Adding basic styling */ div { background-color: green; width: 100px; height: 100px; color: #fff; text-align: center; } </style></head> <body> <div>Normal</div> <script> $('div').hover(function () { // mouse-in $(this).css(\"background-color\", \"blue\"); $(this).html('Hovered!'); }, function () { // mouse-out $(this).css(\"background-color\", \"green\"); $(this).html('Normal'); } ) </script></body> </html>", "e": 27484, "s": 26713, "text": null }, { "code": null, "e": 27492, "s": 27484, "text": "Output:" }, { "code": null, "e": 27516, "s": 27492, "text": "Before mouse move over:" }, { "code": null, "e": 27539, "s": 27516, "text": "After mouse move over:" }, { "code": null, "e": 27676, "s": 27539, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 27685, "s": 27676, "text": "CSS-Misc" }, { "code": null, "e": 27695, "s": 27685, "text": "HTML-Misc" }, { "code": null, "e": 27707, "s": 27695, "text": "jQuery-Misc" }, { "code": null, "e": 27714, "s": 27707, "text": "Picked" }, { "code": null, "e": 27718, "s": 27714, "text": "CSS" }, { "code": null, "e": 27723, "s": 27718, "text": "HTML" }, { "code": null, "e": 27730, "s": 27723, "text": "JQuery" }, { "code": null, "e": 27747, "s": 27730, "text": "Web Technologies" }, { "code": null, "e": 27774, "s": 27747, "text": "Web technologies Questions" }, { "code": null, "e": 27790, "s": 27774, "text": "Write From Home" }, { "code": null, "e": 27795, "s": 27790, "text": "HTML" }, { "code": null, "e": 27893, "s": 27795, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27902, "s": 27893, "text": "Comments" }, { "code": null, "e": 27915, "s": 27902, "text": "Old Comments" }, { "code": null, "e": 27952, "s": 27915, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 27993, "s": 27952, "text": "Create a Responsive Navbar using ReactJS" }, { "code": null, "e": 28022, "s": 27993, "text": "Form validation using jQuery" }, { "code": null, "e": 28067, "s": 28022, "text": "How to set fixed width for <td> in a table ?" }, { "code": null, "e": 28122, "s": 28067, "text": "How to apply style to parent if it has child with CSS?" }, { "code": null, "e": 28182, "s": 28122, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 28243, "s": 28182, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 28293, "s": 28243, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 28317, "s": 28293, "text": "REST API (Introduction)" } ]