title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
MySQL COUNT(), AVG() and SUM() Functions
The COUNT() function returns the number of rows that matches a specified criterion. The AVG() function returns the average value of a numeric column. The SUM() function returns the total sum of a numeric column. Below is a selection from the "Products" table in the Northwind sample database: The following SQL statement finds the number of products: Note: NULL values are not counted. The following SQL statement finds the average price of all products: Note: NULL values are ignored. Below is a selection from the "OrderDetails" table in the Northwind sample database: The following SQL statement finds the sum of the "Quantity" fields in the "OrderDetails" table: Note: NULL values are ignored. Use the correct function to return the number of records that have the Price value set to 18. SELECT (*) FROM Products Price = 18; Start the Exercise We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: [email protected] Your message has been sent to W3Schools.
[ { "code": null, "e": 84, "s": 0, "text": "The COUNT() function returns the number of rows that matches a specified criterion." }, { "code": null, "e": 151, "s": 84, "text": "The AVG() function returns the average value of a numeric column. " }, { "code": null, "e": 214, "s": 151, "text": "The SUM() function returns the total sum of a numeric column. " }, { "code": null, "e": 295, "s": 214, "text": "Below is a selection from the \"Products\" table in the Northwind sample database:" }, { "code": null, "e": 353, "s": 295, "text": "The following SQL statement finds the number of products:" }, { "code": null, "e": 388, "s": 353, "text": "Note: NULL values are not counted." }, { "code": null, "e": 457, "s": 388, "text": "The following SQL statement finds the average price of all products:" }, { "code": null, "e": 488, "s": 457, "text": "Note: NULL values are ignored." }, { "code": null, "e": 574, "s": 488, "text": "Below is a selection from the \"OrderDetails\" table in the Northwind \nsample database:" }, { "code": null, "e": 671, "s": 574, "text": "The following SQL statement finds the sum of the \"Quantity\" fields \nin the \"OrderDetails\" table:" }, { "code": null, "e": 702, "s": 671, "text": "Note: NULL values are ignored." }, { "code": null, "e": 796, "s": 702, "text": "Use the correct function to return the number of records that have the Price value set to 18." }, { "code": null, "e": 835, "s": 796, "text": "SELECT (*)\nFROM Products\n Price = 18;\n" }, { "code": null, "e": 854, "s": 835, "text": "Start the Exercise" }, { "code": null, "e": 887, "s": 854, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 929, "s": 887, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 1036, "s": 929, "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": 1055, "s": 1036, "text": "[email protected]" } ]
Logging TensorFlow(Keras) metrics to Azure ML Studio | by Ben Bogart | Towards Data Science
Training a TensorFlow/Keras model on Azure’s Machine Learning Studio can save a lot of time, especially if you don’t have your own GPU or your dataset is large. It seems that there should be an easy way to track your training metrics in Azure ML Studio’s dashboard. Well, there is! It just requires a short custom Keras callback. If you are new to training TensorFlow models on Azure, take a look my article “Train on Cloud GPUs with Azure Machine Learning SDK for Python.” It starts from the beginning and implements an entire training workflow from scratch. This post, however, assumes you know the basics and will only focus on the necessary tools to log your metrics to Azure. There is a working code example that demonstrates the tools in this article in the examplesfolder of the GitHub repository for this project. The callback itself is in the log_to_azure.py file. github.com Before you look at the callback, you will need an azureml.core.Run object to tell your callback where to log the metrics. Getting the Run object from within your azure training script is quite simple. The following code does the trick. from azureml.core import Runrun = Run.get_context() This will only work when the model is running on azure. If you run your script locally you’ll get an error. All that is left is to implement a simple Keras callback that logs our metrics to Azure ML Studio at the completion of each training epoch. This approach is almost identical to using the TensorBoard callback to store log files for TensorBoard with one exception: you need to pass in an azureml.core.Run object which tells our class where to send the logs. Fortunately you have that from the section above! I wrote the callback for you 😁. Here it is. You implement the callback like any other Keras callback. First download the log_to_azure.py file to your training_script directory.Import theLogToAzure callback class.Add the LogToAzure callback to your training script. First download the log_to_azure.py file to your training_script directory. Import theLogToAzure callback class. Add the LogToAzure callback to your training script. from log_to_azure import LogToAzure...# add LogToAure custom Callbackcallbacks = [LogToAzure(run)]# fit model and store historymodel.fit(train_generator, validation_data=val_generator, callbacks=callbacks, epochs=10) Now when you run your models your metrics will be logged to your run in Azure ML Studio. The last step is to setup your “charts” in the Experiments Dashboard so you can visualize the metrics. The metrics you are sending to Azure will not be available to use in a chart until they have been logged at least once, so you must wait until the first epoch has completed before you do the following. Go to your experiment page. We’ve called our experiment recycling. You can start by editing the charts that are already on the Experiment Dashboard. Click on the icon of a pencil in the top right of the chart. You, of course, can modify the chart in any way that is useful to you. But I want to see training and validation accuracy on the same chart so I will select those metrics for the y axis as seen below. You can leave iterations on the X axis. If you want to, you can give the chart a clever name. Once you have edited the existing charts you can add a new chart with the Add chart icon at the top of the page. Lastly, do not forget to save the view. If you do not save the view you will have to set up your charts again next time you view the page. To save to the default view click Save view. That's it. Now you can track and compare the training progress of your models on azure in real time. And it looks something like this: If you need help getting started training your models on Azure check out my other article: “Train on Cloud GPUs with Azure Machine Learning SDK for Python.” Now go do some good.
[ { "code": null, "e": 377, "s": 47, "text": "Training a TensorFlow/Keras model on Azure’s Machine Learning Studio can save a lot of time, especially if you don’t have your own GPU or your dataset is large. It seems that there should be an easy way to track your training metrics in Azure ML Studio’s dashboard. Well, there is! It just requires a short custom Keras callback." }, { "code": null, "e": 728, "s": 377, "text": "If you are new to training TensorFlow models on Azure, take a look my article “Train on Cloud GPUs with Azure Machine Learning SDK for Python.” It starts from the beginning and implements an entire training workflow from scratch. This post, however, assumes you know the basics and will only focus on the necessary tools to log your metrics to Azure." }, { "code": null, "e": 921, "s": 728, "text": "There is a working code example that demonstrates the tools in this article in the examplesfolder of the GitHub repository for this project. The callback itself is in the log_to_azure.py file." }, { "code": null, "e": 932, "s": 921, "text": "github.com" }, { "code": null, "e": 1168, "s": 932, "text": "Before you look at the callback, you will need an azureml.core.Run object to tell your callback where to log the metrics. Getting the Run object from within your azure training script is quite simple. The following code does the trick." }, { "code": null, "e": 1220, "s": 1168, "text": "from azureml.core import Runrun = Run.get_context()" }, { "code": null, "e": 1328, "s": 1220, "text": "This will only work when the model is running on azure. If you run your script locally you’ll get an error." }, { "code": null, "e": 1734, "s": 1328, "text": "All that is left is to implement a simple Keras callback that logs our metrics to Azure ML Studio at the completion of each training epoch. This approach is almost identical to using the TensorBoard callback to store log files for TensorBoard with one exception: you need to pass in an azureml.core.Run object which tells our class where to send the logs. Fortunately you have that from the section above!" }, { "code": null, "e": 1778, "s": 1734, "text": "I wrote the callback for you 😁. Here it is." }, { "code": null, "e": 1836, "s": 1778, "text": "You implement the callback like any other Keras callback." }, { "code": null, "e": 1999, "s": 1836, "text": "First download the log_to_azure.py file to your training_script directory.Import theLogToAzure callback class.Add the LogToAzure callback to your training script." }, { "code": null, "e": 2074, "s": 1999, "text": "First download the log_to_azure.py file to your training_script directory." }, { "code": null, "e": 2111, "s": 2074, "text": "Import theLogToAzure callback class." }, { "code": null, "e": 2164, "s": 2111, "text": "Add the LogToAzure callback to your training script." }, { "code": null, "e": 2409, "s": 2164, "text": "from log_to_azure import LogToAzure...# add LogToAure custom Callbackcallbacks = [LogToAzure(run)]# fit model and store historymodel.fit(train_generator, validation_data=val_generator, callbacks=callbacks, epochs=10)" }, { "code": null, "e": 2601, "s": 2409, "text": "Now when you run your models your metrics will be logged to your run in Azure ML Studio. The last step is to setup your “charts” in the Experiments Dashboard so you can visualize the metrics." }, { "code": null, "e": 2803, "s": 2601, "text": "The metrics you are sending to Azure will not be available to use in a chart until they have been logged at least once, so you must wait until the first epoch has completed before you do the following." }, { "code": null, "e": 2870, "s": 2803, "text": "Go to your experiment page. We’ve called our experiment recycling." }, { "code": null, "e": 3013, "s": 2870, "text": "You can start by editing the charts that are already on the Experiment Dashboard. Click on the icon of a pencil in the top right of the chart." }, { "code": null, "e": 3308, "s": 3013, "text": "You, of course, can modify the chart in any way that is useful to you. But I want to see training and validation accuracy on the same chart so I will select those metrics for the y axis as seen below. You can leave iterations on the X axis. If you want to, you can give the chart a clever name." }, { "code": null, "e": 3421, "s": 3308, "text": "Once you have edited the existing charts you can add a new chart with the Add chart icon at the top of the page." }, { "code": null, "e": 3605, "s": 3421, "text": "Lastly, do not forget to save the view. If you do not save the view you will have to set up your charts again next time you view the page. To save to the default view click Save view." }, { "code": null, "e": 3740, "s": 3605, "text": "That's it. Now you can track and compare the training progress of your models on azure in real time. And it looks something like this:" }, { "code": null, "e": 3897, "s": 3740, "text": "If you need help getting started training your models on Azure check out my other article: “Train on Cloud GPUs with Azure Machine Learning SDK for Python.”" } ]
fgets() and gets() in C
The function fgets() is used to read the string till the new line character. It checks array bound and it is safe too. Here is the syntax of fgets() in C language, char *fgets(char *string, int value, FILE *stream) Here, string − This is a pointer to the array of char. value − The number of characters to be read. stream − This is a pointer to a file object. Here is an example of fgets() in C language, Live Demo #include <stdio.h> #define FUNC 8 int main() { char b[FUNC]; fgets(b, FUNC, stdin); printf("The string is: %s\n", b); return 0; } The input string is “Hello World!” in stdin stream. The string is: Hello W In the above program, an array of char type is declared. The function fgets() reads the characters till the given number from STDIN stream. char b[FUNC]; fgets(b, FUNC, stdin); The function gets() is used to read the string from standard input device. It does not check array bound and it is insecure too. Here is the syntax of gets() in C language, char *gets(char *string); Here, string − This is a pointer to the array of char. Here is an example of gets() in C language, #include <stdio.h> #include <string.h> int main() { char s[100]; int i; printf("\nEnter a string : "); gets(s); for (i = 0; s[i]!='\0'; i++) { if(s[i] >= 'a' && s[i] <= 'z') { s[i] = s[i] - 32; } } printf("\nString in Upper Case = %s", s); return 0; } Enter a string : hello world! String in Upper Case = HELLO WORLD! In the above program, the string s of char array is converted into upper case string. The function gets() is used to read the string from the stdin stream. char s[100]; int i; printf("\nEnter a string : "); gets(s);
[ { "code": null, "e": 1181, "s": 1062, "text": "The function fgets() is used to read the string till the new line character. It checks array bound and it is safe too." }, { "code": null, "e": 1226, "s": 1181, "text": "Here is the syntax of fgets() in C language," }, { "code": null, "e": 1277, "s": 1226, "text": "char *fgets(char *string, int value, FILE *stream)" }, { "code": null, "e": 1283, "s": 1277, "text": "Here," }, { "code": null, "e": 1332, "s": 1283, "text": "string − This is a pointer to the array of char." }, { "code": null, "e": 1377, "s": 1332, "text": "value − The number of characters to be read." }, { "code": null, "e": 1422, "s": 1377, "text": "stream − This is a pointer to a file object." }, { "code": null, "e": 1467, "s": 1422, "text": "Here is an example of fgets() in C language," }, { "code": null, "e": 1478, "s": 1467, "text": " Live Demo" }, { "code": null, "e": 1620, "s": 1478, "text": "#include <stdio.h>\n#define FUNC 8\nint main() {\n char b[FUNC];\n fgets(b, FUNC, stdin);\n printf(\"The string is: %s\\n\", b);\n return 0;\n}" }, { "code": null, "e": 1672, "s": 1620, "text": "The input string is “Hello World!” in stdin stream." }, { "code": null, "e": 1695, "s": 1672, "text": "The string is: Hello W" }, { "code": null, "e": 1835, "s": 1695, "text": "In the above program, an array of char type is declared. The function fgets() reads the characters till the given number from STDIN stream." }, { "code": null, "e": 1872, "s": 1835, "text": "char b[FUNC];\nfgets(b, FUNC, stdin);" }, { "code": null, "e": 2001, "s": 1872, "text": "The function gets() is used to read the string from standard input device. It does not check array bound and it is insecure too." }, { "code": null, "e": 2045, "s": 2001, "text": "Here is the syntax of gets() in C language," }, { "code": null, "e": 2071, "s": 2045, "text": "char *gets(char *string);" }, { "code": null, "e": 2077, "s": 2071, "text": "Here," }, { "code": null, "e": 2126, "s": 2077, "text": "string − This is a pointer to the array of char." }, { "code": null, "e": 2170, "s": 2126, "text": "Here is an example of gets() in C language," }, { "code": null, "e": 2467, "s": 2170, "text": "#include <stdio.h>\n#include <string.h>\nint main() {\n char s[100];\n int i;\n printf(\"\\nEnter a string : \");\n gets(s);\n for (i = 0; s[i]!='\\0'; i++) {\n if(s[i] >= 'a' && s[i] <= 'z') {\n s[i] = s[i] - 32;\n }\n }\n printf(\"\\nString in Upper Case = %s\", s);\n return 0;\n}" }, { "code": null, "e": 2533, "s": 2467, "text": "Enter a string : hello world!\nString in Upper Case = HELLO WORLD!" }, { "code": null, "e": 2689, "s": 2533, "text": "In the above program, the string s of char array is converted into upper case string. The function gets() is used to read the string from the stdin stream." }, { "code": null, "e": 2749, "s": 2689, "text": "char s[100];\nint i;\nprintf(\"\\nEnter a string : \");\ngets(s);" } ]
VSAM - Alternate Index
Alternate index are the additional index that are created for KSDS/ESDS datasets in addition to their primary index. An alternate index provides access to records by using more than one key. The key of alternate index can be a non-unique key, it can have duplicates. Following steps are used to create an Alternate Index − Define Alternate Index Define Path Building Index Alternate Index is defined using DEFINE AIX command. DEFINE AIX - (NAME(alternate-index-name) - RELATE(vsam-file-name) - CISZ(number) - FREESPACE(CI-Percentage,CA-Percentage) - KEYS(length offset) - NONUNIQUEKEY / UNIQUEKEY - UPGRADE / NOUPGRADE - RECORDSIZE(average maximum)) - DATA - (NAME(vsam-file-name.data)) - INDEX - (NAME(vsam-file-name.index)) Above syntax shows the parameters which are used while defining Alternate Index. We have already discussed some parameters in Define Cluster Module and some of the new parameters are used in defining Alternate Index which we will discuss here − DEFINE AIX Define AIX command is used to define Alternate Index and specify parameter attributes for its components. NAME NAME specifies the name of Alternate Index. RELATE RELATE specifies the name of the VSAM cluster for which the alternate index is created. NONUNIQUEKEY / UNIQUEKEY UNIQUEKEY specifies that the alternate index is unique and NONUNIQUEKEY specifies that duplicates may exist. UPGRADE / NOUPGRADE UPGRADE specifies that the alternate index should be modified if the base cluster is modified and NOUPGRADE specifies that the alternate indexes should be left alone if the base cluster is modified. Following is a basic example to show how to define an Alternate Index in JCL − //SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C //STEP1 EXEC PGM = IDCAMS //SYSPRINT DD SYSOUT = * //SYSIN DD * DEFINE AIX (NAME(MY.VSAM.KSDSAIX) - RELATE(MY.VSAM.KSDSFILE) - CISZ(4096) - FREESPACE(20,20) - KEYS(20,7) - NONUNIQUEKEY - UPGRADE - RECORDSIZE(80,80)) - DATA(NAME(MY.VSAM.KSDSAIX.DATA)) - INDEX(NAME(MY.VSAM.KSDSAIX.INDEX)) /* If you will execute the above JCL on Mainframes server. It should execute with MAXCC = 0 and it will create MY.VSAM.KSDSAIX Alternate Index. Define Path is used to relate the alternate index to the base cluster. While defining path we specify the name of the path and the alternate index to which this path is related. DEFINE PATH - NAME(alternate-index-path-name) - PATHENTRY(alternate-index-name)) Above syntax has two parameters. NAME is used to specify the Alternate Index Path Name and PATHENTRY is used to specify Alternate Index Name. Following is a basic example to define Path in JCL − //SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C //STEP1 EXEC PGM = IDCAMS //SYSPRINT DD SYSOUT = * //SYSIN DD * DEFINE PATH - NAME(MY.VSAM.KSDSAIX.PATH) - PATHENTRY(MY.VSAM.KSDSAIX)) /* If you will execute the above JCL on Mainframes server. It should execute with MAXCC = 0 and it will create path between Alternate Index to the base cluster. BLDINDEX command is used to build the alternate index. BLDINDEX reads all the records in the VSAM indexed data set (or base cluster) and extracts the data needed to build the alternate index. BLDINDEX - INDATASET(vsam-cluster-name) - OUTDATASET(alternate-index-name)) Above syntax has two parameters. INDATASET is used to specify the VSAM Cluster Name and OUTDATASET is used to specify Alternate Index Name. Following is a basic example to Build Index in JCL − //SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C //STEP1 EXEC PGM = IDCAMS //SYSPRINT DD SYSOUT = * //SYSIN DD * BLDINDEX - INDATASET(MY.VSAM.KSDSFILE) - OUTDATASET(MY.VSAM.KSDSAIX)) /* If you will execute the above JCL on Mainframes server. It should execute with MAXCC = 0 and it will build the index. 8 Lectures 1 hours Nishant Malik Print Add Notes Bookmark this page
[ { "code": null, "e": 2032, "s": 1765, "text": "Alternate index are the additional index that are created for KSDS/ESDS datasets in addition to their primary index. An alternate index provides access to records by using more than one key. The key of alternate index can be a non-unique key, it can have duplicates." }, { "code": null, "e": 2088, "s": 2032, "text": "Following steps are used to create an Alternate Index −" }, { "code": null, "e": 2111, "s": 2088, "text": "Define Alternate Index" }, { "code": null, "e": 2123, "s": 2111, "text": "Define Path" }, { "code": null, "e": 2138, "s": 2123, "text": "Building Index" }, { "code": null, "e": 2191, "s": 2138, "text": "Alternate Index is defined using DEFINE AIX command." }, { "code": null, "e": 2728, "s": 2191, "text": "DEFINE AIX -\n(NAME(alternate-index-name) -\nRELATE(vsam-file-name) -\nCISZ(number) -\nFREESPACE(CI-Percentage,CA-Percentage) -\nKEYS(length offset) -\nNONUNIQUEKEY / UNIQUEKEY -\nUPGRADE / NOUPGRADE -\nRECORDSIZE(average maximum)) -\nDATA -\n (NAME(vsam-file-name.data)) -\nINDEX -\n (NAME(vsam-file-name.index))\n" }, { "code": null, "e": 2973, "s": 2728, "text": "Above syntax shows the parameters which are used while defining Alternate Index. We have already discussed some parameters in Define Cluster Module and some of the new parameters are used in defining Alternate Index which we will discuss here −" }, { "code": null, "e": 2984, "s": 2973, "text": "DEFINE AIX" }, { "code": null, "e": 3090, "s": 2984, "text": "Define AIX command is used to define Alternate Index and specify parameter attributes for its components." }, { "code": null, "e": 3095, "s": 3090, "text": "NAME" }, { "code": null, "e": 3139, "s": 3095, "text": "NAME specifies the name of Alternate Index." }, { "code": null, "e": 3146, "s": 3139, "text": "RELATE" }, { "code": null, "e": 3234, "s": 3146, "text": "RELATE specifies the name of the VSAM cluster for which the alternate index is created." }, { "code": null, "e": 3259, "s": 3234, "text": "NONUNIQUEKEY / UNIQUEKEY" }, { "code": null, "e": 3368, "s": 3259, "text": "UNIQUEKEY specifies that the alternate index is unique and NONUNIQUEKEY specifies that duplicates may exist." }, { "code": null, "e": 3388, "s": 3368, "text": "UPGRADE / NOUPGRADE" }, { "code": null, "e": 3587, "s": 3388, "text": "UPGRADE specifies that the alternate index should be modified if the base cluster is modified and NOUPGRADE specifies that the alternate indexes should be left alone if the base cluster is modified." }, { "code": null, "e": 3666, "s": 3587, "text": "Following is a basic example to show how to define an Alternate Index in JCL −" }, { "code": null, "e": 4225, "s": 3666, "text": "//SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C\n//STEP1 EXEC PGM = IDCAMS\n//SYSPRINT DD SYSOUT = *\n//SYSIN DD *\n DEFINE AIX (NAME(MY.VSAM.KSDSAIX) -\n RELATE(MY.VSAM.KSDSFILE) -\n CISZ(4096) -\n FREESPACE(20,20) -\n KEYS(20,7) -\n NONUNIQUEKEY -\n UPGRADE -\n RECORDSIZE(80,80)) -\n DATA(NAME(MY.VSAM.KSDSAIX.DATA)) -\n INDEX(NAME(MY.VSAM.KSDSAIX.INDEX))\n/*" }, { "code": null, "e": 4366, "s": 4225, "text": "If you will execute the above JCL on Mainframes server. It should execute with MAXCC = 0 and it will create MY.VSAM.KSDSAIX Alternate Index." }, { "code": null, "e": 4544, "s": 4366, "text": "Define Path is used to relate the alternate index to the base cluster. While defining path we specify the name of the path and the alternate index to which this path is related." }, { "code": null, "e": 4652, "s": 4544, "text": "DEFINE PATH -\nNAME(alternate-index-path-name) -\nPATHENTRY(alternate-index-name))\n" }, { "code": null, "e": 4794, "s": 4652, "text": "Above syntax has two parameters. NAME is used to specify the Alternate Index Path Name and PATHENTRY is used to specify Alternate Index Name." }, { "code": null, "e": 4847, "s": 4794, "text": "Following is a basic example to define Path in JCL −" }, { "code": null, "e": 5077, "s": 4847, "text": "//SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C\n//STEP1 EXEC PGM = IDCAMS\n//SYSPRINT DD SYSOUT = *\n//SYSIN DD *\nDEFINE PATH -\n NAME(MY.VSAM.KSDSAIX.PATH) -\n PATHENTRY(MY.VSAM.KSDSAIX))\n/*" }, { "code": null, "e": 5235, "s": 5077, "text": "If you will execute the above JCL on Mainframes server. It should execute with MAXCC = 0 and it will create path between Alternate Index to the base cluster." }, { "code": null, "e": 5427, "s": 5235, "text": "BLDINDEX command is used to build the alternate index. BLDINDEX reads all the records in the VSAM indexed data set (or base cluster) and extracts the data needed to build the alternate index." }, { "code": null, "e": 5536, "s": 5427, "text": "BLDINDEX -\nINDATASET(vsam-cluster-name) -\nOUTDATASET(alternate-index-name))\n" }, { "code": null, "e": 5676, "s": 5536, "text": "Above syntax has two parameters. INDATASET is used to specify the VSAM Cluster Name and OUTDATASET is used to specify Alternate Index Name." }, { "code": null, "e": 5729, "s": 5676, "text": "Following is a basic example to Build Index in JCL −" }, { "code": null, "e": 5966, "s": 5729, "text": "//SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C\n//STEP1 EXEC PGM = IDCAMS\n//SYSPRINT DD SYSOUT = *\n//SYSIN DD *\n BLDINDEX -\n INDATASET(MY.VSAM.KSDSFILE) -\n OUTDATASET(MY.VSAM.KSDSAIX))\n/*" }, { "code": null, "e": 6084, "s": 5966, "text": "If you will execute the above JCL on Mainframes server. It should execute with MAXCC = 0 and it will build the index." }, { "code": null, "e": 6116, "s": 6084, "text": "\n 8 Lectures \n 1 hours \n" }, { "code": null, "e": 6131, "s": 6116, "text": " Nishant Malik" }, { "code": null, "e": 6138, "s": 6131, "text": " Print" }, { "code": null, "e": 6149, "s": 6138, "text": " Add Notes" } ]
What are the differences between length and length () in Java?
The length is an instance variable of an array in Java whereas length() is a method of String class. An array is an object that holds a fixed number of values of the same type. The length variable in an array returns the length of an array i.e. a number of elements stored in an array. Once arrays are initialized, its length cannot be changed, so the length variable can directly be used to get the length of an array. The length variable is used only for an array. Live Demo public class ArrayLengthTest { public static void main(String args[]) { int array[] = {1, 2, 3, 4, 5, 6, 7}; System.out.println("Length of an array is: " + array.length); } } Length of an array is: 7 The length() method is a static method of String class. The length() returns the length of a string object i.e. the number of characters stored in an object. String class uses this method because the length of a string can be modified using the various operations on an object. The String class internally uses a char[] array that it does not expose to the outside world. Live Demo public class StringLengthMethodTest { public static void main(String args[]) { String str = "Welcome to Tutorials Point"; System.out.println("Length of String using length() method is: " + str.length()); } } Length of String using length() method is: 26
[ { "code": null, "e": 1163, "s": 1062, "text": "The length is an instance variable of an array in Java whereas length() is a method of String class." }, { "code": null, "e": 1239, "s": 1163, "text": "An array is an object that holds a fixed number of values of the same type." }, { "code": null, "e": 1348, "s": 1239, "text": "The length variable in an array returns the length of an array i.e. a number of elements stored in an array." }, { "code": null, "e": 1482, "s": 1348, "text": "Once arrays are initialized, its length cannot be changed, so the length variable can directly be used to get the length of an array." }, { "code": null, "e": 1529, "s": 1482, "text": "The length variable is used only for an array." }, { "code": null, "e": 1539, "s": 1529, "text": "Live Demo" }, { "code": null, "e": 1732, "s": 1539, "text": "public class ArrayLengthTest {\n public static void main(String args[]) {\n int array[] = {1, 2, 3, 4, 5, 6, 7};\n System.out.println(\"Length of an array is: \" + array.length);\n }\n}" }, { "code": null, "e": 1758, "s": 1732, "text": "Length of an array is: 7\n" }, { "code": null, "e": 1814, "s": 1758, "text": "The length() method is a static method of String class." }, { "code": null, "e": 1916, "s": 1814, "text": "The length() returns the length of a string object i.e. the number of characters stored in an object." }, { "code": null, "e": 2036, "s": 1916, "text": "String class uses this method because the length of a string can be modified using the various operations on an object." }, { "code": null, "e": 2130, "s": 2036, "text": "The String class internally uses a char[] array that it does not expose to the outside world." }, { "code": null, "e": 2140, "s": 2130, "text": "Live Demo" }, { "code": null, "e": 2366, "s": 2140, "text": "public class StringLengthMethodTest {\n public static void main(String args[]) {\n String str = \"Welcome to Tutorials Point\";\n System.out.println(\"Length of String using length() method is: \" + str.length());\n }\n}" }, { "code": null, "e": 2413, "s": 2366, "text": "Length of String using length() method is: 26\n" } ]
How to get programmatically android build id?
This example demonstrate about How to get programmatically android build id. 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"> <TextView android:id = "@+id/text" android:textSize = "30sp" android:layout_width = "match_parent" android:layout_height = "match_parent" /> </LinearLayout> In the above code, we have taken text view to show device id. Step 3 − Add the following code to src/MainActivity.java package com.example.myapplication; import android.Manifest; import android.app.ProgressDialog; import android.content.pm.PackageManager; import android.os.Build; import android.os.Bundle; import android.support.annotation.RequiresApi; import android.support.v4.app.ActivityCompat; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.webkit.CookieManager; import android.webkit.WebChromeClient; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.EditText; import android.widget.TextView; public class MainActivity extends AppCompatActivity { TextView textView; @RequiresApi(api = Build.VERSION_CODES.P) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = findViewById(R.id.text); if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE}, 101); } } @RequiresApi(api = Build.VERSION_CODES.O) @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { switch (requestCode) { case 101: if (grantResults[0] = = PackageManager.PERMISSION_GRANTED) { if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) { return; } textView.setText(Build.ID); } else { //not granted } break; default: super.onRequestPermissionsResult(requestCode, permissions, grantResults); } } @RequiresApi(api = Build.VERSION_CODES.O) @Override protected void onResume() { super.onResume(); if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) { return; } textView.setText(Build.ID); } } 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 = "com.example.myapplication"> <uses-permission android:name = "android.permission.INTERNET"/> <uses-permission android:name = "android.permission.READ_PHONE_STATE" /> <application android:allowBackup = "true" android:icon = "@mipmap/ic_launcher" android:label = "@string/app_name" android:roundIcon = "@mipmap/ic_launcher_round" android:supportsRtl = "true" android:theme = "@style/AppTheme"> <activity android:name = ".MainActivity"> <intent-filter> <action android:name = "android.intent.action.MAIN" /> <category android:name = "android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen – Click here to download the project code
[ { "code": null, "e": 1139, "s": 1062, "text": "This example demonstrate about How to get programmatically android build id." }, { "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": 1893, "s": 1333, "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 <TextView\n android:id = \"@+id/text\"\n android:textSize = \"30sp\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\" />\n</LinearLayout>" }, { "code": null, "e": 1955, "s": 1893, "text": "In the above code, we have taken text view to show device id." }, { "code": null, "e": 2012, "s": 1955, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 4164, "s": 2012, "text": "package com.example.myapplication;\nimport android.Manifest;\nimport android.app.ProgressDialog;\nimport android.content.pm.PackageManager;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.support.annotation.RequiresApi;\nimport android.support.v4.app.ActivityCompat;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.webkit.CookieManager;\nimport android.webkit.WebChromeClient;\nimport android.webkit.WebSettings;\nimport android.webkit.WebView;\nimport android.webkit.WebViewClient;\nimport android.widget.EditText;\nimport android.widget.TextView;\npublic class MainActivity extends AppCompatActivity {\n TextView textView;\n @RequiresApi(api = Build.VERSION_CODES.P)\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n textView = findViewById(R.id.text);\n if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {\n ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE}, 101);\n }\n }\n @RequiresApi(api = Build.VERSION_CODES.O)\n @Override\n public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {\n switch (requestCode) {\n case 101:\n if (grantResults[0] = = PackageManager.PERMISSION_GRANTED) {\n if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {\n return;\n }\n textView.setText(Build.ID);\n } else {\n //not granted\n }\n break;\n default:\n super.onRequestPermissionsResult(requestCode, permissions, grantResults);\n }\n }\n @RequiresApi(api = Build.VERSION_CODES.O)\n @Override\n protected void onResume() {\n super.onResume();\n if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {\n return;\n }\n textView.setText(Build.ID);\n }\n}" }, { "code": null, "e": 4219, "s": 4164, "text": "Step 4 − Add the following code to AndroidManifest.xml" }, { "code": null, "e": 5072, "s": 4219, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<manifest xmlns:android = \"http://schemas.android.com/apk/res/android\"\n package = \"com.example.myapplication\">\n <uses-permission android:name = \"android.permission.INTERNET\"/>\n <uses-permission android:name = \"android.permission.READ_PHONE_STATE\" />\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": 5419, "s": 5072, "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": 5459, "s": 5419, "text": "Click here to download the project code" } ]
How to change the color spaces of an image using Java OpenCV library?
Using color space protocol you can represent the colors in an image. There are several color spaces available in OpenCV some of them are − BGR − RGB is the most widely used color space in this, each pixel is actually formed by three different colors (intensity) values: red, blue and green, it is the default color space in OpenCV but it is stored as BGR. BGR − RGB is the most widely used color space in this, each pixel is actually formed by three different colors (intensity) values: red, blue and green, it is the default color space in OpenCV but it is stored as BGR. HSV − In HSV color space the different colors are formed by changing the hue, saturation, and brightness. HSV − In HSV color space the different colors are formed by changing the hue, saturation, and brightness. CMK − This is a subtractive color space, in this the different colors are formed by subtracting the Cyan, Magenta and Yellow values, starting from white. CMK − This is a subtractive color space, in this the different colors are formed by subtracting the Cyan, Magenta and Yellow values, starting from white. Y’UV − Y’UV defines a color space in terms of one luma (Y’) and two chrominance (UV) components. The Y’UV color model is used in the following composite color video standards. Y’UV − Y’UV defines a color space in terms of one luma (Y’) and two chrominance (UV) components. The Y’UV color model is used in the following composite color video standards. You can convert the representation of an image from one color space to another using the cvtColor() method of the org.opencv.imgproc.Imgproc class. This method accepts a source image, destination image and the code representing the color of the destination image. To change the color space from BGR to HSV you need to pass COLOR_BGR2HSV as the color code value. Similarly to change the color space from BGR to YUV you need to pass COLOR_BGR2YUV as the color code. import org.opencv.core.Core; import org.opencv.core.Mat; import org.opencv.highgui.HighGui; import org.opencv.imgcodecs.Imgcodecs; import org.opencv.imgproc.Imgproc; public class ChangingColorSpaces { public static void main(String args[]) throws Exception { //Loading the OpenCV core library System.loadLibrary( Core.NATIVE_LIBRARY_NAME ); //Reading the image Mat src = Imgcodecs.imread("D:\\images\\elephant.jpg"); //Creating the empty destination matrix Mat dst = new Mat(); //Converting From BGR to Gray Imgproc.cvtColor(src, dst, Imgproc.COLOR_BGR2GRAY); HighGui.imshow("BGR to Gray", dst); dst = new Mat(); //Converting From BGR to HSV Imgproc.cvtColor(src, dst, Imgproc.COLOR_BGR2HSV); HighGui.imshow("BGR to HSV", dst); dst = new Mat(); //Converting From BGR to HSV Imgproc.cvtColor(src, dst, Imgproc.COLOR_RGB2YUV); HighGui.imshow("BGR to YUV", dst); HighGui.waitKey(); } } On executing, the above program generates the following windows − BGR to Gray − BGR to HSV − BGR to YUV −
[ { "code": null, "e": 1201, "s": 1062, "text": "Using color space protocol you can represent the colors in an image. There are several color spaces available in OpenCV some of them are −" }, { "code": null, "e": 1418, "s": 1201, "text": "BGR − RGB is the most widely used color space in this, each pixel is actually formed by three different colors (intensity) values: red, blue and green, it is the default color space in OpenCV but it is stored as BGR." }, { "code": null, "e": 1635, "s": 1418, "text": "BGR − RGB is the most widely used color space in this, each pixel is actually formed by three different colors (intensity) values: red, blue and green, it is the default color space in OpenCV but it is stored as BGR." }, { "code": null, "e": 1741, "s": 1635, "text": "HSV − In HSV color space the different colors are formed by changing the hue, saturation, and brightness." }, { "code": null, "e": 1847, "s": 1741, "text": "HSV − In HSV color space the different colors are formed by changing the hue, saturation, and brightness." }, { "code": null, "e": 2001, "s": 1847, "text": "CMK − This is a subtractive color space, in this the different colors are formed by subtracting the Cyan, Magenta and Yellow values, starting from white." }, { "code": null, "e": 2155, "s": 2001, "text": "CMK − This is a subtractive color space, in this the different colors are formed by subtracting the Cyan, Magenta and Yellow values, starting from white." }, { "code": null, "e": 2331, "s": 2155, "text": "Y’UV − Y’UV defines a color space in terms of one luma (Y’) and two chrominance (UV) components. The Y’UV color model is used in the following composite color video standards." }, { "code": null, "e": 2507, "s": 2331, "text": "Y’UV − Y’UV defines a color space in terms of one luma (Y’) and two chrominance (UV) components. The Y’UV color model is used in the following composite color video standards." }, { "code": null, "e": 2771, "s": 2507, "text": "You can convert the representation of an image from one color space to another using the cvtColor() method of the org.opencv.imgproc.Imgproc class. This method accepts a source image, destination image and the code representing the color of the destination image." }, { "code": null, "e": 2971, "s": 2771, "text": "To change the color space from BGR to HSV you need to pass COLOR_BGR2HSV as the color code value. Similarly to change the color space from BGR to YUV you need to pass COLOR_BGR2YUV as the color code." }, { "code": null, "e": 3968, "s": 2971, "text": "import org.opencv.core.Core;\nimport org.opencv.core.Mat;\nimport org.opencv.highgui.HighGui;\nimport org.opencv.imgcodecs.Imgcodecs;\nimport org.opencv.imgproc.Imgproc;\npublic class ChangingColorSpaces {\n public static void main(String args[]) throws Exception {\n //Loading the OpenCV core library\n System.loadLibrary( Core.NATIVE_LIBRARY_NAME );\n //Reading the image\n Mat src = Imgcodecs.imread(\"D:\\\\images\\\\elephant.jpg\");\n //Creating the empty destination matrix\n Mat dst = new Mat();\n //Converting From BGR to Gray\n Imgproc.cvtColor(src, dst, Imgproc.COLOR_BGR2GRAY);\n HighGui.imshow(\"BGR to Gray\", dst);\n dst = new Mat();\n //Converting From BGR to HSV\n Imgproc.cvtColor(src, dst, Imgproc.COLOR_BGR2HSV);\n HighGui.imshow(\"BGR to HSV\", dst);\n dst = new Mat();\n //Converting From BGR to HSV\n Imgproc.cvtColor(src, dst, Imgproc.COLOR_RGB2YUV);\n HighGui.imshow(\"BGR to YUV\", dst);\n HighGui.waitKey();\n }\n}" }, { "code": null, "e": 4034, "s": 3968, "text": "On executing, the above program generates the following windows −" }, { "code": null, "e": 4049, "s": 4034, "text": "BGR to Gray − " }, { "code": null, "e": 4063, "s": 4049, "text": "BGR to HSV − " }, { "code": null, "e": 4077, "s": 4063, "text": "BGR to YUV − " } ]
Selenium and iframe in html.
We can work with iframe in Selenium webdriver. A frame is defined with <iframe>, <frameset> or <frame> tag in html code. A frame is used to embed an HTML document within another HTML document. Selenium by default has access to the parent browser driver. In order to access a frame element, the driver focus has to shift from the main browser window to the frame. There are more than one methods to shift to frames − switchTo().frame(id) - The id or name of frame is passed as an argument.Syntax − driver.switchTo().frame("id"), switching to the frame with id. switchTo().frame(id) - The id or name of frame is passed as an argument. Syntax − driver.switchTo().frame("id"), switching to the frame with id. switchTo().frame(m) - The index of frame is passed as an argument. The index begins from zero.Syntax − driver.switchTo().frame(0), switching to the first frame in the page. switchTo().frame(m) - The index of frame is passed as an argument. The index begins from zero. Syntax − driver.switchTo().frame(0), switching to the first frame in the page. switchTo().frame(webelement n) - The webelement of frame is passed as an argument.Syntax − driver.switchTo().frame(l), switching to the frame with webelement l. switchTo().frame(webelement n) - The webelement of frame is passed as an argument. Syntax − driver.switchTo().frame(l), switching to the frame with webelement l. switchTo().defaultContent() – Switching focus from frame to the main page.Syntax − driver.switchTo().defaultContent() switchTo().defaultContent() – Switching focus from frame to the main page. Syntax − driver.switchTo().defaultContent() Code Implementation. import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; public class iFrameMethods{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.get("https://the-internet.herokuapp.com/frames"); driver.manage().timeouts().implicitlyWait(8, TimeUnit.SECONDS); // identify element and click driver.findElement(By.partialLinkText("Nested")).click(); // switching to frame with frame name driver.switchTo().frame("frame-bottom"); WebElement m = driver.findElement(By.cssSelector("body")); System.out.println("Frame text: " +m.getText()); driver.close(); } }
[ { "code": null, "e": 1255, "s": 1062, "text": "We can work with iframe in Selenium webdriver. A frame is defined with <iframe>, <frameset> or <frame> tag in html code. A frame is used to embed an HTML document within another HTML document." }, { "code": null, "e": 1478, "s": 1255, "text": "Selenium by default has access to the parent browser driver. In order to access a frame element, the driver focus has to shift from the main browser window to the frame. There are more than one methods to shift to frames −" }, { "code": null, "e": 1622, "s": 1478, "text": "switchTo().frame(id) - The id or name of frame is passed as an argument.Syntax −\ndriver.switchTo().frame(\"id\"), switching to the frame with id." }, { "code": null, "e": 1695, "s": 1622, "text": "switchTo().frame(id) - The id or name of frame is passed as an argument." }, { "code": null, "e": 1767, "s": 1695, "text": "Syntax −\ndriver.switchTo().frame(\"id\"), switching to the frame with id." }, { "code": null, "e": 1940, "s": 1767, "text": "switchTo().frame(m) - The index of frame is passed as an argument. The index begins from zero.Syntax −\ndriver.switchTo().frame(0), switching to the first frame in the page." }, { "code": null, "e": 2035, "s": 1940, "text": "switchTo().frame(m) - The index of frame is passed as an argument. The index begins from zero." }, { "code": null, "e": 2114, "s": 2035, "text": "Syntax −\ndriver.switchTo().frame(0), switching to the first frame in the page." }, { "code": null, "e": 2275, "s": 2114, "text": "switchTo().frame(webelement n) - The webelement of frame is passed as an argument.Syntax −\ndriver.switchTo().frame(l), switching to the frame with webelement l." }, { "code": null, "e": 2358, "s": 2275, "text": "switchTo().frame(webelement n) - The webelement of frame is passed as an argument." }, { "code": null, "e": 2437, "s": 2358, "text": "Syntax −\ndriver.switchTo().frame(l), switching to the frame with webelement l." }, { "code": null, "e": 2555, "s": 2437, "text": "switchTo().defaultContent() – Switching focus from frame to the main page.Syntax −\ndriver.switchTo().defaultContent()" }, { "code": null, "e": 2630, "s": 2555, "text": "switchTo().defaultContent() – Switching focus from frame to the main page." }, { "code": null, "e": 2674, "s": 2630, "text": "Syntax −\ndriver.switchTo().defaultContent()" }, { "code": null, "e": 2695, "s": 2674, "text": "Code Implementation." }, { "code": null, "e": 3587, "s": 2695, "text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport java.util.concurrent.TimeUnit;\npublic class iFrameMethods{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.chrome.driver\", \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n driver.get(\"https://the-internet.herokuapp.com/frames\");\n driver.manage().timeouts().implicitlyWait(8, TimeUnit.SECONDS);\n // identify element and click\n driver.findElement(By.partialLinkText(\"Nested\")).click();\n // switching to frame with frame name\n driver.switchTo().frame(\"frame-bottom\");\n WebElement m = driver.findElement(By.cssSelector(\"body\"));\n System.out.println(\"Frame text: \" +m.getText());\n driver.close();\n }\n}" } ]
Automata Theory | Set 8 - GeeksforGeeks
25 Feb, 2019 These questions for practice purpose for GATE CS Exam. Ques-1: Which one of the following language is Regular? (A) {wxwR | w,x ∈ (a+b)+}(B) {wxwR | w ∈ (a+b)*, x ∈ {a,b}}(C) {wwRx | w,x ∈ (a+b)+}(D) {wwR | w ∈ (a+b)*} Explanation: (A) It is correct, since this language can form regular expression which is {{ a(a + b)+a } + {b(a + b)+b}}, i.e., start and end with same symbol. (B) It is deterministic context free language since, string before and and after ‘x’ are same so, it is matched. (C) It cannot be regular since, wwR is done at first which requires comparison which cannot be done via finite automata. (D) It is also not regular since, comparison is required. Option (A) is true. Ques-2: Let w be any string of length n in {a, b}*. Consider ‘L’ be the set of all strings ending with at least n a’s. What is the minimum number of states in non deterministic finite automata that accept ‘L’? (A) (n+3)(B) (n+1)(C) n(D) 2n Explanation:It is correct since, the minimum number of states required for NFA for ending with at least 2 a’s is (2 + 1) i.e., regular expression will be (a + b)*aaHence, Number of states required for at least n a’s will be (n+1). Option (B) is true. Ques-3: What is the minimum number of states in deterministic finite automata (DFA) for string starting with ba2 and ending with ‘a’ over alphabet {a, b}? (A) Ten(B) Nine(C) Eight(D) Six Explanation:In the above DFA, minimum number of states required is six. Option (D) is correct. Ques-4: Consider the following statements: S1 = {(an)m | n = 0} S2 = {anbn | n>=1} U {anbm | n>=1, m>=1} Which one of the following is regular? (A) only S1(B) only S2(C) both S1 and S2(D) none Explanation:Both given languages are regular. Option (C) is correct. Ques-5: What is the number of states in minimal NFA(non deterministic finite automata), which accepts set of all strings in which the third last symbol is ‘a’ over alphabet {a, b}? (A) three(B) four(C) six(D) five Explanation:In the above NFA, minimum number of states required is four. Option (B) is true. GATE GATE CS Theory of Computation Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments GATE | GATE-IT-2004 | Question 71 GATE | GATE CS 2011 | Question 7 GATE | GATE-CS-2015 (Set 3) | Question 65 GATE | GATE-CS-2014-(Set-3) | Question 38 GATE | GATE-CS-2016 (Set 2) | Question 48 Layers of OSI Model ACID Properties in DBMS Normal Forms in DBMS Types of Operating Systems Page Replacement Algorithms in Operating Systems
[ { "code": null, "e": 24580, "s": 24552, "text": "\n25 Feb, 2019" }, { "code": null, "e": 24635, "s": 24580, "text": "These questions for practice purpose for GATE CS Exam." }, { "code": null, "e": 24691, "s": 24635, "text": "Ques-1: Which one of the following language is Regular?" }, { "code": null, "e": 24798, "s": 24691, "text": "(A) {wxwR | w,x ∈ (a+b)+}(B) {wxwR | w ∈ (a+b)*, x ∈ {a,b}}(C) {wwRx | w,x ∈ (a+b)+}(D) {wwR | w ∈ (a+b)*}" }, { "code": null, "e": 24811, "s": 24798, "text": "Explanation:" }, { "code": null, "e": 24958, "s": 24811, "text": "(A) It is correct, since this language can form regular expression which is {{ a(a + b)+a } + {b(a + b)+b}}, i.e., start and end with same symbol." }, { "code": null, "e": 25071, "s": 24958, "text": "(B) It is deterministic context free language since, string before and and after ‘x’ are same so, it is matched." }, { "code": null, "e": 25192, "s": 25071, "text": "(C) It cannot be regular since, wwR is done at first which requires comparison which cannot be done via finite automata." }, { "code": null, "e": 25250, "s": 25192, "text": "(D) It is also not regular since, comparison is required." }, { "code": null, "e": 25270, "s": 25250, "text": "Option (A) is true." }, { "code": null, "e": 25480, "s": 25270, "text": "Ques-2: Let w be any string of length n in {a, b}*. Consider ‘L’ be the set of all strings ending with at least n a’s. What is the minimum number of states in non deterministic finite automata that accept ‘L’?" }, { "code": null, "e": 25510, "s": 25480, "text": "(A) (n+3)(B) (n+1)(C) n(D) 2n" }, { "code": null, "e": 25741, "s": 25510, "text": "Explanation:It is correct since, the minimum number of states required for NFA for ending with at least 2 a’s is (2 + 1) i.e., regular expression will be (a + b)*aaHence, Number of states required for at least n a’s will be (n+1)." }, { "code": null, "e": 25761, "s": 25741, "text": "Option (B) is true." }, { "code": null, "e": 25916, "s": 25761, "text": "Ques-3: What is the minimum number of states in deterministic finite automata (DFA) for string starting with ba2 and ending with ‘a’ over alphabet {a, b}?" }, { "code": null, "e": 25948, "s": 25916, "text": "(A) Ten(B) Nine(C) Eight(D) Six" }, { "code": null, "e": 26020, "s": 25948, "text": "Explanation:In the above DFA, minimum number of states required is six." }, { "code": null, "e": 26043, "s": 26020, "text": "Option (D) is correct." }, { "code": null, "e": 26086, "s": 26043, "text": "Ques-4: Consider the following statements:" }, { "code": null, "e": 26149, "s": 26086, "text": "S1 = {(an)m | n = 0}\nS2 = {anbn | n>=1} U {anbm | n>=1, m>=1} " }, { "code": null, "e": 26188, "s": 26149, "text": "Which one of the following is regular?" }, { "code": null, "e": 26237, "s": 26188, "text": "(A) only S1(B) only S2(C) both S1 and S2(D) none" }, { "code": null, "e": 26306, "s": 26237, "text": "Explanation:Both given languages are regular. Option (C) is correct." }, { "code": null, "e": 26487, "s": 26306, "text": "Ques-5: What is the number of states in minimal NFA(non deterministic finite automata), which accepts set of all strings in which the third last symbol is ‘a’ over alphabet {a, b}?" }, { "code": null, "e": 26520, "s": 26487, "text": "(A) three(B) four(C) six(D) five" }, { "code": null, "e": 26593, "s": 26520, "text": "Explanation:In the above NFA, minimum number of states required is four." }, { "code": null, "e": 26613, "s": 26593, "text": "Option (B) is true." }, { "code": null, "e": 26618, "s": 26613, "text": "GATE" }, { "code": null, "e": 26626, "s": 26618, "text": "GATE CS" }, { "code": null, "e": 26648, "s": 26626, "text": "Theory of Computation" }, { "code": null, "e": 26746, "s": 26648, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26755, "s": 26746, "text": "Comments" }, { "code": null, "e": 26768, "s": 26755, "text": "Old Comments" }, { "code": null, "e": 26802, "s": 26768, "text": "GATE | GATE-IT-2004 | Question 71" }, { "code": null, "e": 26835, "s": 26802, "text": "GATE | GATE CS 2011 | Question 7" }, { "code": null, "e": 26877, "s": 26835, "text": "GATE | GATE-CS-2015 (Set 3) | Question 65" }, { "code": null, "e": 26919, "s": 26877, "text": "GATE | GATE-CS-2014-(Set-3) | Question 38" }, { "code": null, "e": 26961, "s": 26919, "text": "GATE | GATE-CS-2016 (Set 2) | Question 48" }, { "code": null, "e": 26981, "s": 26961, "text": "Layers of OSI Model" }, { "code": null, "e": 27005, "s": 26981, "text": "ACID Properties in DBMS" }, { "code": null, "e": 27026, "s": 27005, "text": "Normal Forms in DBMS" }, { "code": null, "e": 27053, "s": 27026, "text": "Types of Operating Systems" } ]
C# program to count upper and lower case characters in a given string
To count uppercase characters in a string, check the following condition − myStr[i]>='A' &amp;&amp; myStr[i]<='Z' To count lower case characters in a string, check the following condition − myStr[i]>='a' &amp;&amp; myStr[i]<='z' You can try to run the following code to count upper and lower case characters in a given string. Live Demo using System; public class Demo { public static void Main() { string myStr; int i, len, lower_case, upper_case; myStr = "Hello"; Console.Write("String: "+myStr); lower_case = 0; upper_case = 0; len = myStr.Length; for(i=0; i<len; i++) { if(myStr[i]>='a' &amp;&amp; myStr[i]<='z') { lower_case++; } else if(myStr[i]>='A' &amp;&amp; myStr[i]<='Z') { upper_case++; } } Console.Write("\nCharacters in lowecase: {0}\n", lower_case); Console.Write("Characters in uppercase: {0}\n\n", upper_case); } } String: Hello Characters in lowecase: 4 Characters in uppercase: 1
[ { "code": null, "e": 1137, "s": 1062, "text": "To count uppercase characters in a string, check the following condition −" }, { "code": null, "e": 1176, "s": 1137, "text": "myStr[i]>='A' &amp;&amp; myStr[i]<='Z'" }, { "code": null, "e": 1252, "s": 1176, "text": "To count lower case characters in a string, check the following condition −" }, { "code": null, "e": 1291, "s": 1252, "text": "myStr[i]>='a' &amp;&amp; myStr[i]<='z'" }, { "code": null, "e": 1389, "s": 1291, "text": "You can try to run the following code to count upper and lower case characters in a given string." }, { "code": null, "e": 1399, "s": 1389, "text": "Live Demo" }, { "code": null, "e": 2017, "s": 1399, "text": "using System;\npublic class Demo {\n public static void Main() {\n string myStr;\n int i, len, lower_case, upper_case;\n myStr = \"Hello\";\n Console.Write(\"String: \"+myStr);\n lower_case = 0;\n upper_case = 0;\n len = myStr.Length;\n for(i=0; i<len; i++) {\n if(myStr[i]>='a' &amp;&amp; myStr[i]<='z') {\n lower_case++;\n } else if(myStr[i]>='A' &amp;&amp; myStr[i]<='Z') {\n upper_case++;\n }\n }\n Console.Write(\"\\nCharacters in lowecase: {0}\\n\", lower_case);\n Console.Write(\"Characters in uppercase: {0}\\n\\n\", upper_case);\n }\n}" }, { "code": null, "e": 2084, "s": 2017, "text": "String: Hello\nCharacters in lowecase: 4\nCharacters in uppercase: 1" } ]
Getting the most out of Jupyter Lab | by Adam Green | Towards Data Science
Love them or hate them, notebooks are part of being a data scientist. Historically the only way to work with notebooks was using Jupyter Notebook — in 2017 we were given Jupyter Lab. Jupyter Lab offers a superior development experience to Jupyter Notebook, with improvements such as: a file browser a text editor terminal access split views This post is aimed at showing off what Jupyter Lab can do. If you are already a Jupyter user, skip straight to the tips & tricks section. Install without a space: $ pip install jupyterlab Start a server with a space: $ jupyter lab You can then point your browser to http://localhost:8888/lab, and you'll see the Launcher screen, shown below with the File Browser open in the sidebar: Unlike Jupyter Notebook, you can have multiple tabs open side by side — you can also keep track of your kernels by selecting Running Terminals & Kernels in the sidebar: Something that can be confusing is the difference between the .ipynb notebook file, Jupyter Notebook & Jupyter Lab: a notebook file (.ipynb) is a JSON text file that defines the structure & code of a notebook Jupyter Notebook & Jupyter Lab are programs that allow you to run & edit notebook files Both Jupyter Notebook & Jupyter Lab can be used to run any .ipynb notebook file. Another area for confusion is what exactly a kernel is. A kernel is just a running Python interpreter, usually connected to a notebook. It is possible swap kernels after they are running, but it’s not something we do a lot. Kernels can be managed from the menu bar — restarting kernels is something that is done a lot. Unfortunately there are no default shortcuts setup for kernel management — see our post on Customizing Jupyter Lab Shortcuts to see how to set these up. In order to control which virtual environment you are using in the notebook, it’s best to activate the environment before you install Jupyter Lab or start the server. For example, if you are using conda to manage virtual environments: You’ll also want to make sure you activated this environment before installing Jupyter Lab. When editing notebooks, Jupyter Lab becomes a modal editor with two modes — Command and Edit: Command Mode for operating on cells Edit Mode for operating on text A modal editor will operate differently depending on the mode — the same key will do different things based on what mode you are in. You can see what mode you are in on the status bar. You can move between modes using: Enter to move from Command to Edit Escape to move from Edit to Command Cells can be run using Shift Enter in either mode, ending up in Command mode. A notebook is composed of cells — blocks that contain text. The text inside a cell can either be code, Markdown or raw text. The ability to have mix executable code and Markdown documentation is a key feature of notebooks. You can change the cell type using a dropdown: You can change cell types using the following shortcuts in Command mode:- m = change cell to Markdown - y = change cell to code Three other useful Command Mode shortcuts for operating on cells are:- a = insert cell above- b= insert cell below- dd = delete cell Mastering these five shortcuts will allow you to work with cells as efficiently as you work with text. This section is a rapid fire look at the features Jupyter Lab offers. Pressing Shift-Tab will show a tooltip for the function or class your cursor is on: Similar to the tooltip, except it’s always there. You can have this help always shown in a separate pane by opening a Show Contextual Help window from the Launcher: Consoles are another way to interact with a running kernel — a cool trick is to connect a console to a Python script (.py): No more committing README.md changes just to see the updates: These are actually iPython features, and will also work in an iPython kernel: a single ? to see the docstring a double ?? to see the source code Another iPython feature - running shell commands inside a notebook: You can use this to automatically install packages in the first cell of a notebook — make sure to use the -q flag to hide the output: Autoreload helps deal with the problem of source code outside the notebook not being reimported when it’s changed. This is only a problem when the source code changes after you start the kernel — essentially only when you are writing code yourself, external to the notebook. %load_ext autoreload%autoreload 2 Putting these two commands at the top of your notebook will mean that if you make changes to source code outside of the notebook, you can get these changes without having to restart the kernel. The most important tip of all — a dark theme: Below is a list of the most useful keyboard shortcuts in Jupyter Lab: Cmd B = toggle sidebar Alt W = close tab Enter= to move from Command to Edit Escape = to move from Edit to Command Shift Enter = run cell - a = insert cell above- b = insert cell below- dd = delete cell- z = undo cell- shift z = redo cell- m = change cell to Markdown- y = change cell to code - Cmd Z = undo text - Shift Cmd Z = redo text Thanks for reading! If you enjoyed this post, feel free to follow me on Medium or connect on LinkedIn. Make sure to check out some of my other posts: towardsdatascience.com towardsdatascience.com Originally published at https://www.datasciencesouth.com.
[ { "code": null, "e": 354, "s": 171, "text": "Love them or hate them, notebooks are part of being a data scientist. Historically the only way to work with notebooks was using Jupyter Notebook — in 2017 we were given Jupyter Lab." }, { "code": null, "e": 455, "s": 354, "text": "Jupyter Lab offers a superior development experience to Jupyter Notebook, with improvements such as:" }, { "code": null, "e": 470, "s": 455, "text": "a file browser" }, { "code": null, "e": 484, "s": 470, "text": "a text editor" }, { "code": null, "e": 500, "s": 484, "text": "terminal access" }, { "code": null, "e": 512, "s": 500, "text": "split views" }, { "code": null, "e": 650, "s": 512, "text": "This post is aimed at showing off what Jupyter Lab can do. If you are already a Jupyter user, skip straight to the tips & tricks section." }, { "code": null, "e": 675, "s": 650, "text": "Install without a space:" }, { "code": null, "e": 700, "s": 675, "text": "$ pip install jupyterlab" }, { "code": null, "e": 729, "s": 700, "text": "Start a server with a space:" }, { "code": null, "e": 743, "s": 729, "text": "$ jupyter lab" }, { "code": null, "e": 896, "s": 743, "text": "You can then point your browser to http://localhost:8888/lab, and you'll see the Launcher screen, shown below with the File Browser open in the sidebar:" }, { "code": null, "e": 1065, "s": 896, "text": "Unlike Jupyter Notebook, you can have multiple tabs open side by side — you can also keep track of your kernels by selecting Running Terminals & Kernels in the sidebar:" }, { "code": null, "e": 1181, "s": 1065, "text": "Something that can be confusing is the difference between the .ipynb notebook file, Jupyter Notebook & Jupyter Lab:" }, { "code": null, "e": 1274, "s": 1181, "text": "a notebook file (.ipynb) is a JSON text file that defines the structure & code of a notebook" }, { "code": null, "e": 1362, "s": 1274, "text": "Jupyter Notebook & Jupyter Lab are programs that allow you to run & edit notebook files" }, { "code": null, "e": 1443, "s": 1362, "text": "Both Jupyter Notebook & Jupyter Lab can be used to run any .ipynb notebook file." }, { "code": null, "e": 1667, "s": 1443, "text": "Another area for confusion is what exactly a kernel is. A kernel is just a running Python interpreter, usually connected to a notebook. It is possible swap kernels after they are running, but it’s not something we do a lot." }, { "code": null, "e": 1915, "s": 1667, "text": "Kernels can be managed from the menu bar — restarting kernels is something that is done a lot. Unfortunately there are no default shortcuts setup for kernel management — see our post on Customizing Jupyter Lab Shortcuts to see how to set these up." }, { "code": null, "e": 2150, "s": 1915, "text": "In order to control which virtual environment you are using in the notebook, it’s best to activate the environment before you install Jupyter Lab or start the server. For example, if you are using conda to manage virtual environments:" }, { "code": null, "e": 2242, "s": 2150, "text": "You’ll also want to make sure you activated this environment before installing Jupyter Lab." }, { "code": null, "e": 2336, "s": 2242, "text": "When editing notebooks, Jupyter Lab becomes a modal editor with two modes — Command and Edit:" }, { "code": null, "e": 2372, "s": 2336, "text": "Command Mode for operating on cells" }, { "code": null, "e": 2404, "s": 2372, "text": "Edit Mode for operating on text" }, { "code": null, "e": 2589, "s": 2404, "text": "A modal editor will operate differently depending on the mode — the same key will do different things based on what mode you are in. You can see what mode you are in on the status bar." }, { "code": null, "e": 2623, "s": 2589, "text": "You can move between modes using:" }, { "code": null, "e": 2658, "s": 2623, "text": "Enter to move from Command to Edit" }, { "code": null, "e": 2694, "s": 2658, "text": "Escape to move from Edit to Command" }, { "code": null, "e": 2772, "s": 2694, "text": "Cells can be run using Shift Enter in either mode, ending up in Command mode." }, { "code": null, "e": 2995, "s": 2772, "text": "A notebook is composed of cells — blocks that contain text. The text inside a cell can either be code, Markdown or raw text. The ability to have mix executable code and Markdown documentation is a key feature of notebooks." }, { "code": null, "e": 3042, "s": 2995, "text": "You can change the cell type using a dropdown:" }, { "code": null, "e": 3170, "s": 3042, "text": "You can change cell types using the following shortcuts in Command mode:- m = change cell to Markdown - y = change cell to code" }, { "code": null, "e": 3303, "s": 3170, "text": "Three other useful Command Mode shortcuts for operating on cells are:- a = insert cell above- b= insert cell below- dd = delete cell" }, { "code": null, "e": 3406, "s": 3303, "text": "Mastering these five shortcuts will allow you to work with cells as efficiently as you work with text." }, { "code": null, "e": 3476, "s": 3406, "text": "This section is a rapid fire look at the features Jupyter Lab offers." }, { "code": null, "e": 3560, "s": 3476, "text": "Pressing Shift-Tab will show a tooltip for the function or class your cursor is on:" }, { "code": null, "e": 3725, "s": 3560, "text": "Similar to the tooltip, except it’s always there. You can have this help always shown in a separate pane by opening a Show Contextual Help window from the Launcher:" }, { "code": null, "e": 3849, "s": 3725, "text": "Consoles are another way to interact with a running kernel — a cool trick is to connect a console to a Python script (.py):" }, { "code": null, "e": 3911, "s": 3849, "text": "No more committing README.md changes just to see the updates:" }, { "code": null, "e": 3989, "s": 3911, "text": "These are actually iPython features, and will also work in an iPython kernel:" }, { "code": null, "e": 4021, "s": 3989, "text": "a single ? to see the docstring" }, { "code": null, "e": 4056, "s": 4021, "text": "a double ?? to see the source code" }, { "code": null, "e": 4124, "s": 4056, "text": "Another iPython feature - running shell commands inside a notebook:" }, { "code": null, "e": 4258, "s": 4124, "text": "You can use this to automatically install packages in the first cell of a notebook — make sure to use the -q flag to hide the output:" }, { "code": null, "e": 4533, "s": 4258, "text": "Autoreload helps deal with the problem of source code outside the notebook not being reimported when it’s changed. This is only a problem when the source code changes after you start the kernel — essentially only when you are writing code yourself, external to the notebook." }, { "code": null, "e": 4567, "s": 4533, "text": "%load_ext autoreload%autoreload 2" }, { "code": null, "e": 4761, "s": 4567, "text": "Putting these two commands at the top of your notebook will mean that if you make changes to source code outside of the notebook, you can get these changes without having to restart the kernel." }, { "code": null, "e": 4807, "s": 4761, "text": "The most important tip of all — a dark theme:" }, { "code": null, "e": 4877, "s": 4807, "text": "Below is a list of the most useful keyboard shortcuts in Jupyter Lab:" }, { "code": null, "e": 4900, "s": 4877, "text": "Cmd B = toggle sidebar" }, { "code": null, "e": 4918, "s": 4900, "text": "Alt W = close tab" }, { "code": null, "e": 4954, "s": 4918, "text": "Enter= to move from Command to Edit" }, { "code": null, "e": 4992, "s": 4954, "text": "Escape = to move from Edit to Command" }, { "code": null, "e": 5015, "s": 4992, "text": "Shift Enter = run cell" }, { "code": null, "e": 5170, "s": 5015, "text": "- a = insert cell above- b = insert cell below- dd = delete cell- z = undo cell- shift z = redo cell- m = change cell to Markdown- y = change cell to code" }, { "code": null, "e": 5216, "s": 5170, "text": "- Cmd Z = undo text - Shift Cmd Z = redo text" }, { "code": null, "e": 5236, "s": 5216, "text": "Thanks for reading!" }, { "code": null, "e": 5319, "s": 5236, "text": "If you enjoyed this post, feel free to follow me on Medium or connect on LinkedIn." }, { "code": null, "e": 5366, "s": 5319, "text": "Make sure to check out some of my other posts:" }, { "code": null, "e": 5389, "s": 5366, "text": "towardsdatascience.com" }, { "code": null, "e": 5412, "s": 5389, "text": "towardsdatascience.com" } ]
Neural Network for Predicting the Energy Performance of a Building | by Marco Sanguineti | Towards Data Science
I spent years, during my master’s studies in engineering, trying to model energy systems. In most cases, only the simplest problems can be modelled directly (analytical resolution of the governing differential equations of the system studied), for particularly simple and convenient geometries and boundary conditions. More complex problems are tackled using various mathematical/numerical or procedural techniques to simplify their nature so that reasonably accurate, albeit approximate, calculation models can be developed. One of the most interesting aspects of my recent experience with the integration of Deep Learning and engineering in the broadest sense (structural analysis, fluid dynamics, energy systems...) is the possibility of approaching the problems studied in completely different ways. The abundance and complexity of data is no longer a problem, but an advantage, allowing more accurate and sophisticated forecasting models to be developed. It is no longer necessarily necessary to simplify a problem to the bone until it is perfectly interpretable and analytically solvable. The reliability of the data, coupled with complex neural network models, can be sufficient to model the system with more than acceptable engineering and functional accuracy. All this preamble is necessary to introduce the problem addressed in this article, i.e. the estimation of summer and winter heat loads of a building from a structured dataset. I have been confronted with this problem several times in my studies and my personal life. As is my practice, I have always dealt with the subject of estimating energy performance using the inevitable Excel spreadsheet and the relevant national legislation. This takes into account the sum of various contributions (direct and indirect solar load, ventilation, sensible and latent internal heat loads...) with an approach based on superposition of effects and one-dimensionality, generating a usual simplified approach to the problem. The interpretation of the standard, associated with its implementation, can be a far from trivial task, more for lack of clarity than for numerical difficulty of the calculation to be developed. The possibility of revolutionising this approach by coupling the huge amount of data that can be generated with numerical simulations or installed home automation sensors may be an interesting point of reflection. In this story, we will see how to develop a sequential (fully connected) Dense neural network model for estimating the summer and winter heat load of a building from an open-source dataset, generated with Autodesk Ecotect. We’ll evaluate the performance and the structure of our Network. This analysis starts from the Energy efficiency Data Set, freely available. This energy analysis covers 12 buildings. Each simulation was carried out with the Ecotect. The edifices differ in terms of the glazing area, the glazing area distribution, the orientation... Various combinations of the above parameters were tested, starting with a total of 8 degrees of freedom, to obtain 768 building shapes. The dataset comprises 768 samples, 8 features and two real-valued responses (outputs/features). The dataset comprises 8 attributes/features (Xi) and two responses/labels (Yi). “The goal is to use the eight features to predict each of the two responses. Specifically: X1 Relative Compactness X2 Surface Area X3 Wall Area X4 Roof Area X5 Overall Height X6 Orientation X7 Glazing Area X8 Glazing Area Distribution Y1 Heating Load Y2 Cooling Load” Autodesk Ecotect Analysis is an environmental analysis tool that enables designers to simulate building performance early in the conceptual design process. It combines analysis functions with an interactive visualisation that presents analytical results directly in the context of the building model. For this analysis, I used a Dense neural network. I used 2 hidden layers (shallow network), with 256 neurons/layer and ‘relu’ as activation functions. If you are interested in how I made this plot, I wrote an article about it. For this analysis, I choose the Keras Functional API for the generation of the Neural Network. You can find the source code here and the complete repository on GitHub and YouTube. I choose the Meas Squared Error as a loss function, monitoring also the Mean Absolute Error and the Mean Percentage Absolute Error during training. Finally, I use Adam as an adaptive learning rate optimizer, with no learning rate decay scheduling. Finally, the dataset has to be split into training and validation data. The data are normalized to facilitate the model training process. The Neural Network has been trained for 500 epochs, with a batch size of 128. We get a good trend of the training (blue line) and validation (orange line) loss. To assess the performance of the model, it is advisable to make validation plots. These plots show the exact value of the labels in the abscissa, while the ordinate shows the value predicted by the neural network for the same set of inputs. For the heating load, we get the following trends: From a quantitative point of view, the Mean Absolute Error, the Mean Squared Error, the Pearson Coefficient and the Coefficient of Determination were assessed. Y0 - mae-train - 0.00474Y0 - mse-train - 4.44430Y0 - r2-train - 0.99940Y0 - pearson-train - 0.99972Y0 - mae-test - 0.00947Y0 - mse-test - 0.00015Y0 - r2-test - 0.99783 We can see that our algorithm achieves very high accuracy on both sets (for both the coefficient of determination and the Pearson coefficient the ideal condition is a value of 1). For the cooling load, we get the following trends: From a quantitative point of view: Y1 - mae-train - 0.00685Y1 - mse-train - 8.63810Y1 - r2-train - 0.99870Y1 - pearson-train - 0.99951Y1 - mae-test - 0.01739Y1 - mse-test - 0.00058Y1 - r2-test - 0.99042Y1 - pearson-test - 0.99606 The results obtained continue to be very satisfactory, both numerically and qualitatively (trend). These results, although partial and deprived of the beneficial effects of possible optimisation and testing on further data never seen by the model, turned out to be promising and surprisingly accurate. We tackled a complex engineering problem with the interesting combination of simulation software + Deep Learning algorithms, exploiting the potential of Python, Colab and Tensorflow. We developed a neural network model, trained on a structured dataset, for the prediction of thermal loads. We obtained very good results, suggesting the possibility of applying this approach to evaluate thermal performance also on new data, as well as to address this kind of engineering analysis. Until next time,Marco 3-minutes machine learning is a series of tutorials, videos and articles related to the world of AI, Deep Learning, and Data Science. You can find the complete videos collection on YouTube. The GitHub repository contains all the Google Colab notebooks shown in the articles and videos. I hope these contents will be useful or simply of interest to you. Any feedback is welcome. Check out the other episodes: Images Generation with Neural Style Transfer and Tensorflow Cats VS Dogs Convolutional Classifier Plot a TensorFlow Model with Keras Functional API
[ { "code": null, "e": 698, "s": 172, "text": "I spent years, during my master’s studies in engineering, trying to model energy systems. In most cases, only the simplest problems can be modelled directly (analytical resolution of the governing differential equations of the system studied), for particularly simple and convenient geometries and boundary conditions. More complex problems are tackled using various mathematical/numerical or procedural techniques to simplify their nature so that reasonably accurate, albeit approximate, calculation models can be developed." }, { "code": null, "e": 976, "s": 698, "text": "One of the most interesting aspects of my recent experience with the integration of Deep Learning and engineering in the broadest sense (structural analysis, fluid dynamics, energy systems...) is the possibility of approaching the problems studied in completely different ways." }, { "code": null, "e": 1132, "s": 976, "text": "The abundance and complexity of data is no longer a problem, but an advantage, allowing more accurate and sophisticated forecasting models to be developed." }, { "code": null, "e": 1441, "s": 1132, "text": "It is no longer necessarily necessary to simplify a problem to the bone until it is perfectly interpretable and analytically solvable. The reliability of the data, coupled with complex neural network models, can be sufficient to model the system with more than acceptable engineering and functional accuracy." }, { "code": null, "e": 2347, "s": 1441, "text": "All this preamble is necessary to introduce the problem addressed in this article, i.e. the estimation of summer and winter heat loads of a building from a structured dataset. I have been confronted with this problem several times in my studies and my personal life. As is my practice, I have always dealt with the subject of estimating energy performance using the inevitable Excel spreadsheet and the relevant national legislation. This takes into account the sum of various contributions (direct and indirect solar load, ventilation, sensible and latent internal heat loads...) with an approach based on superposition of effects and one-dimensionality, generating a usual simplified approach to the problem. The interpretation of the standard, associated with its implementation, can be a far from trivial task, more for lack of clarity than for numerical difficulty of the calculation to be developed." }, { "code": null, "e": 2561, "s": 2347, "text": "The possibility of revolutionising this approach by coupling the huge amount of data that can be generated with numerical simulations or installed home automation sensors may be an interesting point of reflection." }, { "code": null, "e": 2849, "s": 2561, "text": "In this story, we will see how to develop a sequential (fully connected) Dense neural network model for estimating the summer and winter heat load of a building from an open-source dataset, generated with Autodesk Ecotect. We’ll evaluate the performance and the structure of our Network." }, { "code": null, "e": 3349, "s": 2849, "text": "This analysis starts from the Energy efficiency Data Set, freely available. This energy analysis covers 12 buildings. Each simulation was carried out with the Ecotect. The edifices differ in terms of the glazing area, the glazing area distribution, the orientation... Various combinations of the above parameters were tested, starting with a total of 8 degrees of freedom, to obtain 768 building shapes. The dataset comprises 768 samples, 8 features and two real-valued responses (outputs/features)." }, { "code": null, "e": 3429, "s": 3349, "text": "The dataset comprises 8 attributes/features (Xi) and two responses/labels (Yi)." }, { "code": null, "e": 3520, "s": 3429, "text": "“The goal is to use the eight features to predict each of the two responses. Specifically:" }, { "code": null, "e": 3544, "s": 3520, "text": "X1 Relative Compactness" }, { "code": null, "e": 3560, "s": 3544, "text": "X2 Surface Area" }, { "code": null, "e": 3573, "s": 3560, "text": "X3 Wall Area" }, { "code": null, "e": 3586, "s": 3573, "text": "X4 Roof Area" }, { "code": null, "e": 3604, "s": 3586, "text": "X5 Overall Height" }, { "code": null, "e": 3619, "s": 3604, "text": "X6 Orientation" }, { "code": null, "e": 3635, "s": 3619, "text": "X7 Glazing Area" }, { "code": null, "e": 3664, "s": 3635, "text": "X8 Glazing Area Distribution" }, { "code": null, "e": 3680, "s": 3664, "text": "Y1 Heating Load" }, { "code": null, "e": 3697, "s": 3680, "text": "Y2 Cooling Load”" }, { "code": null, "e": 3998, "s": 3697, "text": "Autodesk Ecotect Analysis is an environmental analysis tool that enables designers to simulate building performance early in the conceptual design process. It combines analysis functions with an interactive visualisation that presents analytical results directly in the context of the building model." }, { "code": null, "e": 4149, "s": 3998, "text": "For this analysis, I used a Dense neural network. I used 2 hidden layers (shallow network), with 256 neurons/layer and ‘relu’ as activation functions." }, { "code": null, "e": 4791, "s": 4149, "text": "If you are interested in how I made this plot, I wrote an article about it. For this analysis, I choose the Keras Functional API for the generation of the Neural Network. You can find the source code here and the complete repository on GitHub and YouTube. I choose the Meas Squared Error as a loss function, monitoring also the Mean Absolute Error and the Mean Percentage Absolute Error during training. Finally, I use Adam as an adaptive learning rate optimizer, with no learning rate decay scheduling. Finally, the dataset has to be split into training and validation data. The data are normalized to facilitate the model training process." }, { "code": null, "e": 4952, "s": 4791, "text": "The Neural Network has been trained for 500 epochs, with a batch size of 128. We get a good trend of the training (blue line) and validation (orange line) loss." }, { "code": null, "e": 5244, "s": 4952, "text": "To assess the performance of the model, it is advisable to make validation plots. These plots show the exact value of the labels in the abscissa, while the ordinate shows the value predicted by the neural network for the same set of inputs. For the heating load, we get the following trends:" }, { "code": null, "e": 5404, "s": 5244, "text": "From a quantitative point of view, the Mean Absolute Error, the Mean Squared Error, the Pearson Coefficient and the Coefficient of Determination were assessed." }, { "code": null, "e": 5572, "s": 5404, "text": "Y0 - mae-train - 0.00474Y0 - mse-train - 4.44430Y0 - r2-train - 0.99940Y0 - pearson-train - 0.99972Y0 - mae-test - 0.00947Y0 - mse-test - 0.00015Y0 - r2-test - 0.99783" }, { "code": null, "e": 5803, "s": 5572, "text": "We can see that our algorithm achieves very high accuracy on both sets (for both the coefficient of determination and the Pearson coefficient the ideal condition is a value of 1). For the cooling load, we get the following trends:" }, { "code": null, "e": 5838, "s": 5803, "text": "From a quantitative point of view:" }, { "code": null, "e": 6033, "s": 5838, "text": "Y1 - mae-train - 0.00685Y1 - mse-train - 8.63810Y1 - r2-train - 0.99870Y1 - pearson-train - 0.99951Y1 - mae-test - 0.01739Y1 - mse-test - 0.00058Y1 - r2-test - 0.99042Y1 - pearson-test - 0.99606" }, { "code": null, "e": 6335, "s": 6033, "text": "The results obtained continue to be very satisfactory, both numerically and qualitatively (trend). These results, although partial and deprived of the beneficial effects of possible optimisation and testing on further data never seen by the model, turned out to be promising and surprisingly accurate." }, { "code": null, "e": 6816, "s": 6335, "text": "We tackled a complex engineering problem with the interesting combination of simulation software + Deep Learning algorithms, exploiting the potential of Python, Colab and Tensorflow. We developed a neural network model, trained on a structured dataset, for the prediction of thermal loads. We obtained very good results, suggesting the possibility of applying this approach to evaluate thermal performance also on new data, as well as to address this kind of engineering analysis." }, { "code": null, "e": 6838, "s": 6816, "text": "Until next time,Marco" }, { "code": null, "e": 7216, "s": 6838, "text": "3-minutes machine learning is a series of tutorials, videos and articles related to the world of AI, Deep Learning, and Data Science. You can find the complete videos collection on YouTube. The GitHub repository contains all the Google Colab notebooks shown in the articles and videos. I hope these contents will be useful or simply of interest to you. Any feedback is welcome." }, { "code": null, "e": 7246, "s": 7216, "text": "Check out the other episodes:" }, { "code": null, "e": 7306, "s": 7246, "text": "Images Generation with Neural Style Transfer and Tensorflow" }, { "code": null, "e": 7344, "s": 7306, "text": "Cats VS Dogs Convolutional Classifier" } ]
What is a static class in Java?
You cannot use the static keyword with a class unless it is an inner class. A static inner class is a nested class which is a static member of the outer class. It can be accessed without instantiating the outer class, using other static members. Just like static members, a static nested class does not have access to the instance variables and methods of the outer class. class MyOuter { static class Nested_Demo { } } Instantiating a static nested class is a bit different from instantiating an inner class. The following program shows how to use a static nested class. Live Demo public class Outer { Java Arrays with Answers static class Nested_Demo { public void my_method() { System.out.println("This is my nested class"); } } public static void main(String args[]) { Outer.Nested_Demo nested = new Outer.Nested_Demo(); nested.my_method(); } } If you compile and execute the above program, you will get the following result − This is my nested class
[ { "code": null, "e": 1435, "s": 1062, "text": "You cannot use the static keyword with a class unless it is an inner class. A static inner class is a nested class which is a static member of the outer class. It can be accessed without instantiating the outer class, using other static members. Just like static members, a static nested class does not have access to the instance variables and methods of the outer class." }, { "code": null, "e": 1488, "s": 1435, "text": "class MyOuter {\n static class Nested_Demo {\n }\n}" }, { "code": null, "e": 1640, "s": 1488, "text": "Instantiating a static nested class is a bit different from instantiating an inner class. The following program shows how to use a static nested class." }, { "code": null, "e": 1650, "s": 1640, "text": "Live Demo" }, { "code": null, "e": 1965, "s": 1650, "text": "public class Outer {\n Java Arrays with Answers\n static class Nested_Demo {\n public void my_method() {\n System.out.println(\"This is my nested class\");\n }\n }\n public static void main(String args[]) {\n Outer.Nested_Demo nested = new Outer.Nested_Demo();\n nested.my_method();\n }\n}" }, { "code": null, "e": 2047, "s": 1965, "text": "If you compile and execute the above program, you will get the following result −" }, { "code": null, "e": 2071, "s": 2047, "text": "This is my nested class" } ]
LALR Parser (with Examples) - GeeksforGeeks
24 Jun, 2021 LALR Parser :LALR Parser is lookahead LR parser. It is the most powerful parser which can handle large classes of grammar. The size of CLR parsing table is quite large as compared to other parsing table. LALR reduces the size of this table.LALR works similar to CLR. The only difference is , it combines the similar states of CLR parsing table into one single state. The general syntax becomes [A->∝.B, a ]where A->∝.B is production and a is a terminal or right end marker $LR(1) items=LR(0) items + look ahead How to add lookahead with the production? CASE 1 – A->∝.BC, a Suppose this is the 0th production.Now, since ‘ . ‘ precedes B,so we have to write B’s productions as well. B->.D [1st production] Suppose this is B’s production. The look ahead of this production is given as- we look at previous production i.e. – 0th production. Whatever is after B, we find FIRST(of that value) , that is the lookahead of 1st production. So, here in 0th production, after B, C is there. Assume FIRST(C)=d, then 1st production become. B->.D, d CASE 2 –Now if the 0th production was like this, A->∝.B, a Here,we can see there’s nothing after B. So the lookahead of 0th production will be the lookahead of 1st production. ie- B->.D, a CASE 3 –Assume a production A->a|b A->a,$ [0th production] A->b,$ [1st production] Here, the 1st production is a part of the previous production, so the lookahead will be the same as that of its previous production. Steps for constructing the LALR parsing table : Writing augmented grammar LR(1) collection of items to be found Defining 2 functions: goto[list of terminals] and action[list of non-terminals] in the LALR parsing table Writing augmented grammar LR(1) collection of items to be found Defining 2 functions: goto[list of terminals] and action[list of non-terminals] in the LALR parsing table EXAMPLEConstruct CLR parsing table for the given context free grammar S-->AA A-->aA|b Solution: STEP1- Find augmented grammarThe augmented grammar of the given grammar is:- S'-->.S ,$ [0th production] S-->.AA ,$ [1st production] A-->.aA ,a|b [2nd production] A-->.b ,a|b [3rd production] Let’s apply the rule of lookahead to the above productions. The initial look ahead is always $ Now,the 1st production came into existence because of ‘ . ‘ before ‘S’ in 0th production.There is nothing after ‘S’, so the lookahead of 0th production will be the lookahead of 1st production. i.e. : S–>.AA ,$ Now,the 2nd production came into existence because of ‘ . ‘ before ‘A’ in the 1st production.After ‘A’, there’s ‘A’. So, FIRST(A) is a,b. Therefore, the lookahead of the 2nd production becomes a|b. Now,the 3rd production is a part of the 2nd production.So, the look ahead will be the same. STEP2 – Find LR(0) collection of itemsBelow is the figure showing the LR(0) collection of items. We will understand everything one by one. The terminals of this grammar are {a,b}The non-terminals of this grammar are {S,A} RULES – If any non-terminal has ‘ . ‘ preceding it, we have to write all its production and add ‘ . ‘ preceding each of its production. from each state to the next state, the ‘ . ‘ shifts to one place to the right. If any non-terminal has ‘ . ‘ preceding it, we have to write all its production and add ‘ . ‘ preceding each of its production. from each state to the next state, the ‘ . ‘ shifts to one place to the right. In the figure, I0 consists of augmented grammar. Io goes to I1 when ‘ . ‘ of 0th production is shifted towards the right of S(S’->S.). This state is the accept state . S is seen by the compiler. Since I1 is a part of the 0th production, the lookahead is same i.e. $ Io goes to I2 when ‘ . ‘ of 1st production is shifted towards right (S->A.A) . A is seen by the compiler. Since I2 is a part of the 1st production, the lookahead is same i.e. $. I0 goes to I3 when ‘ . ‘ of 2nd production is shifted towards the right (A->a.A) . a is seen by the compiler.since I3 is a part of 2nd production, the lookahead is same i.e. a|b. I0 goes to I4 when ‘ . ‘ of 3rd production is shifted towards right (A->b.) . b is seen by the compiler. Since I4 is a part of 3rd production, the lookahead is same i.e. a|b. I2 goes to I5 when ‘ . ‘ of 1st production is shifted towards right (S->AA.) . A is seen by the compiler. Since I5 is a part of the 1st production, the lookahead is same i.e. $. I2 goes to I6 when ‘ . ‘ of 2nd production is shifted towards the right (A->a.A) . A is seen by the compiler. Since I6 is a part of the 2nd production, the lookahead is same i.e. $. I2 goes to I7 when ‘ . ‘ of 3rd production is shifted towards right (A->b.) . A is seen by the compiler. Since I6 is a part of the 3rd production, the lookahead is same i.e. $. I3 goes to I3 when ‘ . ‘ of the 2nd production is shifted towards right (A->a.A) . a is seen by the compiler. Since I3 is a part of the 2nd production, the lookahead is same i.e. a|b. I3 goes to I8 when ‘ . ‘ of 2nd production is shifted towards the right (A->aA.) . A is seen by the compiler. Since I8 is a part of the 2nd production, the lookahead is same i.e. a|b. I6 goes to I9 when ‘ . ‘ of 2nd production is shifted towards the right (A->aA.) . A is seen by the compiler. Since I9 is a part of the 2nd production, the lookahead is same i.e. $. I6 goes to I6 when ‘ . ‘ of the 2nd production is shifted towards right (A->a.A) . a is seen by the compiler. Since I6 is a part of the 2nd production, the lookahead is same i.e. $. I6 goes to I7 when ‘ . ‘ of the 3rd production is shifted towards right (A->b.) . b is seen by the compiler. Since I6 is a part of the 3rd production, the lookahead is same i.e. $. STEP 3 –Defining 2 functions: goto[list of terminals] and action[list of non-terminals] in the parsing table.Below is the CLR parsing table Once we make a CLR parsing table, we can easily make a LALR parsing table from it. In the step2 diagram, we can see that I3 and I6 are similar except their lookaheads. I4 and I7 are similar except their lookaheads. I8 and I9 are similar except their lookaheads. In LALR parsing table construction , we merge these similar states. Wherever there is 3 or 6, make it 36(combined form) Wherever there is 4 or 7, make it 47(combined form) Wherever there is 8 or 9, make it 89(combined form) Below is the LALR parsing table. Now we have to remove the unwanted rows As we can see, 36 row has same data twice, so we delete 1 row. We combine two 47 row into one by combining each value in the single 47 row. We combine two 89 row into one by combining each value in the single 89 row. The final LALR table looks like the below. abhijithoyur Picked Compiler Design GATE CS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between Top down parsing and Bottom up parsing Loop Optimization in Compiler Design Issues in the design of a code generator Why FIRST and FOLLOW in Compiler Design? Problem on LR(0) parser Layers of OSI Model ACID Properties in DBMS Normal Forms in DBMS Types of Operating Systems
[ { "code": null, "e": 24438, "s": 24407, "text": " \n24 Jun, 2021\n" }, { "code": null, "e": 24952, "s": 24438, "text": "LALR Parser :LALR Parser is lookahead LR parser. It is the most powerful parser which can handle large classes of grammar. The size of CLR parsing table is quite large as compared to other parsing table. LALR reduces the size of this table.LALR works similar to CLR. The only difference is , it combines the similar states of CLR parsing table into one single state. The general syntax becomes [A->∝.B, a ]where A->∝.B is production and a is a terminal or right end marker $LR(1) items=LR(0) items + look ahead" }, { "code": null, "e": 24994, "s": 24952, "text": "How to add lookahead with the production?" }, { "code": null, "e": 25003, "s": 24994, "text": "CASE 1 –" }, { "code": null, "e": 25014, "s": 25003, "text": "A->∝.BC, a" }, { "code": null, "e": 25122, "s": 25014, "text": "Suppose this is the 0th production.Now, since ‘ . ‘ precedes B,so we have to write B’s productions as well." }, { "code": null, "e": 25145, "s": 25122, "text": "B->.D [1st production]" }, { "code": null, "e": 25467, "s": 25145, "text": "Suppose this is B’s production. The look ahead of this production is given as- we look at previous production i.e. – 0th production. Whatever is after B, we find FIRST(of that value) , that is the lookahead of 1st production. So, here in 0th production, after B, C is there. Assume FIRST(C)=d, then 1st production become." }, { "code": null, "e": 25476, "s": 25467, "text": "B->.D, d" }, { "code": null, "e": 25526, "s": 25476, "text": "CASE 2 –Now if the 0th production was like this," }, { "code": null, "e": 25536, "s": 25526, "text": "A->∝.B, a" }, { "code": null, "e": 25657, "s": 25536, "text": "Here,we can see there’s nothing after B. So the lookahead of 0th production will be the lookahead of 1st production. ie-" }, { "code": null, "e": 25666, "s": 25657, "text": "B->.D, a" }, { "code": null, "e": 25701, "s": 25666, "text": "CASE 3 –Assume a production A->a|b" }, { "code": null, "e": 25749, "s": 25701, "text": "A->a,$ [0th production]\nA->b,$ [1st production]" }, { "code": null, "e": 25882, "s": 25749, "text": "Here, the 1st production is a part of the previous production, so the lookahead will be the same as that of its previous production." }, { "code": null, "e": 25930, "s": 25882, "text": "Steps for constructing the LALR parsing table :" }, { "code": null, "e": 26102, "s": 25930, "text": "\nWriting augmented grammar\nLR(1) collection of items to be found\nDefining 2 functions: goto[list of terminals] and action[list of non-terminals] in the LALR parsing table\n" }, { "code": null, "e": 26128, "s": 26102, "text": "Writing augmented grammar" }, { "code": null, "e": 26166, "s": 26128, "text": "LR(1) collection of items to be found" }, { "code": null, "e": 26272, "s": 26166, "text": "Defining 2 functions: goto[list of terminals] and action[list of non-terminals] in the LALR parsing table" }, { "code": null, "e": 26342, "s": 26272, "text": "EXAMPLEConstruct CLR parsing table for the given context free grammar" }, { "code": null, "e": 26362, "s": 26342, "text": "S-->AA \nA-->aA|b" }, { "code": null, "e": 26372, "s": 26362, "text": "Solution:" }, { "code": null, "e": 26449, "s": 26372, "text": "STEP1- Find augmented grammarThe augmented grammar of the given grammar is:-" }, { "code": null, "e": 26580, "s": 26449, "text": "S'-->.S ,$ [0th production] \nS-->.AA ,$ [1st production] \nA-->.aA ,a|b [2nd production] \nA-->.b ,a|b [3rd production]" }, { "code": null, "e": 26640, "s": 26580, "text": "Let’s apply the rule of lookahead to the above productions." }, { "code": null, "e": 26675, "s": 26640, "text": "The initial look ahead is always $" }, { "code": null, "e": 26886, "s": 26675, "text": "Now,the 1st production came into existence because of ‘ . ‘ before ‘S’ in 0th production.There is nothing after ‘S’, so the lookahead of 0th production will be the lookahead of 1st production. i.e. : S–>.AA ,$" }, { "code": null, "e": 27085, "s": 26886, "text": "Now,the 2nd production came into existence because of ‘ . ‘ before ‘A’ in the 1st production.After ‘A’, there’s ‘A’. So, FIRST(A) is a,b. Therefore, the lookahead of the 2nd production becomes a|b." }, { "code": null, "e": 27177, "s": 27085, "text": "Now,the 3rd production is a part of the 2nd production.So, the look ahead will be the same." }, { "code": null, "e": 27316, "s": 27177, "text": "STEP2 – Find LR(0) collection of itemsBelow is the figure showing the LR(0) collection of items. We will understand everything one by one." }, { "code": null, "e": 27399, "s": 27316, "text": "The terminals of this grammar are {a,b}The non-terminals of this grammar are {S,A}" }, { "code": null, "e": 27407, "s": 27399, "text": "RULES –" }, { "code": null, "e": 27616, "s": 27407, "text": "\nIf any non-terminal has ‘ . ‘ preceding it, we have to write all its production and add ‘ . ‘ preceding each of its production.\nfrom each state to the next state, the ‘ . ‘ shifts to one place to the right.\n" }, { "code": null, "e": 27744, "s": 27616, "text": "If any non-terminal has ‘ . ‘ preceding it, we have to write all its production and add ‘ . ‘ preceding each of its production." }, { "code": null, "e": 27823, "s": 27744, "text": "from each state to the next state, the ‘ . ‘ shifts to one place to the right." }, { "code": null, "e": 27872, "s": 27823, "text": "In the figure, I0 consists of augmented grammar." }, { "code": null, "e": 28090, "s": 27872, "text": "Io goes to I1 when ‘ . ‘ of 0th production is shifted towards the right of S(S’->S.). This state is the accept state . S is seen by the compiler. Since I1 is a part of the 0th production, the lookahead is same i.e. $" }, { "code": null, "e": 28270, "s": 28090, "text": "Io goes to I2 when ‘ . ‘ of 1st production is shifted towards right (S->A.A) . A is seen by the compiler. Since I2 is a part of the 1st production, the lookahead is same i.e. $." }, { "code": null, "e": 28450, "s": 28270, "text": "I0 goes to I3 when ‘ . ‘ of 2nd production is shifted towards the right (A->a.A) . a is seen by the compiler.since I3 is a part of 2nd production, the lookahead is same i.e. a|b." }, { "code": null, "e": 28626, "s": 28450, "text": "I0 goes to I4 when ‘ . ‘ of 3rd production is shifted towards right (A->b.) . b is seen by the compiler. Since I4 is a part of 3rd production, the lookahead is same i.e. a|b." }, { "code": null, "e": 28805, "s": 28626, "text": "I2 goes to I5 when ‘ . ‘ of 1st production is shifted towards right (S->AA.) . A is seen by the compiler. Since I5 is a part of the 1st production, the lookahead is same i.e. $." }, { "code": null, "e": 28988, "s": 28805, "text": "I2 goes to I6 when ‘ . ‘ of 2nd production is shifted towards the right (A->a.A) . A is seen by the compiler. Since I6 is a part of the 2nd production, the lookahead is same i.e. $." }, { "code": null, "e": 29166, "s": 28988, "text": "I2 goes to I7 when ‘ . ‘ of 3rd production is shifted towards right (A->b.) . A is seen by the compiler. Since I6 is a part of the 3rd production, the lookahead is same i.e. $." }, { "code": null, "e": 29351, "s": 29166, "text": "I3 goes to I3 when ‘ . ‘ of the 2nd production is shifted towards right (A->a.A) . a is seen by the compiler. Since I3 is a part of the 2nd production, the lookahead is same i.e. a|b." }, { "code": null, "e": 29536, "s": 29351, "text": "I3 goes to I8 when ‘ . ‘ of 2nd production is shifted towards the right (A->aA.) . A is seen by the compiler. Since I8 is a part of the 2nd production, the lookahead is same i.e. a|b." }, { "code": null, "e": 29719, "s": 29536, "text": "I6 goes to I9 when ‘ . ‘ of 2nd production is shifted towards the right (A->aA.) . A is seen by the compiler. Since I9 is a part of the 2nd production, the lookahead is same i.e. $." }, { "code": null, "e": 29902, "s": 29719, "text": "I6 goes to I6 when ‘ . ‘ of the 2nd production is shifted towards right (A->a.A) . a is seen by the compiler. Since I6 is a part of the 2nd production, the lookahead is same i.e. $." }, { "code": null, "e": 30084, "s": 29902, "text": "I6 goes to I7 when ‘ . ‘ of the 3rd production is shifted towards right (A->b.) . b is seen by the compiler. Since I6 is a part of the 3rd production, the lookahead is same i.e. $." }, { "code": null, "e": 30224, "s": 30084, "text": "STEP 3 –Defining 2 functions: goto[list of terminals] and action[list of non-terminals] in the parsing table.Below is the CLR parsing table" }, { "code": null, "e": 30307, "s": 30224, "text": "Once we make a CLR parsing table, we can easily make a LALR parsing table from it." }, { "code": null, "e": 30346, "s": 30307, "text": "In the step2 diagram, we can see that " }, { "code": null, "e": 30393, "s": 30346, "text": "I3 and I6 are similar except their lookaheads." }, { "code": null, "e": 30440, "s": 30393, "text": "I4 and I7 are similar except their lookaheads." }, { "code": null, "e": 30487, "s": 30440, "text": "I8 and I9 are similar except their lookaheads." }, { "code": null, "e": 30556, "s": 30487, "text": "In LALR parsing table construction , we merge these similar states. " }, { "code": null, "e": 30609, "s": 30556, "text": "Wherever there is 3 or 6, make it 36(combined form)" }, { "code": null, "e": 30662, "s": 30609, "text": "Wherever there is 4 or 7, make it 47(combined form)" }, { "code": null, "e": 30715, "s": 30662, "text": "Wherever there is 8 or 9, make it 89(combined form)" }, { "code": null, "e": 30749, "s": 30715, "text": "Below is the LALR parsing table. " }, { "code": null, "e": 30789, "s": 30749, "text": "Now we have to remove the unwanted rows" }, { "code": null, "e": 30852, "s": 30789, "text": "As we can see, 36 row has same data twice, so we delete 1 row." }, { "code": null, "e": 30929, "s": 30852, "text": "We combine two 47 row into one by combining each value in the single 47 row." }, { "code": null, "e": 31006, "s": 30929, "text": "We combine two 89 row into one by combining each value in the single 89 row." }, { "code": null, "e": 31049, "s": 31006, "text": "The final LALR table looks like the below." }, { "code": null, "e": 31062, "s": 31049, "text": "abhijithoyur" }, { "code": null, "e": 31071, "s": 31062, "text": "\nPicked\n" }, { "code": null, "e": 31089, "s": 31071, "text": "\nCompiler Design\n" }, { "code": null, "e": 31099, "s": 31089, "text": "\nGATE CS\n" }, { "code": null, "e": 31304, "s": 31099, "text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n " }, { "code": null, "e": 31362, "s": 31304, "text": "Difference between Top down parsing and Bottom up parsing" }, { "code": null, "e": 31399, "s": 31362, "text": "Loop Optimization in Compiler Design" }, { "code": null, "e": 31440, "s": 31399, "text": "Issues in the design of a code generator" }, { "code": null, "e": 31481, "s": 31440, "text": "Why FIRST and FOLLOW in Compiler Design?" }, { "code": null, "e": 31505, "s": 31481, "text": "Problem on LR(0) parser" }, { "code": null, "e": 31525, "s": 31505, "text": "Layers of OSI Model" }, { "code": null, "e": 31549, "s": 31525, "text": "ACID Properties in DBMS" }, { "code": null, "e": 31570, "s": 31549, "text": "Normal Forms in DBMS" } ]
java.util.zip.Inflater.inflate() Method Example
The java.util.zip.Inflater.inflate(byte[] b) method uncompresses bytes into specified buffer. Returns actual number of bytes uncompressed. A return value of 0 indicates that needsInput() or needsDictionary() should be called in order to determine if more input data or a preset dictionary is required. In the latter case, getAdler() can be used to get the Adler-32 value of the dictionary required. Following is the declaration for java.util.zip.Inflater.inflate(byte[] b) method. public int inflate(byte[] b) throws DataFormatException b − the buffer for the uncompressed data. b − the buffer for the uncompressed data. the actual number of uncompressed bytes. DataFormatException − if the compressed data format is invalid. DataFormatException − if the compressed data format is invalid. The following example shows the usage of java.util.zip.Inflater.inflate(byte[] b) method. package com.tutorialspoint; import java.io.UnsupportedEncodingException; import java.util.zip.DataFormatException; import java.util.zip.Deflater; import java.util.zip.Inflater; public class InflaterDemo { public static void main(String[] args) throws DataFormatException, UnsupportedEncodingException { String message = "Welcome to TutorialsPoint.com;" +"Welcome to TutorialsPoint.com;" +"Welcome to TutorialsPoint.com;" +"Welcome to TutorialsPoint.com;" +"Welcome to TutorialsPoint.com;" +"Welcome to TutorialsPoint.com;" +"Welcome to TutorialsPoint.com;" +"Welcome to TutorialsPoint.com;" +"Welcome to TutorialsPoint.com;" +"Welcome to TutorialsPoint.com;"; System.out.println("Original Message length : " + message.length()); byte[] input = message.getBytes("UTF-8"); // Compress the bytes byte[] output = new byte[1024]; Deflater deflater = new Deflater(); deflater.setInput(input); deflater.finish(); int compressedDataLength = deflater.deflate(output); deflater.end(); System.out.println("Compressed Message length : " + compressedDataLength); // Decompress the bytes Inflater inflater = new Inflater(); inflater.setInput(output, 0, compressedDataLength); byte[] result = new byte[1024]; int resultLength = inflater.inflate(result); inflater.end(); // Decode the bytes into a String message = new String(result, 0, resultLength, "UTF-8"); System.out.println("UnCompressed Message length : " + message.length()); } } Let us compile and run the above program, this will produce the following result − Original Message length : 300 Compressed Message length : 42 UnCompressed Message length : 300 Print Add Notes Bookmark this page
[ { "code": null, "e": 2591, "s": 2192, "text": "The java.util.zip.Inflater.inflate(byte[] b) method uncompresses bytes into specified buffer. Returns actual number of bytes uncompressed. A return value of 0 indicates that needsInput() or needsDictionary() should be called in order to determine if more input data or a preset dictionary is required. In the latter case, getAdler() can be used to get the Adler-32 value of the dictionary required." }, { "code": null, "e": 2673, "s": 2591, "text": "Following is the declaration for java.util.zip.Inflater.inflate(byte[] b) method." }, { "code": null, "e": 2733, "s": 2673, "text": "public int inflate(byte[] b)\n throws DataFormatException\n" }, { "code": null, "e": 2775, "s": 2733, "text": "b − the buffer for the uncompressed data." }, { "code": null, "e": 2817, "s": 2775, "text": "b − the buffer for the uncompressed data." }, { "code": null, "e": 2858, "s": 2817, "text": "the actual number of uncompressed bytes." }, { "code": null, "e": 2922, "s": 2858, "text": "DataFormatException − if the compressed data format is invalid." }, { "code": null, "e": 2986, "s": 2922, "text": "DataFormatException − if the compressed data format is invalid." }, { "code": null, "e": 3076, "s": 2986, "text": "The following example shows the usage of java.util.zip.Inflater.inflate(byte[] b) method." }, { "code": null, "e": 4722, "s": 3076, "text": "package com.tutorialspoint;\n\nimport java.io.UnsupportedEncodingException;\nimport java.util.zip.DataFormatException;\nimport java.util.zip.Deflater;\nimport java.util.zip.Inflater;\n\npublic class InflaterDemo {\n public static void main(String[] args) \n throws DataFormatException, UnsupportedEncodingException {\n String message = \"Welcome to TutorialsPoint.com;\"\n +\"Welcome to TutorialsPoint.com;\"\n +\"Welcome to TutorialsPoint.com;\"\n +\"Welcome to TutorialsPoint.com;\"\n +\"Welcome to TutorialsPoint.com;\"\n +\"Welcome to TutorialsPoint.com;\"\n +\"Welcome to TutorialsPoint.com;\"\n +\"Welcome to TutorialsPoint.com;\"\n +\"Welcome to TutorialsPoint.com;\"\n +\"Welcome to TutorialsPoint.com;\";\n System.out.println(\"Original Message length : \" + message.length());\n byte[] input = message.getBytes(\"UTF-8\");\n\n // Compress the bytes\n byte[] output = new byte[1024];\n Deflater deflater = new Deflater();\n deflater.setInput(input);\n deflater.finish();\n int compressedDataLength = deflater.deflate(output);\n deflater.end();\n\n System.out.println(\"Compressed Message length : \" + compressedDataLength);\n\n // Decompress the bytes\n Inflater inflater = new Inflater();\n inflater.setInput(output, 0, compressedDataLength);\n byte[] result = new byte[1024];\n int resultLength = inflater.inflate(result);\n inflater.end();\n\n // Decode the bytes into a String\n message = new String(result, 0, resultLength, \"UTF-8\");\n \n System.out.println(\"UnCompressed Message length : \" + message.length());\n }\n}" }, { "code": null, "e": 4805, "s": 4722, "text": "Let us compile and run the above program, this will produce the following result −" }, { "code": null, "e": 4901, "s": 4805, "text": "Original Message length : 300\nCompressed Message length : 42\nUnCompressed Message length : 300\n" }, { "code": null, "e": 4908, "s": 4901, "text": " Print" }, { "code": null, "e": 4919, "s": 4908, "text": " Add Notes" } ]
Semantic-UI | Cards - GeeksforGeeks
01 Oct, 2021 Semantic UI is an open-source framework that uses CSS and jQuery to build great user interfaces. It is the same as a bootstrap for use and has great different elements to use to make your website look more amazing. It uses a class to add CSS to the elements. A card is used to displaying the content similar to a playing card. Example 1: This example creating a simple card using Semantic-ui. HTML <!DOCTYPE html> <html> <head> <title>Semantic UI</title> <link href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css" rel="stylesheet" /> </head> <body> <div class="ui container"> <div class="ui card"> <div class="image"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200509221352/image30.png"> </div> <div class="content"> <a class="header">Geeksforgeeks</a> <div class="description"> A Computer SCience Portal. </div> </div> <div class="extra content"> <a> <i class="user icon"></i> 1m Followers </a> </div> </div> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js"> </script> </body> </html> Output: Example 2: This example creating a Group of Card using Semantic-ui. HTML <!DOCTYPE html> <html> <head> <title>Semantic UI</title> <link href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css" rel="stylesheet" /> </head> <body> <div style="margin-top: 20px" class="ui container"> <div class="ui cards"> <div class="card"> <div class="content"> <img class="right floated mini ui image" src="https://media.geeksforgeeks.org/wp-content/uploads/20200509221352/image30.png"> <div class="header"> Geeksforgeeks </div> <div class="meta"> A computer science Portal </div> <div class="description"> Geeksforgeeks wants to follow you. </div> </div> <div class="extra content"> <div class="ui two buttons"> <div class="ui basic green button">Approve</div> <div class="ui basic red button">Decline</div> </div> </div> </div> <div class="card"> <div class="content"> <img class="right floated mini ui image" src="https://media.geeksforgeeks.org/wp-content/uploads/20200509221352/image30.png"> <div class="header"> Geeksforgeeks </div> <div class="meta"> A computer Science Portal. </div> <div class="description"> Geeksforgeeks wants to be your friend. </div> </div> <div class="extra content"> <div class="ui two buttons"> <div class="ui basic green button">Approve</div> <div class="ui basic red button">Decline</div> </div> </div> </div> </div> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js"> </script> </body></html> Output: Example 3: This example creating a card that contains some button using Semantic-ui. HTML <!DOCTYPE html> <html> <head> <title>Semantic UI</title> <link href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css" rel="stylesheet" /> </head> <body> <div style="margin-top: 20px" class="ui container"> <div class="ui card"> <div class="content"> <div class="header">Geeksforgeeks</div> </div> <div class="content"> <h4 class="ui sub header">Activity</h4> <div class="ui small feed"> <div class="event"> <div class="content"> <div class="summary"> Your friend Rahul Joined the course. </div> </div> </div> <div class="event"> <div class="content"> <div class="summary"> Started next Friday </div> </div> </div> </div> </div> <div class="extra content"> <button class="ui button"> Join Course </button> </div> </div> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js"> </script> </body> </html> Output: Image card with effect on hover: For this, you need the jQuery library imported. jQuery Code $('.special.cards .image').dimmer({ on: 'hover' }); Complete code: HTML <!DOCTYPE html><html> <head> <title>Semantic UI</title> <link href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css" rel="stylesheet" /> </head> <body> <div style="margin-top: 20px;" class="ui container"> <div class="ui special cards"> <div class="card"> <div class="blurring dimmable image"> <div class="ui dimmer"> <div class="content"> <div class="center"> <div class="ui inverted button"> Add Friend </div> </div> </div> </div> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200509221352/image30.png"> </div> <div class="content"> <a class="header">Geeksforgeeks</a> <div class="meta"> <span class="date">Newly Joined</span> </div> </div> <div class="extra content"> <a> <i class="users icon"></i> 10 Friends </a> </div> </div> <div class="card"> <div class="blurring dimmable image"> <div class="ui inverted dimmer"> <div class="content"> <div class="center"> <div class="ui primary button"> Add Friend </div> </div> </div> </div> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200509221352/image30.png"> </div> <div class="content"> <a class="header">Geeksforgeeks</a> <div class="meta"> <span class="date"> You and Geeksforgeeks have 20 mutual Friends </span> </div> </div> <div class="extra content"> <a> <i class="users icon"></i> 500 Friends. </a> </div> </div> </div> </div> <script src="https://code.jquery.com/jquery-3.1.1.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js"> </script> <script> $('.special.cards .image').dimmer({ on: 'hover' }); </script> </body></html> Output: Example 5: This example creating a card that contains some button using Semantic-ui. HTML <!DOCTYPE html> <html> <head> <title>Semantic UI</title> <link href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css" rel="stylesheet" /> </head> <body> <div style="margin-top: 20px" class="ui container"> <div class="ui cards"> <div class="card"> <div class="content"> <div class="header">Geeksforgeeks</div> <div class="description"> A Computer Science Portal. </div> </div> <div class="ui bottom attached button"> <i class="add icon"></i> Join </div> </div> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js"> </script> </body> </html> Output: Example 6: This example creating an approval card using Semantic-ui. HTML <!DOCTYPE html> <html> <head> <title>Semantic UI</title> <link href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css"rel="stylesheet" /> </head> <body> <div style="margin-top: 20px" class="ui container"> <div class="ui card"> <div class="content"> <i class="right floated like icon"></i> <i class="right floated star icon"></i> <div class="header">Geeksforgeeks</div> <div class="description"> <p></p> </div> </div> <div class="extra content"> <span class="left floated like"> <i class="like icon"></i> Like </span> <span class="right floated star"> <i class="star icon"></i> Star </span> </div> </div> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js"> </script> </body> </html> Output: You can try different things in the card from semantic-UI. adnanirshad158 Semantic-UI CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to create footer to stay at the bottom of a Web page? Types of CSS (Cascading Style Sheet) Create a Responsive Navbar using ReactJS How to position a div at the bottom of its container using CSS? Design a web page using HTML and CSS Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Convert a string to an integer in JavaScript Top 10 Angular Libraries For Web Developers
[ { "code": null, "e": 23982, "s": 23954, "text": "\n01 Oct, 2021" }, { "code": null, "e": 24241, "s": 23982, "text": "Semantic UI is an open-source framework that uses CSS and jQuery to build great user interfaces. It is the same as a bootstrap for use and has great different elements to use to make your website look more amazing. It uses a class to add CSS to the elements." }, { "code": null, "e": 24309, "s": 24241, "text": "A card is used to displaying the content similar to a playing card." }, { "code": null, "e": 24376, "s": 24309, "text": "Example 1: This example creating a simple card using Semantic-ui. " }, { "code": null, "e": 24381, "s": 24376, "text": "HTML" }, { "code": "<!DOCTYPE html> <html> <head> <title>Semantic UI</title> <link href=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css\" rel=\"stylesheet\" /> </head> <body> <div class=\"ui container\"> <div class=\"ui card\"> <div class=\"image\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200509221352/image30.png\"> </div> <div class=\"content\"> <a class=\"header\">Geeksforgeeks</a> <div class=\"description\"> A Computer SCience Portal. </div> </div> <div class=\"extra content\"> <a> <i class=\"user icon\"></i> 1m Followers </a> </div> </div> </div> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js\"> </script> </body> </html>", "e": 25411, "s": 24381, "text": null }, { "code": null, "e": 25420, "s": 25411, "text": "Output: " }, { "code": null, "e": 25431, "s": 25420, "text": "Example 2:" }, { "code": null, "e": 25488, "s": 25431, "text": "This example creating a Group of Card using Semantic-ui." }, { "code": null, "e": 25493, "s": 25488, "text": "HTML" }, { "code": "<!DOCTYPE html> <html> <head> <title>Semantic UI</title> <link href=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css\" rel=\"stylesheet\" /> </head> <body> <div style=\"margin-top: 20px\" class=\"ui container\"> <div class=\"ui cards\"> <div class=\"card\"> <div class=\"content\"> <img class=\"right floated mini ui image\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200509221352/image30.png\"> <div class=\"header\"> Geeksforgeeks </div> <div class=\"meta\"> A computer science Portal </div> <div class=\"description\"> Geeksforgeeks wants to follow you. </div> </div> <div class=\"extra content\"> <div class=\"ui two buttons\"> <div class=\"ui basic green button\">Approve</div> <div class=\"ui basic red button\">Decline</div> </div> </div> </div> <div class=\"card\"> <div class=\"content\"> <img class=\"right floated mini ui image\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200509221352/image30.png\"> <div class=\"header\"> Geeksforgeeks </div> <div class=\"meta\"> A computer Science Portal. </div> <div class=\"description\"> Geeksforgeeks wants to be your friend. </div> </div> <div class=\"extra content\"> <div class=\"ui two buttons\"> <div class=\"ui basic green button\">Approve</div> <div class=\"ui basic red button\">Decline</div> </div> </div> </div> </div> </div> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js\"> </script> </body></html>", "e": 27736, "s": 25493, "text": null }, { "code": null, "e": 27745, "s": 27736, "text": "Output: " }, { "code": null, "e": 27831, "s": 27745, "text": "Example 3: This example creating a card that contains some button using Semantic-ui. " }, { "code": null, "e": 27836, "s": 27831, "text": "HTML" }, { "code": "<!DOCTYPE html> <html> <head> <title>Semantic UI</title> <link href=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css\" rel=\"stylesheet\" /> </head> <body> <div style=\"margin-top: 20px\" class=\"ui container\"> <div class=\"ui card\"> <div class=\"content\"> <div class=\"header\">Geeksforgeeks</div> </div> <div class=\"content\"> <h4 class=\"ui sub header\">Activity</h4> <div class=\"ui small feed\"> <div class=\"event\"> <div class=\"content\"> <div class=\"summary\"> Your friend Rahul Joined the course. </div> </div> </div> <div class=\"event\"> <div class=\"content\"> <div class=\"summary\"> Started next Friday </div> </div> </div> </div> </div> <div class=\"extra content\"> <button class=\"ui button\"> Join Course </button> </div> </div> </div> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js\"> </script> </body> </html>", "e": 29294, "s": 27836, "text": null }, { "code": null, "e": 29303, "s": 29294, "text": "Output: " }, { "code": null, "e": 29385, "s": 29303, "text": "Image card with effect on hover: For this, you need the jQuery library imported. " }, { "code": null, "e": 29398, "s": 29385, "text": "jQuery Code " }, { "code": null, "e": 29453, "s": 29398, "text": "$('.special.cards .image').dimmer({\n on: 'hover'\n});" }, { "code": null, "e": 29469, "s": 29453, "text": "Complete code: " }, { "code": null, "e": 29474, "s": 29469, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>Semantic UI</title> <link href=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css\" rel=\"stylesheet\" /> </head> <body> <div style=\"margin-top: 20px;\" class=\"ui container\"> <div class=\"ui special cards\"> <div class=\"card\"> <div class=\"blurring dimmable image\"> <div class=\"ui dimmer\"> <div class=\"content\"> <div class=\"center\"> <div class=\"ui inverted button\"> Add Friend </div> </div> </div> </div> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200509221352/image30.png\"> </div> <div class=\"content\"> <a class=\"header\">Geeksforgeeks</a> <div class=\"meta\"> <span class=\"date\">Newly Joined</span> </div> </div> <div class=\"extra content\"> <a> <i class=\"users icon\"></i> 10 Friends </a> </div> </div> <div class=\"card\"> <div class=\"blurring dimmable image\"> <div class=\"ui inverted dimmer\"> <div class=\"content\"> <div class=\"center\"> <div class=\"ui primary button\"> Add Friend </div> </div> </div> </div> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200509221352/image30.png\"> </div> <div class=\"content\"> <a class=\"header\">Geeksforgeeks</a> <div class=\"meta\"> <span class=\"date\"> You and Geeksforgeeks have 20 mutual Friends </span> </div> </div> <div class=\"extra content\"> <a> <i class=\"users icon\"></i> 500 Friends. </a> </div> </div> </div> </div> <script src=\"https://code.jquery.com/jquery-3.1.1.min.js\" integrity=\"sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=\" crossorigin=\"anonymous\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js\"> </script> <script> $('.special.cards .image').dimmer({ on: 'hover' }); </script> </body></html>", "e": 32198, "s": 29474, "text": null }, { "code": null, "e": 32207, "s": 32198, "text": "Output: " }, { "code": null, "e": 32293, "s": 32207, "text": "Example 5: This example creating a card that contains some button using Semantic-ui. " }, { "code": null, "e": 32298, "s": 32293, "text": "HTML" }, { "code": "<!DOCTYPE html> <html> <head> <title>Semantic UI</title> <link href=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css\" rel=\"stylesheet\" /> </head> <body> <div style=\"margin-top: 20px\" class=\"ui container\"> <div class=\"ui cards\"> <div class=\"card\"> <div class=\"content\"> <div class=\"header\">Geeksforgeeks</div> <div class=\"description\"> A Computer Science Portal. </div> </div> <div class=\"ui bottom attached button\"> <i class=\"add icon\"></i> Join </div> </div> </div> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js\"> </script> </body> </html>", "e": 33211, "s": 32298, "text": null }, { "code": null, "e": 33220, "s": 33211, "text": "Output: " }, { "code": null, "e": 33290, "s": 33220, "text": "Example 6: This example creating an approval card using Semantic-ui. " }, { "code": null, "e": 33295, "s": 33290, "text": "HTML" }, { "code": "<!DOCTYPE html> <html> <head> <title>Semantic UI</title> <link href=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css\"rel=\"stylesheet\" /> </head> <body> <div style=\"margin-top: 20px\" class=\"ui container\"> <div class=\"ui card\"> <div class=\"content\"> <i class=\"right floated like icon\"></i> <i class=\"right floated star icon\"></i> <div class=\"header\">Geeksforgeeks</div> <div class=\"description\"> <p></p> </div> </div> <div class=\"extra content\"> <span class=\"left floated like\"> <i class=\"like icon\"></i> Like </span> <span class=\"right floated star\"> <i class=\"star icon\"></i> Star </span> </div> </div> </div> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js\"> </script> </body> </html>", "e": 34431, "s": 33295, "text": null }, { "code": null, "e": 34440, "s": 34431, "text": "Output: " }, { "code": null, "e": 34500, "s": 34440, "text": "You can try different things in the card from semantic-UI. " }, { "code": null, "e": 34515, "s": 34500, "text": "adnanirshad158" }, { "code": null, "e": 34527, "s": 34515, "text": "Semantic-UI" }, { "code": null, "e": 34531, "s": 34527, "text": "CSS" }, { "code": null, "e": 34548, "s": 34531, "text": "Web Technologies" }, { "code": null, "e": 34646, "s": 34548, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34655, "s": 34646, "text": "Comments" }, { "code": null, "e": 34668, "s": 34655, "text": "Old Comments" }, { "code": null, "e": 34726, "s": 34668, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 34763, "s": 34726, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 34804, "s": 34763, "text": "Create a Responsive Navbar using ReactJS" }, { "code": null, "e": 34868, "s": 34804, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 34905, "s": 34868, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 34947, "s": 34905, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 34980, "s": 34947, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 35023, "s": 34980, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 35068, "s": 35023, "text": "Convert a string to an integer in JavaScript" } ]
How to initialize an empty DateTime in C#
Set a DateTime to its minimum value. DateTime.MinValue; The above will display the minimum value i.e. 1/1/0001 Let us see how to display the minimum value and avoid adding null to a date to initialize it as empty. Live Demo using System; using System.Linq; public class Demo { public static void Main() { DateTime dt = DateTime.MinValue; Console.WriteLine(dt); } } 1/1/0001 12:00:00 AM
[ { "code": null, "e": 1099, "s": 1062, "text": "Set a DateTime to its minimum value." }, { "code": null, "e": 1118, "s": 1099, "text": "DateTime.MinValue;" }, { "code": null, "e": 1164, "s": 1118, "text": "The above will display the minimum value i.e." }, { "code": null, "e": 1173, "s": 1164, "text": "1/1/0001" }, { "code": null, "e": 1276, "s": 1173, "text": "Let us see how to display the minimum value and avoid adding null to a date to initialize it as empty." }, { "code": null, "e": 1287, "s": 1276, "text": " Live Demo" }, { "code": null, "e": 1446, "s": 1287, "text": "using System;\nusing System.Linq;\npublic class Demo {\n public static void Main() {\n DateTime dt = DateTime.MinValue;\n Console.WriteLine(dt);\n }\n}" }, { "code": null, "e": 1467, "s": 1446, "text": "1/1/0001 12:00:00 AM" } ]
GATE | GATE CS 2021 | Set 1 | Question 43 - GeeksforGeeks
24 May, 2021 Consider the relation R(P,Q,S,T,X,Y,Z,W) with the following functional dependencies. Consider the decomposition of the relation R into the constituent relations according to the following two decomposition schemes. Which one of the following options is correct?(A) D1 is a lossless decomposition, but D2 is a lossy decomposition(B) D1 is a lossy decomposition, but D2 is a lossless decomposition(C) Both D1 and D2 are lossless decompositions(D) Both D1 and D2 are lossy decompositionsAnswer: (A)Explanation: Lossless-Join Decomposition:Lossless-Join Decomposition:Decomposition of R into R1, R2, R3, R4 is a lossless-join decomposition if at least one of the following functional dependencies are in F+ (Closure of functional dependencies): R1 ∩ R2 → R1 OR R1 ∩ R2 → R2 For decomposition D1: R1(PQST) R2(PTX) R3(QY) R4(YZW) R1 ∩ R2 = (PT)+ = PTYXZW , it is a super key, so we can merge R1 and R2. combined table T1 is PQSTX similarly, R3 ∩ R4 =(Y)+ = YZW, it is a super key, so we can merge R3 and R4. another combined table T2 is QYZW. now, Q is common in both T1 and T2. T1 ∩ T2 = Q+ = QYZW, it is a super key, so we can merge T1 and T2. after combining, we get original table PQSTXYZW, Hence D1 is lossless join decomposition. For decomposition D2: R1(PQS) R2(TX) R3(QY) R4(YZW) since R2 has no common attributes as the primary key, so R2 cannot be merge with any other table, Hence D2 is lossy decomposition. Quiz of this Question 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-1) | Question 30 GATE | GATE-CS-2015 (Set 1) | Question 65 GATE | GATE CS 2010 | Question 45 GATE | GATE-CS-2015 (Set 3) | Question 65 C++ Program to count Vowels in a string using Pointer GATE | GATE-CS-2015 (Set 1) | Question 42 GATE | GATE-CS-2004 | Question 3 GATE | GATE CS 2011 | Question 65 GATE | GATE-CS-2014-(Set-3) | Question 65 GATE | GATE-CS-2009 | Question 60
[ { "code": null, "e": 24075, "s": 24047, "text": "\n24 May, 2021" }, { "code": null, "e": 24160, "s": 24075, "text": "Consider the relation R(P,Q,S,T,X,Y,Z,W) with the following functional dependencies." }, { "code": null, "e": 24290, "s": 24160, "text": "Consider the decomposition of the relation R into the constituent relations according to the following two decomposition schemes." }, { "code": null, "e": 24816, "s": 24290, "text": "Which one of the following options is correct?(A) D1 is a lossless decomposition, but D2 is a lossy decomposition(B) D1 is a lossy decomposition, but D2 is a lossless decomposition(C) Both D1 and D2 are lossless decompositions(D) Both D1 and D2 are lossy decompositionsAnswer: (A)Explanation: Lossless-Join Decomposition:Lossless-Join Decomposition:Decomposition of R into R1, R2, R3, R4 is a lossless-join decomposition if at least one of the following functional dependencies are in F+ (Closure of functional dependencies):" }, { "code": null, "e": 24848, "s": 24816, "text": "R1 ∩ R2 → R1\n OR\nR1 ∩ R2 → R2" }, { "code": null, "e": 24871, "s": 24848, "text": "For decomposition D1: " }, { "code": null, "e": 24880, "s": 24871, "text": "R1(PQST)" }, { "code": null, "e": 24888, "s": 24880, "text": "R2(PTX)" }, { "code": null, "e": 24895, "s": 24888, "text": "R3(QY)" }, { "code": null, "e": 24903, "s": 24895, "text": "R4(YZW)" }, { "code": null, "e": 24976, "s": 24903, "text": "R1 ∩ R2 = (PT)+ = PTYXZW , it is a super key, so we can merge R1 and R2." }, { "code": null, "e": 25003, "s": 24976, "text": "combined table T1 is PQSTX" }, { "code": null, "e": 25015, "s": 25003, "text": " similarly," }, { "code": null, "e": 25083, "s": 25015, "text": "R3 ∩ R4 =(Y)+ = YZW, it is a super key, so we can merge R3 and R4." }, { "code": null, "e": 25118, "s": 25083, "text": "another combined table T2 is QYZW." }, { "code": null, "e": 25154, "s": 25118, "text": "now, Q is common in both T1 and T2." }, { "code": null, "e": 25222, "s": 25154, "text": " T1 ∩ T2 = Q+ = QYZW, it is a super key, so we can merge T1 and T2." }, { "code": null, "e": 25271, "s": 25222, "text": "after combining, we get original table PQSTXYZW," }, { "code": null, "e": 25312, "s": 25271, "text": "Hence D1 is lossless join decomposition." }, { "code": null, "e": 25335, "s": 25312, "text": "For decomposition D2: " }, { "code": null, "e": 25343, "s": 25335, "text": "R1(PQS)" }, { "code": null, "e": 25350, "s": 25343, "text": "R2(TX)" }, { "code": null, "e": 25357, "s": 25350, "text": "R3(QY)" }, { "code": null, "e": 25365, "s": 25357, "text": "R4(YZW)" }, { "code": null, "e": 25464, "s": 25365, "text": "since R2 has no common attributes as the primary key, so R2 cannot be merge with any other table, " }, { "code": null, "e": 25497, "s": 25464, "text": "Hence D2 is lossy decomposition." }, { "code": null, "e": 25519, "s": 25497, "text": "Quiz of this Question" }, { "code": null, "e": 25524, "s": 25519, "text": "GATE" }, { "code": null, "e": 25622, "s": 25524, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25631, "s": 25622, "text": "Comments" }, { "code": null, "e": 25644, "s": 25631, "text": "Old Comments" }, { "code": null, "e": 25686, "s": 25644, "text": "GATE | GATE-CS-2014-(Set-1) | Question 30" }, { "code": null, "e": 25728, "s": 25686, "text": "GATE | GATE-CS-2015 (Set 1) | Question 65" }, { "code": null, "e": 25762, "s": 25728, "text": "GATE | GATE CS 2010 | Question 45" }, { "code": null, "e": 25804, "s": 25762, "text": "GATE | GATE-CS-2015 (Set 3) | Question 65" }, { "code": null, "e": 25858, "s": 25804, "text": "C++ Program to count Vowels in a string using Pointer" }, { "code": null, "e": 25900, "s": 25858, "text": "GATE | GATE-CS-2015 (Set 1) | Question 42" }, { "code": null, "e": 25933, "s": 25900, "text": "GATE | GATE-CS-2004 | Question 3" }, { "code": null, "e": 25967, "s": 25933, "text": "GATE | GATE CS 2011 | Question 65" }, { "code": null, "e": 26009, "s": 25967, "text": "GATE | GATE-CS-2014-(Set-3) | Question 65" } ]
The Most Important Statistical Test | by Wicaksono Wijono | Towards Data Science
The likelihood ratio test (LRT) “unifies” frequentist statistical tests. Brand-name tests like t-test, F-test, chi-squared-test, and so on are specific cases (or even approximations) of the LRT. Thus, it is surprising that many people have never heard of LRT. When I help people with their statistical questions, most of the time they only need to perform LRT and they’re done. But then they ask what it is and how to perform it. If you must know a single statistical test by heart, it should be LRT. This article will walk you through the theory and application of LRT. Basic understanding of mathematical statistics is assumed. Though I lean Bayesian, any applied statistician must understand basic frequentist methods too. People often don’t have time to learn the theoretical overhead and superiors ask for p-values in reports. As the name implies, we take the ratio of two likelihoods and transform it: I apologize for the obtuse notation but it is consistent with the one in Wikipedia so please consult it for clarification. The numerator is the likelihood under the null hypothesis, while the denominator is the maximum likelihood under the union of the null and alternative hypotheses. I denote this quantity ΔD to mean the difference in deviance, -2 log likelihood + some constant (that cancels out from the subtraction), between the null model and the relaxed model. If this is unclear right now, don’t worry; as we work through some examples below, the LRT should become more clear. Those who have seen AIC or BIC in passing might be puzzled by the seemingly arbitrary -2, but deviance is important because ΔD is asymptotically χ2-distributed with degrees of freedom (df) equal to the difference in df between the two models (the difference in number of estimated parameters). This amazing fact enables the majority of hypothesis testing. The use of the LRT is justified by the Neyman-Pearson lemma, which states that the LRT is the most powerful test to compare two simple hypotheses, e.g. H0: θ = 0 and Ha: θ = 2. Because the alternative hypothesis is usually not simple, like θ ≠ 0, we use maximum likelihood estimation (MLE) to reduce it to a simple one such as θ = 2. Commonly the MLE is done through (generalized) linear regression. Intuitively, if we cannot reject the null hypothesis at the MLE, then we cannot possibly reject at any other point, so the MLE is the only point that matters. In human language, we are comparing two models: one with a constraint and one with a relaxation of the constraint. You often see it as In the null model, we constrain the mean to be 0. In the alternative model, we allow the mean to be nonzero. We then need to specify a likelihood function. Here, to keep it familiar, we’ll posit that the observations come from a normal distribution with a known variance σ2 = 1. The MLE is the sample mean. Thus: This looks gnarly, but the ΔD term looks familiar: regression sum of squares (SS)! (It should be scaled, but here the scale parameter is 1.) It can be re-expressed as total SS minus the residual SS, as in the second line. And the χ2 distribution is defined as the SS from a standard normal distribution, so this all makes sense. Because in the alternative model we estimate one extra parameter, ΔD follows the χ2 distribution with 1 df. What if the variance is unknown? Then the null model estimates one parameter while the alternative model estimates two, so the difference in df is still 1. And in this case, we know this more familiarly as the ANOVA or F-test, which in this example is equivalent to the t-test on the intercept. Remember my point about how all of these statistical tests with different names are actually the same thing (LRT)? Yeah. Here’s some R code to demonstrate the equivalence: set.seed(123)x <- rnorm(50, 0.5, 1)model0 <- lm(x~0)model1 <- lm(x~1)anova(model0, model1)summary(model1)t.test(x) You can think of deviance as a generalization of SS applied to distributions other than the normal. Though not completely accurate, the intuition is there. As an exercise, compare the binomial deviance to the log loss function that is sometimes optimized in classification models. Other than testing sample means, we often want to test for independence in contingency tables. Statistics is riddled with many antiquated traditions and this is one of them. Most would immediately jump to Pearson’s Chi-Squared test but this is merely an approximation (by Taylor expansion) of the G-test, a specific case of LRT. Before calculators, it was difficult to take logarithms so statisticians used the Chi-Squared test for computational ease. It is surprising that we now have calculators but still have not switched over to the G-test by default. (Another common alternative, Fisher’s Exact Test, provides exact p-values instead of relying on asymptotics but the factorials make it computationally impractical for large sample sizes.) What is the likelihood? Under independence, we can think of the data as being generated from a multinomial distribution where the probability of falling in each cell is With dependence, the probability of falling in each cell is And we can compute the ΔD as: which is equivalent to the test statistic in the Wikipedia page for G-test. This looks suspiciously like KL divergence, hm? Funny how many concepts are so interconnected with each other. We can easily perform this test using Poisson regression: y~x1+x2 against y~x1+x2+x1*x2. (Equivalence to multinomial model left as an exercise. Oh no. I have become the thing I hated.) When all the πN are large, Chi-Squared test and G-test yield similar p-values. The G-test should be preferable because the LRT is the most powerful test and the distribution of the test statistic more closely matches the χ2 distribution. library(data.table)N <- 100 # play around with thisfactor1 <- sample( c('A', 'B'), N, replace = TRUE, prob = c(0.4, 0.6))factor2 <- ifelse( factor1 == 'A', sample(c('C', 'D'), N, replace = TRUE, prob = c(0.3, 0.7)), sample(c('C', 'D'), N, replace = TRUE, prob = c(0.7, 0.3)))dat <- data.table(factor1, factor2)xtab <- table(dat)dat_count <- dat[,.N, by = .(factor1, factor2)]model_indep <- glm( N~factor1+factor2, data = dat_count, family = 'poisson')model_dep <- glm( N~factor1*factor2, data = dat_count, family = 'poisson')summary(model_indep)summary(model_dep) # the fitted match the observed so deviance = 0pchisq(model_indep$deviance, df = 1, lower.tail = FALSE) # G-testchisq.test(xtab) # Chi-Squared test The above is the general procedure for LRT. We fit a simpler regression model and compare the deviance against a more complex model. From the two previous examples, hopefully, it was clear: Compute the maximum log likelihood under the constrained null modelCompute the maximum log likelihood when the constraint is relaxedCompare ΔD against the χ2 distribution with the appropriate df to get the p-value Compute the maximum log likelihood under the constrained null model Compute the maximum log likelihood when the constraint is relaxed Compare ΔD against the χ2 distribution with the appropriate df to get the p-value The model in 1) has to be nested under 2). After all, that’s what relaxing constraints means. Otherwise, ΔD doesn’t have the theoretical guarantees. For instance, ΔD of y~x1 against y~x1+x2 is fair game because in the first model we constrain b2 = 0 while in the second model we relax this constraint. However, ΔD of y~x1 against y~x2 is meaningless. In the first model we don’t have the constraint b1 = 0 while in the second model we do have the constraint b1 = 0. For b2, it’s vice versa. Sometimes we have hypotheses like H0: θ ≤ 0 and Ha: θ > 0. To make sure the models are simple and nested, the null model should be the MLE when θ ≤ 0 while the alternative model should be MLE when θ is any real number. Computing MLE by hand is cumbersome and most of the time the MLE does not have closed-form solutions. Luckily, we can harness the power of computers. For linear models, statistical packages have built-in functions to compute MLE for GLMs, which cover most of the hypotheses you want to test. (Be careful! In Python, sklearn’s logistic regression function does NOT compute the MLE and will yield incorrect deviances. Use statsmodels instead.) I’d argue that GLM is the most important skill for applied statisticians because so many inferential tasks can be framed as GLM problems. For more complicated likelihood functions (e.g. censoring and truncation), you need to write down the function and perform numerical optimization. You can abandon dozens of different statistical tests and replace them with the LRT (mostly through GLM), which should be the most powerful test anyway. Learn how to frame questions as the correct regression formulas, choose the most reasonable distribution, and diagnose the models. Writing the correct regression formula is the trickiest part. Adding too many variables can result in grossly incorrect inferences. Stepwise regression is a poster child of what not to do, while regularization methods are not MLE so we cannot compute ΔD. See a previous article to learn how to pick variables.
[ { "code": null, "e": 367, "s": 172, "text": "The likelihood ratio test (LRT) “unifies” frequentist statistical tests. Brand-name tests like t-test, F-test, chi-squared-test, and so on are specific cases (or even approximations) of the LRT." }, { "code": null, "e": 673, "s": 367, "text": "Thus, it is surprising that many people have never heard of LRT. When I help people with their statistical questions, most of the time they only need to perform LRT and they’re done. But then they ask what it is and how to perform it. If you must know a single statistical test by heart, it should be LRT." }, { "code": null, "e": 802, "s": 673, "text": "This article will walk you through the theory and application of LRT. Basic understanding of mathematical statistics is assumed." }, { "code": null, "e": 1004, "s": 802, "text": "Though I lean Bayesian, any applied statistician must understand basic frequentist methods too. People often don’t have time to learn the theoretical overhead and superiors ask for p-values in reports." }, { "code": null, "e": 1080, "s": 1004, "text": "As the name implies, we take the ratio of two likelihoods and transform it:" }, { "code": null, "e": 1666, "s": 1080, "text": "I apologize for the obtuse notation but it is consistent with the one in Wikipedia so please consult it for clarification. The numerator is the likelihood under the null hypothesis, while the denominator is the maximum likelihood under the union of the null and alternative hypotheses. I denote this quantity ΔD to mean the difference in deviance, -2 log likelihood + some constant (that cancels out from the subtraction), between the null model and the relaxed model. If this is unclear right now, don’t worry; as we work through some examples below, the LRT should become more clear." }, { "code": null, "e": 2022, "s": 1666, "text": "Those who have seen AIC or BIC in passing might be puzzled by the seemingly arbitrary -2, but deviance is important because ΔD is asymptotically χ2-distributed with degrees of freedom (df) equal to the difference in df between the two models (the difference in number of estimated parameters). This amazing fact enables the majority of hypothesis testing." }, { "code": null, "e": 2199, "s": 2022, "text": "The use of the LRT is justified by the Neyman-Pearson lemma, which states that the LRT is the most powerful test to compare two simple hypotheses, e.g. H0: θ = 0 and Ha: θ = 2." }, { "code": null, "e": 2582, "s": 2199, "text": "Because the alternative hypothesis is usually not simple, like θ ≠ 0, we use maximum likelihood estimation (MLE) to reduce it to a simple one such as θ = 2. Commonly the MLE is done through (generalized) linear regression. Intuitively, if we cannot reject the null hypothesis at the MLE, then we cannot possibly reject at any other point, so the MLE is the only point that matters." }, { "code": null, "e": 2717, "s": 2582, "text": "In human language, we are comparing two models: one with a constraint and one with a relaxation of the constraint. You often see it as" }, { "code": null, "e": 3030, "s": 2717, "text": "In the null model, we constrain the mean to be 0. In the alternative model, we allow the mean to be nonzero. We then need to specify a likelihood function. Here, to keep it familiar, we’ll posit that the observations come from a normal distribution with a known variance σ2 = 1. The MLE is the sample mean. Thus:" }, { "code": null, "e": 3467, "s": 3030, "text": "This looks gnarly, but the ΔD term looks familiar: regression sum of squares (SS)! (It should be scaled, but here the scale parameter is 1.) It can be re-expressed as total SS minus the residual SS, as in the second line. And the χ2 distribution is defined as the SS from a standard normal distribution, so this all makes sense. Because in the alternative model we estimate one extra parameter, ΔD follows the χ2 distribution with 1 df." }, { "code": null, "e": 3762, "s": 3467, "text": "What if the variance is unknown? Then the null model estimates one parameter while the alternative model estimates two, so the difference in df is still 1. And in this case, we know this more familiarly as the ANOVA or F-test, which in this example is equivalent to the t-test on the intercept." }, { "code": null, "e": 3934, "s": 3762, "text": "Remember my point about how all of these statistical tests with different names are actually the same thing (LRT)? Yeah. Here’s some R code to demonstrate the equivalence:" }, { "code": null, "e": 4049, "s": 3934, "text": "set.seed(123)x <- rnorm(50, 0.5, 1)model0 <- lm(x~0)model1 <- lm(x~1)anova(model0, model1)summary(model1)t.test(x)" }, { "code": null, "e": 4330, "s": 4049, "text": "You can think of deviance as a generalization of SS applied to distributions other than the normal. Though not completely accurate, the intuition is there. As an exercise, compare the binomial deviance to the log loss function that is sometimes optimized in classification models." }, { "code": null, "e": 4504, "s": 4330, "text": "Other than testing sample means, we often want to test for independence in contingency tables. Statistics is riddled with many antiquated traditions and this is one of them." }, { "code": null, "e": 5075, "s": 4504, "text": "Most would immediately jump to Pearson’s Chi-Squared test but this is merely an approximation (by Taylor expansion) of the G-test, a specific case of LRT. Before calculators, it was difficult to take logarithms so statisticians used the Chi-Squared test for computational ease. It is surprising that we now have calculators but still have not switched over to the G-test by default. (Another common alternative, Fisher’s Exact Test, provides exact p-values instead of relying on asymptotics but the factorials make it computationally impractical for large sample sizes.)" }, { "code": null, "e": 5244, "s": 5075, "text": "What is the likelihood? Under independence, we can think of the data as being generated from a multinomial distribution where the probability of falling in each cell is" }, { "code": null, "e": 5304, "s": 5244, "text": "With dependence, the probability of falling in each cell is" }, { "code": null, "e": 5334, "s": 5304, "text": "And we can compute the ΔD as:" }, { "code": null, "e": 5521, "s": 5334, "text": "which is equivalent to the test statistic in the Wikipedia page for G-test. This looks suspiciously like KL divergence, hm? Funny how many concepts are so interconnected with each other." }, { "code": null, "e": 5706, "s": 5521, "text": "We can easily perform this test using Poisson regression: y~x1+x2 against y~x1+x2+x1*x2. (Equivalence to multinomial model left as an exercise. Oh no. I have become the thing I hated.)" }, { "code": null, "e": 5944, "s": 5706, "text": "When all the πN are large, Chi-Squared test and G-test yield similar p-values. The G-test should be preferable because the LRT is the most powerful test and the distribution of the test statistic more closely matches the χ2 distribution." }, { "code": null, "e": 6676, "s": 5944, "text": "library(data.table)N <- 100 # play around with thisfactor1 <- sample( c('A', 'B'), N, replace = TRUE, prob = c(0.4, 0.6))factor2 <- ifelse( factor1 == 'A', sample(c('C', 'D'), N, replace = TRUE, prob = c(0.3, 0.7)), sample(c('C', 'D'), N, replace = TRUE, prob = c(0.7, 0.3)))dat <- data.table(factor1, factor2)xtab <- table(dat)dat_count <- dat[,.N, by = .(factor1, factor2)]model_indep <- glm( N~factor1+factor2, data = dat_count, family = 'poisson')model_dep <- glm( N~factor1*factor2, data = dat_count, family = 'poisson')summary(model_indep)summary(model_dep) # the fitted match the observed so deviance = 0pchisq(model_indep$deviance, df = 1, lower.tail = FALSE) # G-testchisq.test(xtab) # Chi-Squared test" }, { "code": null, "e": 6809, "s": 6676, "text": "The above is the general procedure for LRT. We fit a simpler regression model and compare the deviance against a more complex model." }, { "code": null, "e": 6866, "s": 6809, "text": "From the two previous examples, hopefully, it was clear:" }, { "code": null, "e": 7080, "s": 6866, "text": "Compute the maximum log likelihood under the constrained null modelCompute the maximum log likelihood when the constraint is relaxedCompare ΔD against the χ2 distribution with the appropriate df to get the p-value" }, { "code": null, "e": 7148, "s": 7080, "text": "Compute the maximum log likelihood under the constrained null model" }, { "code": null, "e": 7214, "s": 7148, "text": "Compute the maximum log likelihood when the constraint is relaxed" }, { "code": null, "e": 7296, "s": 7214, "text": "Compare ΔD against the χ2 distribution with the appropriate df to get the p-value" }, { "code": null, "e": 7445, "s": 7296, "text": "The model in 1) has to be nested under 2). After all, that’s what relaxing constraints means. Otherwise, ΔD doesn’t have the theoretical guarantees." }, { "code": null, "e": 7598, "s": 7445, "text": "For instance, ΔD of y~x1 against y~x1+x2 is fair game because in the first model we constrain b2 = 0 while in the second model we relax this constraint." }, { "code": null, "e": 7787, "s": 7598, "text": "However, ΔD of y~x1 against y~x2 is meaningless. In the first model we don’t have the constraint b1 = 0 while in the second model we do have the constraint b1 = 0. For b2, it’s vice versa." }, { "code": null, "e": 8006, "s": 7787, "text": "Sometimes we have hypotheses like H0: θ ≤ 0 and Ha: θ > 0. To make sure the models are simple and nested, the null model should be the MLE when θ ≤ 0 while the alternative model should be MLE when θ is any real number." }, { "code": null, "e": 8156, "s": 8006, "text": "Computing MLE by hand is cumbersome and most of the time the MLE does not have closed-form solutions. Luckily, we can harness the power of computers." }, { "code": null, "e": 8586, "s": 8156, "text": "For linear models, statistical packages have built-in functions to compute MLE for GLMs, which cover most of the hypotheses you want to test. (Be careful! In Python, sklearn’s logistic regression function does NOT compute the MLE and will yield incorrect deviances. Use statsmodels instead.) I’d argue that GLM is the most important skill for applied statisticians because so many inferential tasks can be framed as GLM problems." }, { "code": null, "e": 8733, "s": 8586, "text": "For more complicated likelihood functions (e.g. censoring and truncation), you need to write down the function and perform numerical optimization." }, { "code": null, "e": 9017, "s": 8733, "text": "You can abandon dozens of different statistical tests and replace them with the LRT (mostly through GLM), which should be the most powerful test anyway. Learn how to frame questions as the correct regression formulas, choose the most reasonable distribution, and diagnose the models." } ]
Building an Automated Machine Learning Pipeline: Part One | by Ceren Iyim | Towards Data Science
Part 1: Understand, clean, explore, process data (you are reading now) Part 2: Set metric and baseline, select and tune model (live!) Part 3: Train, evaluate and interpret model (live!) Part 4: Automate your pipeline using Docker and Luigi (live!) During my data science learning journey, I learned through reading articles on Towards Data Science as much as I learned from online courses and various coding challenges. Following such diverse sources of learning that come with their own interpretations of machine learning (ML) helped me a lot. Today, I will bring a part of my perspective to the ML applications that I distilled throughout this journey and start an article series. It will hopefully show how to build an automated ML pipeline with a beginner-friendly language and structure. We are going to follow an intuitive ML pipeline to build a predictor to rate wine quality: Understand & Clean & Format DataExploratory Data AnalysisFeature Engineering & Pre-processingSet Evaluation Metric & Establish BaselineSelect an ML Model based on the Evaluation MetricPerform Hyperparameter Tuning on the Selected ModelTrain and Evaluate the ModelInterpret Model PredictionsDraw Conclusions & Document Work Understand & Clean & Format Data Exploratory Data Analysis Feature Engineering & Pre-processing Set Evaluation Metric & Establish Baseline Select an ML Model based on the Evaluation Metric Perform Hyperparameter Tuning on the Selected Model Train and Evaluate the Model Interpret Model Predictions Draw Conclusions & Document Work This first article covers steps 1, 2 and 3. The code behind this article can be found in this notebook. The second and third articles in the series will have covered the entire pipeline. After we build the pipeline, the fourth article will focus on how we can automate the wine rating predictor with Docker and Luigi. This part is especially exciting for me because it introduced me to concepts and tooling that let me understand how an ML solution runs on production systems. Disclaimer: The core structure and utilities in this automation are taken from a coding challenge that I took on recently as part of an ML Engineer interview process at an amazing company called Data Revenue. I did not get the job because they were looking for someone with more emphasis and experience in engineering whereas I’m more on the science part. Ultimately, I wore a software engineer’s hat and learned a lot during the interview process. The complete project is available on GitHub for the impatient: github.com In this project, we are provided with a sample dataset. In a real-world scenario, one can possibly obtain (perhaps scrape) this data from online sources like winemag. The goal of the project is to build a wine rating predictor using a sample dataset to show good prediction is possible, perhaps as a proof of concept for a larger project. We are going to use the results of the wine rating predictor to confirm that ML applications are effective solutions to business problems such as optimizing a wine portfolio for a seller. We should always keep in mind that the “science” in data science serves a purpose, ultimately for a non-scientist. A typical project has some implied base requirements. Our wine rating predictor should be understandable because our audience will likely have limited knowledge of statistics and ML. Furthermore, it should be performant because the complete production dataset could have millions of rows. Finally, it should be automated in a way that it can run on any production system without requiring specialized configurations and setups. The data for this project is available in data_root/raw/wine_dataset in the repository. For now, we will use 90% of it as the training set and the remaining 10% as the test set. They are both available in data_root/interim as train.csv and test.csv . We are going to use Python 3.7 and will need the following libraries in this notebook: In this step, we will get ourselves familiar with the dataset, understand what our dataset conveys and clean it by removing redundant rows and columns. Let’s load the training and test datasets into data frames and have a look at some rows of the training dataset: train = pd.read_csv("../data_root/interim/train.csv") test = pd.read_csv("../data_root/interim/test.csv")train.sample(5) There are some empty rows in the dataset and we have only 2 numeric variables: points and the price. Points is the dependent variable that we are trying to predict, and will be referred to as the target. The rest are the independent variables that can be used in determining the target and will be referred to as features. We are trying to grasp the relationships between independent variables and a dependent variable and use this relationship to generate predictions, which makes the wine rating predictor a supervised regression machine learning model: Supervised: Dataset includes the wine ratings (labelled as points) and independent variables which can be used in determining the points. Regression: Our target variable — points consist of continuous integers ranging from 80 to 100. Most of the column names are self-explanatory if you ever thought about which wine to buy at a supermarket. However, I think it is important to understand how a particular wine receives points and domain-specific features. Points are assigned to a wine by a taster. A wine may receive different points from the same taster. When a taster is assigning points to a wine, s/he also provides a description of the notes and taste about the wine. The designation is the name of the vineyard and region_1 & region_2 features describe the places where the grapes of the wine are grown. Here is how a Barlow 2005 Barrouge Red looks like: Now, let’s have a look at the data types and number of non-empty (non-null) of the training and test dataset: train.info() test.info() This is an interesting dataset because 90% of the features are categorical — variables that are in object Dtype. ML models can only work with numerical data and non-null values. Thus, we are going to develop some strategies in the Feature Engineering & Pre-processing to handle the categorical data and missing values in our model. The function below will enable us to observe the missing values as a percentage per feature. Features that have missing values of more than 50% are not likely to provide significant information to our model. Therefore, region_2 will be dropped from both datasets. In this sample dataset, target value has no missing values. If we would have missing values in the target, we would have dropped all the missing values not to distort the existing distribution of the target. Cardinality is the number of unique values that a categorical feature has. Let’s have a look at it for our training dataset: object_columns = (train .select_dtypes(include="object") .columns)for column in object_columns: print("{} has {} unique values." .format(column, train[column] .nunique())) We can infer that a feature has a high cardinality if it has more than 1000 rows out of 9000: description, designation, title and winery. moderate cardinality if it has more than 100 rows: province, region_1 and variety. low cardinality if it has less than 100 rows: country, region_2, taster_name and taster_twitter_handle. High cardinality features may cause problems when we are training our model. Even though we transform each unique value of a categorical feature to a new feature, they may bring the curse of dimensionality. So, we are going to use the high cardinality features for adding new features, then we are going to remove them from the datasets. Remember that this is a sample dataset. So we cannot guarantee that we have seen all the possible values of each categorical feature when we are training the model. If our wine rating predictor encounters with a new value in the test set, it will throw errors. That is why we are going to revisit this in the Feature Engineering & Pre-processing. Two variables are called collinear if there exists a linear association between them. In case of categorical features, they are called collinear if they are providing the same information to predict a target. Collinear features decrease the generalization performance on the test set and interpretability of the model. Recall that one of the requirements for our wine rating predictor was interpretability. In our sample dataset, taster_name and taster_twitter_handle signals for the collinearity. After making sure that all values of the taster_twitter_handle are covered by the taster_name (not shown here but checked here in the notebook), it is removed to build a good and explicable wine rating predictor. Up until now, we had the first glance of the dataset and detected the features to remove: designation and winery due to the high cardinality region_2 due to having missing values more than 50% taster_twitter_handle due to collinearity Moreover, the training set contains some duplicate rows. In addition to the list above, we are going to drop them and clean the data with the below function: drop_columns = ["designation", "winery", "taster_twitter_handle", "region_2"]train_cleaned = CleanDatat(train, drop_columns, "points")test_cleaned = CleanData(test, drop_columns, "points" Now, we are going to use the train_cleaned.csv and test_cleaned.csv to visualize and explore the features and target further in the Exploratory Data Analysis. Exploratory data analysis (EDA) is the step where we have a detailed look at the variables and visualize the relationships between features and target. In this step, we are going to seek and follow the clues of strong determiners of the target. At the end of this step, we will decide which features to process in the Feature Engineering & Pre-processing. First, we will examine the points (target), numeric features and link between them. Then, we will investigate the low-cardinality features and their relationship to the target. As we find valuable insights, we will elaborate on them through the steps of EDA. Distribution is a description of a variable’s range and how data is spread in that range. We can easily observe a distribution by plotting a histogram: figsize(10, 8)plt.rcParams['font.size'] = 14plot_histogram(train_cleaned, "points") Points show a normal distribution (a bell-shaped curve is obvious in the distribution) as expected from a random variable. Range of the points is distributed between 80 and 100 with a mean of 88.45 and a median of 88. Moreover, standard deviation — a measure of the spread of a data range is 3.03 resulting in a variance of 9.1 as the squared deviation. Based on the normal distribution, we can confidently say that 95% of the points lie in the 82.5–94.5 range. When we plot the histogram of the price it showed a vague picture because it was highly right-skewed (available here in the notebook). To get a reasonable one, we will observe it in the 0–200 range: figsize(10, 8) plt.rcParams['font.size'] = 14plot_histogram(train_cleaned, "price", 200) plt.xlim(0,200) This is still a right-skewed or positively skewed distribution where the right tail is longer and most of the values are concentrated on the left-hand side. Median of the price is 25 and the mean price is 35.5. In order to use price as a predictor, we need to assume that the points received do not cause any price change. Otherwise, this will cause data leakage since we’ll be including a predictor at a later point in time. This could potentially spoil our future predictions of points. Nonetheless, assuming that price is not affected by the points assigned by a taster, it is an indicator of wine’s quality and age. Therefore, we expect it to be an essential feature of the model. To visualize the relationships of several variables, we will use a density plot where we plot the distribution of target per unique values of a categorical feature. A density plot can be interpreted as the continuous and smoothed version of a histogram which conveys the shape of the distribution easily. To keep the plots interpretable, we will plot the distribution of points for the countries with more than 100 occurrences. # make a list of countries that has most occurencescountries = (train_cleaned["country"] .value_counts())freq_countries = list( countries[ countries.values > 300] .index)freq2_countries = list( countries[ (countries.values <= 300) & (countries.values >= 100)] .index) figsize(20, 10)plt.rcParams['font.size'] = 14# plot points distribution for most frequent countriesplt.subplot(1, 2, 1)plot_distribution(train_cleaned, "points", freq_countries, "country")plt.subplot(1, 2, 2)plot_distribution(train_cleaned, "points", freq2_countries, "country") Wine producing market is dominated by the US, France, Italy and Spain which is easily available from the plots. Country is a differentiating feature to determine points of wine. However, there are some exceptions: USA & Portugal or Austria & Germany. Assuming that the price is an essential determiner for the points, we will explore points and price relationship with country. # create dataframe of most frequent countriespoints_freq_countries = train_cleaned[ train_cleaned .country .isin(freq_countries)]figsize(20, 10)plt.rcParams['font.size'] = 14# plot a scatterplot of Points and Priceplt.subplot(1,2,1)sns.scatterplot(x='price', y='points', hue='country', data=points_freq_countries, alpha=0.7)plt.xlabel("Price", size=14)plt.ylabel("Points", size=14)plt.title("Points vs Price for Most Frequent Countries", size=16)# plot a scatterplot of Points and Priceplt.subplot(1,2,2)sns.scatterplot(x='price', y='points', data=train_cleaned, alpha=0.7)plt.xlabel("Price", size=14)plt.ylabel("Points", size=14)plt.title("Points vs Price for all Countries with price range 0-200", size=16)plt.xlim(0,200) The plot on the left-hand side shows the points and price relationship for the wines produced by the dominant countries in the complete price range. The plot on the right-hand side shows the points and price relationship for all countries zoomed in 0 and 200 price range. Both plots show that there is a strong positive correlation exists between the points and price, which serves as proof that price is an important predictor. Another valuable insight is, there are two wines from Italy and one from France that received full points from tasters, all of their prices are greater than 200. Points, represents the score of a particular wine received from a taster. So, a different taster might imply different interpretations of a wine. To investigate this we are going to plot a violin plot. Violin plot ​is my favourite plot that conveys the distribution of the data shape and summary statistics with the violins outside and slim rectangles inside respectively. figsize(14, 8)plt.rcParams['font.size'] = 14f = sns.violinplot(data=train_cleaned, x="taster_name", y="points")f.set_xticklabels(f.get_xticklabels(), rotation=90)plt.title("Points from Different Tasters", size=16) Each taster’s summary statistics and distribution of points are unique resulting in different violins above. Looking at this picture, we expect it to be the second most important predictor of the model. We explored points, price, country and the taster_name and relationships between them. In addition to them, variety, region_1 and province will remain in the final feature list since: variety and region_1 are major elements in differentiating the grapes of the wine so as the wine’s taste and quality province provides location information when combined with country Moreover, we observed a normal distribution in the points and identified its mean and variance, which will be useful for us in the Set Evaluation Metric & Establish Baseline. We expect price and taster_name to be the two most important predictors in determining points. Now, we will move forward with the long-waited and mentioned Feature Engineering & Pre-processing part. Feature engineering is the process of extracting and transforming information from raw features and potentially create a lot more useful features. We are going to take what we’ve learned about our features in the previous parts and encode that information into new ones. Since our features are mostly categorical, we are going to search for numerical or binary features in the description, variety and title. Then, we are going to prepare both datasets to be used as an input for our wine rating predictor. This process is called feature pre-processing. This is a necessary step because ML models can only work with numerical data and non-missing values. Building a good wine rating predictor starts with identifying the most useful features to determine points. At the end of this step, we will identify the most effective feature set, which will provide a good and understandable wine rating predictor in return. We are going to follow feature extraction, categorical feature transformation and missing value filling respectively. description: It contains information about the wine’s colour, taste and notes (like sweet, dry). Taste and colour-related words are searched and extracted from the description with the function below. If a taste or colour-related word exists in the description, the corresponding feature to that word is assigned with a value of 1, otherwise 0. title: It contains the production year of the wine. If year information is not available in the title year is assigned to 0. variety: It contains information about whether different types of grapes are blended. is_blend is assigned to 1 if several grape varieties present, otherwise 0. Now, using those functions above and search keywords below, we are going to add new features. # create search terms for new features # to be extracted from descriptionis_red_list = ["red", "Red", "RED", "noir", "NOIR", "Noir", "black", "BLACK", "Black"]is_white_list = ["white", "WHITE", "White", "blanc", "Blanc", "BLANC", "bianco", "Bianco", "BIANCO", "blanco", "Blanco", "BLANCO", "blanca", "Blanca", "BLANCA"]is_rose_list = ["rose", "ROSE", "Rose", "rosé", "Rosé", "ROSÉ"]is_sparkling_list = ["sparkling", "SPARKLING", "Sparkling"]is_dry_list = ["dry", "Dry", "DRY", "dried", "Dried", "DRIED"]is_sweet_list = ["sweet", "Sweet", "SWEET"]desc_extracting_dict = { "is_red": is_red_list, "is_white": is_white_list, "is_rose": is_rose_list, "is_sparkling": is_sparkling_list, "is_dry": is_dry_list, "is_sweet": is_sweet_list} train_features_added = ExtractFeatures(train_cleaned) test_features_added = ExtractFeatures(test_cleaned) After the feature engineering, we have 14 features in the train_features_added and test_features_added data frames: country, province, region_1, variety, price, year, taster_name, is_red, is_white, is_rose, is_dry, is_sweet, is_sparkling, is_blend. As the first part of feature pre-processing steps, categorical features (country, province, region_1, taster_name and variety) will be turned into the numerical features. We selected the ​ordinal encoding ​approach for the transformation, which is the process of assigning positive integers consecutively starting from 1 to each unique value of a particular feature in the order of appearance. Remember that this is a sample dataset, so we have to consider the possible values that are not present in this sample dataset but may show up in the test dataset. To manage them we are going to use ordinal encoder from the category_encoders library. When we set handle_unknown parameter to the "value", the ordinal_encoder object will assign the first-time seen values of the test set to -1. Then, we run fit method on the training set, ordinal_encoder object maps the values of the given features to the integers. Then, we run transform method on both datasets, the transformation process is completed according to mapping done during fitting and we get full-numeric datasets in return. ordinal_encode_cols = ["country", "province", "region_1", "variety", "taster_name"]data_encoded = EncodeCategoricalData(train_features_added, test_features_added)train_encoded = data_encoded[0]test_encoded = data_encoded[1] As the second part of the feature pre-processing, we will handle missing values. An easy option is to drop them. However, we already have only 8500 data points to train the model. Therefore, we are going to proceed by filling them. ​Process of filling missing values of features is called imputation. We are going to use the following strategies for different features: taster_name: Since we expect taster_name to be one of the most important features, it is imputed with a constant value (0 stands for “Unknown taster”). That way, we can maintain each taster’s effect in determining points. price and year: Imputed with median value since they are numeric columns and the median is not affected by the extreme values. country, province, region_1 and variety: Imputed with most frequent value since they are categorical and the most frequent values of each feature align. Those are US, California, Napa Valley and Pinot Noir respectively. One important consideration during imputing is, whatever imputing strategy is selected, both training and test sets are imputed with the same values. For instance, the median of the price in the training dataset is 25 and this value is assigned to missing values of the training dataset and the test dataset to prevent data leakage into the test set. transformed_data = ImputeMissingValues(train_encoded, test_encoded)train_features = transformed_data[0]train_target = transformed_data[1]test_features = transformed_data[2]test_target = transformed_data[3] Before moving on to the next article and the section, we are going to reserve some part of the training set as a validation set to provide an unbiased evaluation of a model. Training dataset will be used for training the machine learning model. Training a machine learning model is the process of the grasping the patterns between the features and the target by our model, and using them for further predictions. Validation dataset — the held-out part of the training dataset will be used as a measure of how well our model will generalize to a first-time-seen dataset. This measure will be one of the objective selection criteria of the Select an ML Model based on the Evaluation Metric part. I can hear you thinking why don’t we use the test set for model selection then? Because, if we used the test set for this purpose, we would be selecting a biased model that is trained perfectly fit to our test set. Moreover, the model performance would not be representative. The test set will come into the play when we are evaluating our fully-specified model at the Train and Evaluate the Model. In light of the information above, let’s create the validation set by separating 25% of the training set randomly: X_train, X_valid, y_train, y_valid = train_test_split( train_features, train_target, test_size=0.25, random_state=42) Training, validation and test datasets are available under the notebooks/transformed in the repository. They are all ready to be fed into the wine rating predictor! In this article, we completed the first three steps of a machine learning pipeline. After defining the problem and objectives, we Cleaned data by removing redundant and collinear features; and duplicate rowsExplored data to have a detailed understanding of the target, features and their relationshipsAdded more useful features (hopefully!), prepared and transformed both datasets Cleaned data by removing redundant and collinear features; and duplicate rows Explored data to have a detailed understanding of the target, features and their relationships Added more useful features (hopefully!), prepared and transformed both datasets We also completed the crucial step of creating a validation set from the training set. The second article will show how to select an evaluation metric, establish a baseline, select an ML model and tune its hyperparameters by optimizing the selected model’s evaluation metric (steps 4, 5 and 6). towardsdatascience.com The third article will train and evaluate the model with the training and test dataset respectively. It will show how to interpret an ML model’s predictions and draw conclusions (steps 7, 8, and 9). towardsdatascience.com The last article will automate this pipeline with Docker and Luigi. towardsdatascience.com Thanks for reading 😊 now the article series is complete and you can read the next ones! For comments or constructive feedback, you can reach out to me on responses, Twitter or Linkedin! Stay safe and healthy until then 👋
[ { "code": null, "e": 243, "s": 172, "text": "Part 1: Understand, clean, explore, process data (you are reading now)" }, { "code": null, "e": 306, "s": 243, "text": "Part 2: Set metric and baseline, select and tune model (live!)" }, { "code": null, "e": 358, "s": 306, "text": "Part 3: Train, evaluate and interpret model (live!)" }, { "code": null, "e": 420, "s": 358, "text": "Part 4: Automate your pipeline using Docker and Luigi (live!)" }, { "code": null, "e": 966, "s": 420, "text": "During my data science learning journey, I learned through reading articles on Towards Data Science as much as I learned from online courses and various coding challenges. Following such diverse sources of learning that come with their own interpretations of machine learning (ML) helped me a lot. Today, I will bring a part of my perspective to the ML applications that I distilled throughout this journey and start an article series. It will hopefully show how to build an automated ML pipeline with a beginner-friendly language and structure." }, { "code": null, "e": 1057, "s": 966, "text": "We are going to follow an intuitive ML pipeline to build a predictor to rate wine quality:" }, { "code": null, "e": 1380, "s": 1057, "text": "Understand & Clean & Format DataExploratory Data AnalysisFeature Engineering & Pre-processingSet Evaluation Metric & Establish BaselineSelect an ML Model based on the Evaluation MetricPerform Hyperparameter Tuning on the Selected ModelTrain and Evaluate the ModelInterpret Model PredictionsDraw Conclusions & Document Work" }, { "code": null, "e": 1413, "s": 1380, "text": "Understand & Clean & Format Data" }, { "code": null, "e": 1439, "s": 1413, "text": "Exploratory Data Analysis" }, { "code": null, "e": 1476, "s": 1439, "text": "Feature Engineering & Pre-processing" }, { "code": null, "e": 1519, "s": 1476, "text": "Set Evaluation Metric & Establish Baseline" }, { "code": null, "e": 1569, "s": 1519, "text": "Select an ML Model based on the Evaluation Metric" }, { "code": null, "e": 1621, "s": 1569, "text": "Perform Hyperparameter Tuning on the Selected Model" }, { "code": null, "e": 1650, "s": 1621, "text": "Train and Evaluate the Model" }, { "code": null, "e": 1678, "s": 1650, "text": "Interpret Model Predictions" }, { "code": null, "e": 1711, "s": 1678, "text": "Draw Conclusions & Document Work" }, { "code": null, "e": 1898, "s": 1711, "text": "This first article covers steps 1, 2 and 3. The code behind this article can be found in this notebook. The second and third articles in the series will have covered the entire pipeline." }, { "code": null, "e": 2188, "s": 1898, "text": "After we build the pipeline, the fourth article will focus on how we can automate the wine rating predictor with Docker and Luigi. This part is especially exciting for me because it introduced me to concepts and tooling that let me understand how an ML solution runs on production systems." }, { "code": null, "e": 2637, "s": 2188, "text": "Disclaimer: The core structure and utilities in this automation are taken from a coding challenge that I took on recently as part of an ML Engineer interview process at an amazing company called Data Revenue. I did not get the job because they were looking for someone with more emphasis and experience in engineering whereas I’m more on the science part. Ultimately, I wore a software engineer’s hat and learned a lot during the interview process." }, { "code": null, "e": 2700, "s": 2637, "text": "The complete project is available on GitHub for the impatient:" }, { "code": null, "e": 2711, "s": 2700, "text": "github.com" }, { "code": null, "e": 2878, "s": 2711, "text": "In this project, we are provided with a sample dataset. In a real-world scenario, one can possibly obtain (perhaps scrape) this data from online sources like winemag." }, { "code": null, "e": 3050, "s": 2878, "text": "The goal of the project is to build a wine rating predictor using a sample dataset to show good prediction is possible, perhaps as a proof of concept for a larger project." }, { "code": null, "e": 3238, "s": 3050, "text": "We are going to use the results of the wine rating predictor to confirm that ML applications are effective solutions to business problems such as optimizing a wine portfolio for a seller." }, { "code": null, "e": 3407, "s": 3238, "text": "We should always keep in mind that the “science” in data science serves a purpose, ultimately for a non-scientist. A typical project has some implied base requirements." }, { "code": null, "e": 3781, "s": 3407, "text": "Our wine rating predictor should be understandable because our audience will likely have limited knowledge of statistics and ML. Furthermore, it should be performant because the complete production dataset could have millions of rows. Finally, it should be automated in a way that it can run on any production system without requiring specialized configurations and setups." }, { "code": null, "e": 4032, "s": 3781, "text": "The data for this project is available in data_root/raw/wine_dataset in the repository. For now, we will use 90% of it as the training set and the remaining 10% as the test set. They are both available in data_root/interim as train.csv and test.csv ." }, { "code": null, "e": 4119, "s": 4032, "text": "We are going to use Python 3.7 and will need the following libraries in this notebook:" }, { "code": null, "e": 4271, "s": 4119, "text": "In this step, we will get ourselves familiar with the dataset, understand what our dataset conveys and clean it by removing redundant rows and columns." }, { "code": null, "e": 4384, "s": 4271, "text": "Let’s load the training and test datasets into data frames and have a look at some rows of the training dataset:" }, { "code": null, "e": 4505, "s": 4384, "text": "train = pd.read_csv(\"../data_root/interim/train.csv\") test = pd.read_csv(\"../data_root/interim/test.csv\")train.sample(5)" }, { "code": null, "e": 4606, "s": 4505, "text": "There are some empty rows in the dataset and we have only 2 numeric variables: points and the price." }, { "code": null, "e": 4828, "s": 4606, "text": "Points is the dependent variable that we are trying to predict, and will be referred to as the target. The rest are the independent variables that can be used in determining the target and will be referred to as features." }, { "code": null, "e": 5061, "s": 4828, "text": "We are trying to grasp the relationships between independent variables and a dependent variable and use this relationship to generate predictions, which makes the wine rating predictor a supervised regression machine learning model:" }, { "code": null, "e": 5199, "s": 5061, "text": "Supervised: Dataset includes the wine ratings (labelled as points) and independent variables which can be used in determining the points." }, { "code": null, "e": 5295, "s": 5199, "text": "Regression: Our target variable — points consist of continuous integers ranging from 80 to 100." }, { "code": null, "e": 5518, "s": 5295, "text": "Most of the column names are self-explanatory if you ever thought about which wine to buy at a supermarket. However, I think it is important to understand how a particular wine receives points and domain-specific features." }, { "code": null, "e": 5736, "s": 5518, "text": "Points are assigned to a wine by a taster. A wine may receive different points from the same taster. When a taster is assigning points to a wine, s/he also provides a description of the notes and taste about the wine." }, { "code": null, "e": 5924, "s": 5736, "text": "The designation is the name of the vineyard and region_1 & region_2 features describe the places where the grapes of the wine are grown. Here is how a Barlow 2005 Barrouge Red looks like:" }, { "code": null, "e": 6034, "s": 5924, "text": "Now, let’s have a look at the data types and number of non-empty (non-null) of the training and test dataset:" }, { "code": null, "e": 6047, "s": 6034, "text": "train.info()" }, { "code": null, "e": 6059, "s": 6047, "text": "test.info()" }, { "code": null, "e": 6391, "s": 6059, "text": "This is an interesting dataset because 90% of the features are categorical — variables that are in object Dtype. ML models can only work with numerical data and non-null values. Thus, we are going to develop some strategies in the Feature Engineering & Pre-processing to handle the categorical data and missing values in our model." }, { "code": null, "e": 6484, "s": 6391, "text": "The function below will enable us to observe the missing values as a percentage per feature." }, { "code": null, "e": 6655, "s": 6484, "text": "Features that have missing values of more than 50% are not likely to provide significant information to our model. Therefore, region_2 will be dropped from both datasets." }, { "code": null, "e": 6863, "s": 6655, "text": "In this sample dataset, target value has no missing values. If we would have missing values in the target, we would have dropped all the missing values not to distort the existing distribution of the target." }, { "code": null, "e": 6988, "s": 6863, "text": "Cardinality is the number of unique values that a categorical feature has. Let’s have a look at it for our training dataset:" }, { "code": null, "e": 7241, "s": 6988, "text": "object_columns = (train .select_dtypes(include=\"object\") .columns)for column in object_columns: print(\"{} has {} unique values.\" .format(column, train[column] .nunique()))" }, { "code": null, "e": 7275, "s": 7241, "text": "We can infer that a feature has a" }, { "code": null, "e": 7379, "s": 7275, "text": "high cardinality if it has more than 1000 rows out of 9000: description, designation, title and winery." }, { "code": null, "e": 7462, "s": 7379, "text": "moderate cardinality if it has more than 100 rows: province, region_1 and variety." }, { "code": null, "e": 7566, "s": 7462, "text": "low cardinality if it has less than 100 rows: country, region_2, taster_name and taster_twitter_handle." }, { "code": null, "e": 7904, "s": 7566, "text": "High cardinality features may cause problems when we are training our model. Even though we transform each unique value of a categorical feature to a new feature, they may bring the curse of dimensionality. So, we are going to use the high cardinality features for adding new features, then we are going to remove them from the datasets." }, { "code": null, "e": 8251, "s": 7904, "text": "Remember that this is a sample dataset. So we cannot guarantee that we have seen all the possible values of each categorical feature when we are training the model. If our wine rating predictor encounters with a new value in the test set, it will throw errors. That is why we are going to revisit this in the Feature Engineering & Pre-processing." }, { "code": null, "e": 8460, "s": 8251, "text": "Two variables are called collinear if there exists a linear association between them. In case of categorical features, they are called collinear if they are providing the same information to predict a target." }, { "code": null, "e": 8658, "s": 8460, "text": "Collinear features decrease the generalization performance on the test set and interpretability of the model. Recall that one of the requirements for our wine rating predictor was interpretability." }, { "code": null, "e": 8962, "s": 8658, "text": "In our sample dataset, taster_name and taster_twitter_handle signals for the collinearity. After making sure that all values of the taster_twitter_handle are covered by the taster_name (not shown here but checked here in the notebook), it is removed to build a good and explicable wine rating predictor." }, { "code": null, "e": 9052, "s": 8962, "text": "Up until now, we had the first glance of the dataset and detected the features to remove:" }, { "code": null, "e": 9103, "s": 9052, "text": "designation and winery due to the high cardinality" }, { "code": null, "e": 9155, "s": 9103, "text": "region_2 due to having missing values more than 50%" }, { "code": null, "e": 9197, "s": 9155, "text": "taster_twitter_handle due to collinearity" }, { "code": null, "e": 9355, "s": 9197, "text": "Moreover, the training set contains some duplicate rows. In addition to the list above, we are going to drop them and clean the data with the below function:" }, { "code": null, "e": 9543, "s": 9355, "text": "drop_columns = [\"designation\", \"winery\", \"taster_twitter_handle\", \"region_2\"]train_cleaned = CleanDatat(train, drop_columns, \"points\")test_cleaned = CleanData(test, drop_columns, \"points\"" }, { "code": null, "e": 9702, "s": 9543, "text": "Now, we are going to use the train_cleaned.csv and test_cleaned.csv to visualize and explore the features and target further in the Exploratory Data Analysis." }, { "code": null, "e": 10058, "s": 9702, "text": "Exploratory data analysis (EDA) is the step where we have a detailed look at the variables and visualize the relationships between features and target. In this step, we are going to seek and follow the clues of strong determiners of the target. At the end of this step, we will decide which features to process in the Feature Engineering & Pre-processing." }, { "code": null, "e": 10317, "s": 10058, "text": "First, we will examine the points (target), numeric features and link between them. Then, we will investigate the low-cardinality features and their relationship to the target. As we find valuable insights, we will elaborate on them through the steps of EDA." }, { "code": null, "e": 10469, "s": 10317, "text": "Distribution is a description of a variable’s range and how data is spread in that range. We can easily observe a distribution by plotting a histogram:" }, { "code": null, "e": 10553, "s": 10469, "text": "figsize(10, 8)plt.rcParams['font.size'] = 14plot_histogram(train_cleaned, \"points\")" }, { "code": null, "e": 11015, "s": 10553, "text": "Points show a normal distribution (a bell-shaped curve is obvious in the distribution) as expected from a random variable. Range of the points is distributed between 80 and 100 with a mean of 88.45 and a median of 88. Moreover, standard deviation — a measure of the spread of a data range is 3.03 resulting in a variance of 9.1 as the squared deviation. Based on the normal distribution, we can confidently say that 95% of the points lie in the 82.5–94.5 range." }, { "code": null, "e": 11214, "s": 11015, "text": "When we plot the histogram of the price it showed a vague picture because it was highly right-skewed (available here in the notebook). To get a reasonable one, we will observe it in the 0–200 range:" }, { "code": null, "e": 11319, "s": 11214, "text": "figsize(10, 8) plt.rcParams['font.size'] = 14plot_histogram(train_cleaned, \"price\", 200) plt.xlim(0,200)" }, { "code": null, "e": 11530, "s": 11319, "text": "This is still a right-skewed or positively skewed distribution where the right tail is longer and most of the values are concentrated on the left-hand side. Median of the price is 25 and the mean price is 35.5." }, { "code": null, "e": 11808, "s": 11530, "text": "In order to use price as a predictor, we need to assume that the points received do not cause any price change. Otherwise, this will cause data leakage since we’ll be including a predictor at a later point in time. This could potentially spoil our future predictions of points." }, { "code": null, "e": 12004, "s": 11808, "text": "Nonetheless, assuming that price is not affected by the points assigned by a taster, it is an indicator of wine’s quality and age. Therefore, we expect it to be an essential feature of the model." }, { "code": null, "e": 12309, "s": 12004, "text": "To visualize the relationships of several variables, we will use a density plot where we plot the distribution of target per unique values of a categorical feature. A density plot can be interpreted as the continuous and smoothed version of a histogram which conveys the shape of the distribution easily." }, { "code": null, "e": 12432, "s": 12309, "text": "To keep the plots interpretable, we will plot the distribution of points for the countries with more than 100 occurrences." }, { "code": null, "e": 12745, "s": 12432, "text": "# make a list of countries that has most occurencescountries = (train_cleaned[\"country\"] .value_counts())freq_countries = list( countries[ countries.values > 300] .index)freq2_countries = list( countries[ (countries.values <= 300) & (countries.values >= 100)] .index)" }, { "code": null, "e": 13058, "s": 12745, "text": "figsize(20, 10)plt.rcParams['font.size'] = 14# plot points distribution for most frequent countriesplt.subplot(1, 2, 1)plot_distribution(train_cleaned, \"points\", freq_countries, \"country\")plt.subplot(1, 2, 2)plot_distribution(train_cleaned, \"points\", freq2_countries, \"country\")" }, { "code": null, "e": 13309, "s": 13058, "text": "Wine producing market is dominated by the US, France, Italy and Spain which is easily available from the plots. Country is a differentiating feature to determine points of wine. However, there are some exceptions: USA & Portugal or Austria & Germany." }, { "code": null, "e": 13436, "s": 13309, "text": "Assuming that the price is an essential determiner for the points, we will explore points and price relationship with country." }, { "code": null, "e": 14256, "s": 13436, "text": "# create dataframe of most frequent countriespoints_freq_countries = train_cleaned[ train_cleaned .country .isin(freq_countries)]figsize(20, 10)plt.rcParams['font.size'] = 14# plot a scatterplot of Points and Priceplt.subplot(1,2,1)sns.scatterplot(x='price', y='points', hue='country', data=points_freq_countries, alpha=0.7)plt.xlabel(\"Price\", size=14)plt.ylabel(\"Points\", size=14)plt.title(\"Points vs Price for Most Frequent Countries\", size=16)# plot a scatterplot of Points and Priceplt.subplot(1,2,2)sns.scatterplot(x='price', y='points', data=train_cleaned, alpha=0.7)plt.xlabel(\"Price\", size=14)plt.ylabel(\"Points\", size=14)plt.title(\"Points vs Price for all Countries with price range 0-200\", size=16)plt.xlim(0,200)" }, { "code": null, "e": 14528, "s": 14256, "text": "The plot on the left-hand side shows the points and price relationship for the wines produced by the dominant countries in the complete price range. The plot on the right-hand side shows the points and price relationship for all countries zoomed in 0 and 200 price range." }, { "code": null, "e": 14847, "s": 14528, "text": "Both plots show that there is a strong positive correlation exists between the points and price, which serves as proof that price is an important predictor. Another valuable insight is, there are two wines from Italy and one from France that received full points from tasters, all of their prices are greater than 200." }, { "code": null, "e": 15049, "s": 14847, "text": "Points, represents the score of a particular wine received from a taster. So, a different taster might imply different interpretations of a wine. To investigate this we are going to plot a violin plot." }, { "code": null, "e": 15220, "s": 15049, "text": "Violin plot ​is my favourite plot that conveys the distribution of the data shape and summary statistics with the violins outside and slim rectangles inside respectively." }, { "code": null, "e": 15496, "s": 15220, "text": "figsize(14, 8)plt.rcParams['font.size'] = 14f = sns.violinplot(data=train_cleaned, x=\"taster_name\", y=\"points\")f.set_xticklabels(f.get_xticklabels(), rotation=90)plt.title(\"Points from Different Tasters\", size=16)" }, { "code": null, "e": 15699, "s": 15496, "text": "Each taster’s summary statistics and distribution of points are unique resulting in different violins above. Looking at this picture, we expect it to be the second most important predictor of the model." }, { "code": null, "e": 15883, "s": 15699, "text": "We explored points, price, country and the taster_name and relationships between them. In addition to them, variety, region_1 and province will remain in the final feature list since:" }, { "code": null, "e": 16000, "s": 15883, "text": "variety and region_1 are major elements in differentiating the grapes of the wine so as the wine’s taste and quality" }, { "code": null, "e": 16066, "s": 16000, "text": "province provides location information when combined with country" }, { "code": null, "e": 16336, "s": 16066, "text": "Moreover, we observed a normal distribution in the points and identified its mean and variance, which will be useful for us in the Set Evaluation Metric & Establish Baseline. We expect price and taster_name to be the two most important predictors in determining points." }, { "code": null, "e": 16440, "s": 16336, "text": "Now, we will move forward with the long-waited and mentioned Feature Engineering & Pre-processing part." }, { "code": null, "e": 16849, "s": 16440, "text": "Feature engineering is the process of extracting and transforming information from raw features and potentially create a lot more useful features. We are going to take what we’ve learned about our features in the previous parts and encode that information into new ones. Since our features are mostly categorical, we are going to search for numerical or binary features in the description, variety and title." }, { "code": null, "e": 17095, "s": 16849, "text": "Then, we are going to prepare both datasets to be used as an input for our wine rating predictor. This process is called feature pre-processing. This is a necessary step because ML models can only work with numerical data and non-missing values." }, { "code": null, "e": 17473, "s": 17095, "text": "Building a good wine rating predictor starts with identifying the most useful features to determine points. At the end of this step, we will identify the most effective feature set, which will provide a good and understandable wine rating predictor in return. We are going to follow feature extraction, categorical feature transformation and missing value filling respectively." }, { "code": null, "e": 17818, "s": 17473, "text": "description: It contains information about the wine’s colour, taste and notes (like sweet, dry). Taste and colour-related words are searched and extracted from the description with the function below. If a taste or colour-related word exists in the description, the corresponding feature to that word is assigned with a value of 1, otherwise 0." }, { "code": null, "e": 17943, "s": 17818, "text": "title: It contains the production year of the wine. If year information is not available in the title year is assigned to 0." }, { "code": null, "e": 18104, "s": 17943, "text": "variety: It contains information about whether different types of grapes are blended. is_blend is assigned to 1 if several grape varieties present, otherwise 0." }, { "code": null, "e": 18198, "s": 18104, "text": "Now, using those functions above and search keywords below, we are going to add new features." }, { "code": null, "e": 19071, "s": 18198, "text": "# create search terms for new features # to be extracted from descriptionis_red_list = [\"red\", \"Red\", \"RED\", \"noir\", \"NOIR\", \"Noir\", \"black\", \"BLACK\", \"Black\"]is_white_list = [\"white\", \"WHITE\", \"White\", \"blanc\", \"Blanc\", \"BLANC\", \"bianco\", \"Bianco\", \"BIANCO\", \"blanco\", \"Blanco\", \"BLANCO\", \"blanca\", \"Blanca\", \"BLANCA\"]is_rose_list = [\"rose\", \"ROSE\", \"Rose\", \"rosé\", \"Rosé\", \"ROSÉ\"]is_sparkling_list = [\"sparkling\", \"SPARKLING\", \"Sparkling\"]is_dry_list = [\"dry\", \"Dry\", \"DRY\", \"dried\", \"Dried\", \"DRIED\"]is_sweet_list = [\"sweet\", \"Sweet\", \"SWEET\"]desc_extracting_dict = { \"is_red\": is_red_list, \"is_white\": is_white_list, \"is_rose\": is_rose_list, \"is_sparkling\": is_sparkling_list, \"is_dry\": is_dry_list, \"is_sweet\": is_sweet_list}" }, { "code": null, "e": 19177, "s": 19071, "text": "train_features_added = ExtractFeatures(train_cleaned) test_features_added = ExtractFeatures(test_cleaned)" }, { "code": null, "e": 19426, "s": 19177, "text": "After the feature engineering, we have 14 features in the train_features_added and test_features_added data frames: country, province, region_1, variety, price, year, taster_name, is_red, is_white, is_rose, is_dry, is_sweet, is_sparkling, is_blend." }, { "code": null, "e": 19820, "s": 19426, "text": "As the first part of feature pre-processing steps, categorical features (country, province, region_1, taster_name and variety) will be turned into the numerical features. We selected the ​ordinal encoding ​approach for the transformation, which is the process of assigning positive integers consecutively starting from 1 to each unique value of a particular feature in the order of appearance." }, { "code": null, "e": 20071, "s": 19820, "text": "Remember that this is a sample dataset, so we have to consider the possible values that are not present in this sample dataset but may show up in the test dataset. To manage them we are going to use ordinal encoder from the category_encoders library." }, { "code": null, "e": 20509, "s": 20071, "text": "When we set handle_unknown parameter to the \"value\", the ordinal_encoder object will assign the first-time seen values of the test set to -1. Then, we run fit method on the training set, ordinal_encoder object maps the values of the given features to the integers. Then, we run transform method on both datasets, the transformation process is completed according to mapping done during fitting and we get full-numeric datasets in return." }, { "code": null, "e": 20770, "s": 20509, "text": "ordinal_encode_cols = [\"country\", \"province\", \"region_1\", \"variety\", \"taster_name\"]data_encoded = EncodeCategoricalData(train_features_added, test_features_added)train_encoded = data_encoded[0]test_encoded = data_encoded[1]" }, { "code": null, "e": 21140, "s": 20770, "text": "As the second part of the feature pre-processing, we will handle missing values. An easy option is to drop them. However, we already have only 8500 data points to train the model. Therefore, we are going to proceed by filling them. ​Process of filling missing values of features is called imputation. We are going to use the following strategies for different features:" }, { "code": null, "e": 21362, "s": 21140, "text": "taster_name: Since we expect taster_name to be one of the most important features, it is imputed with a constant value (0 stands for “Unknown taster”). That way, we can maintain each taster’s effect in determining points." }, { "code": null, "e": 21489, "s": 21362, "text": "price and year: Imputed with median value since they are numeric columns and the median is not affected by the extreme values." }, { "code": null, "e": 21709, "s": 21489, "text": "country, province, region_1 and variety: Imputed with most frequent value since they are categorical and the most frequent values of each feature align. Those are US, California, Napa Valley and Pinot Noir respectively." }, { "code": null, "e": 22060, "s": 21709, "text": "One important consideration during imputing is, whatever imputing strategy is selected, both training and test sets are imputed with the same values. For instance, the median of the price in the training dataset is 25 and this value is assigned to missing values of the training dataset and the test dataset to prevent data leakage into the test set." }, { "code": null, "e": 22266, "s": 22060, "text": "transformed_data = ImputeMissingValues(train_encoded, test_encoded)train_features = transformed_data[0]train_target = transformed_data[1]test_features = transformed_data[2]test_target = transformed_data[3]" }, { "code": null, "e": 22440, "s": 22266, "text": "Before moving on to the next article and the section, we are going to reserve some part of the training set as a validation set to provide an unbiased evaluation of a model." }, { "code": null, "e": 22679, "s": 22440, "text": "Training dataset will be used for training the machine learning model. Training a machine learning model is the process of the grasping the patterns between the features and the target by our model, and using them for further predictions." }, { "code": null, "e": 22960, "s": 22679, "text": "Validation dataset — the held-out part of the training dataset will be used as a measure of how well our model will generalize to a first-time-seen dataset. This measure will be one of the objective selection criteria of the Select an ML Model based on the Evaluation Metric part." }, { "code": null, "e": 23236, "s": 22960, "text": "I can hear you thinking why don’t we use the test set for model selection then? Because, if we used the test set for this purpose, we would be selecting a biased model that is trained perfectly fit to our test set. Moreover, the model performance would not be representative." }, { "code": null, "e": 23359, "s": 23236, "text": "The test set will come into the play when we are evaluating our fully-specified model at the Train and Evaluate the Model." }, { "code": null, "e": 23474, "s": 23359, "text": "In light of the information above, let’s create the validation set by separating 25% of the training set randomly:" }, { "code": null, "e": 23607, "s": 23474, "text": "X_train, X_valid, y_train, y_valid = train_test_split( train_features, train_target, test_size=0.25, random_state=42)" }, { "code": null, "e": 23772, "s": 23607, "text": "Training, validation and test datasets are available under the notebooks/transformed in the repository. They are all ready to be fed into the wine rating predictor!" }, { "code": null, "e": 23902, "s": 23772, "text": "In this article, we completed the first three steps of a machine learning pipeline. After defining the problem and objectives, we" }, { "code": null, "e": 24153, "s": 23902, "text": "Cleaned data by removing redundant and collinear features; and duplicate rowsExplored data to have a detailed understanding of the target, features and their relationshipsAdded more useful features (hopefully!), prepared and transformed both datasets" }, { "code": null, "e": 24231, "s": 24153, "text": "Cleaned data by removing redundant and collinear features; and duplicate rows" }, { "code": null, "e": 24326, "s": 24231, "text": "Explored data to have a detailed understanding of the target, features and their relationships" }, { "code": null, "e": 24406, "s": 24326, "text": "Added more useful features (hopefully!), prepared and transformed both datasets" }, { "code": null, "e": 24493, "s": 24406, "text": "We also completed the crucial step of creating a validation set from the training set." }, { "code": null, "e": 24701, "s": 24493, "text": "The second article will show how to select an evaluation metric, establish a baseline, select an ML model and tune its hyperparameters by optimizing the selected model’s evaluation metric (steps 4, 5 and 6)." }, { "code": null, "e": 24724, "s": 24701, "text": "towardsdatascience.com" }, { "code": null, "e": 24923, "s": 24724, "text": "The third article will train and evaluate the model with the training and test dataset respectively. It will show how to interpret an ML model’s predictions and draw conclusions (steps 7, 8, and 9)." }, { "code": null, "e": 24946, "s": 24923, "text": "towardsdatascience.com" }, { "code": null, "e": 25014, "s": 24946, "text": "The last article will automate this pipeline with Docker and Luigi." }, { "code": null, "e": 25037, "s": 25014, "text": "towardsdatascience.com" }, { "code": null, "e": 25125, "s": 25037, "text": "Thanks for reading 😊 now the article series is complete and you can read the next ones!" }, { "code": null, "e": 25223, "s": 25125, "text": "For comments or constructive feedback, you can reach out to me on responses, Twitter or Linkedin!" } ]
Redis - Connections
Redis connection commands are basically used to manage client connections with Redis server. Following example explains how a client authenticates itself to Redis server and checks whether the server is running or not. redis 127.0.0.1:6379> AUTH "password" OK redis 127.0.0.1:6379> PING PONG Following table lists some basic commands related to Redis connections. Authenticates to the server with the given password Prints the given string Checks whether the server is running or not Closes the current connection Changes the selected database for the current connection 22 Lectures 40 mins Skillbakerystudios Print Add Notes Bookmark this page
[ { "code": null, "e": 2138, "s": 2045, "text": "Redis connection commands are basically used to manage client connections with Redis server." }, { "code": null, "e": 2264, "s": 2138, "text": "Following example explains how a client authenticates itself to Redis server and checks whether the server is running or not." }, { "code": null, "e": 2342, "s": 2264, "text": "redis 127.0.0.1:6379> AUTH \"password\" \nOK \nredis 127.0.0.1:6379> PING \nPONG \n" }, { "code": null, "e": 2414, "s": 2342, "text": "Following table lists some basic commands related to Redis connections." }, { "code": null, "e": 2466, "s": 2414, "text": "Authenticates to the server with the given password" }, { "code": null, "e": 2490, "s": 2466, "text": "Prints the given string" }, { "code": null, "e": 2534, "s": 2490, "text": "Checks whether the server is running or not" }, { "code": null, "e": 2564, "s": 2534, "text": "Closes the current connection" }, { "code": null, "e": 2621, "s": 2564, "text": "Changes the selected database for the current connection" }, { "code": null, "e": 2653, "s": 2621, "text": "\n 22 Lectures \n 40 mins\n" }, { "code": null, "e": 2673, "s": 2653, "text": " Skillbakerystudios" }, { "code": null, "e": 2680, "s": 2673, "text": " Print" }, { "code": null, "e": 2691, "s": 2680, "text": " Add Notes" } ]
How to get the port number of the processes using PowerShell?
When we use Get-Process cmdlet in PowerShell, it doesn’t have properties to get Port number the processes use. So here we will write a function that will provide us the ports number associated with the processes. There is one windows command NETSTAT which provides the Port number and the associated process ID but doesn’t provide the process name. We have Get-Process command which provides the process name and the PID (Process ID) so we can write a program that can associate both the commands and we can retrieve the process ID, local address, remote address, and if the state of the port like LISTENING, ESTABLISHED, etc. Let look at how the NETSTAT command looks like. PS C:\WINDOWS\system32> netstat Active Connections Proto Local Address Foreign Address State TCP 127.0.0.1:9012 DESKTOP-9435KM9:56668 ESTABLISHED TCP 127.0.0.1:29885 DESKTOP-9435KM9:56733 ESTABLISHED TCP 127.0.0.1:49676 DESKTOP-9435KM9:58748 ESTABLISHED TCP 127.0.0.1:49676 DESKTOP-9435KM9:58755 ESTABLISHED TCP 127.0.0.1:49676 DESKTOP-9435KM9:58766 ESTABLISHED TCP 127.0.0.1:49676 DESKTOP-9435KM9:58772 ESTABLISHED TCP 127.0.0.1:49676 DESKTOP-9435KM9:58780 ESTABLISHED TCP 127.0.0.1:49676 DESKTOP-9435KM9:58782 ESTABLISHED TCP 127.0.0.1:49676 DESKTOP-9435KM9:58788 ESTABLISHED TCP 127.0.0.1:49676 DESKTOP-9435KM9:58797 ESTABLISHED TCP 127.0.0.1:49676 DESKTOP-9435KM9:58799 ESTABLISHED TCP 127.0.0.1:49676 DESKTOP-9435KM9:58801 ESTABLISHED TCP 127.0.0.1:49676 DESKTOP-9435KM9:58810 ESTABLISHED TCP 127.0.0.1:49676 DESKTOP-9435KM9:58815 ESTABLISHED TCP 127.0.0.1:49676 DESKTOP-9435KM9:58833 ESTABLISHED TCP 127.0.0.1:49676 DESKTOP-9435KM9:58835 ESTABLISHED TCP 127.0.0.1:49676 DESKTOP-9435KM9:58836 ESTABLISHED TCP 127.0.0.1:49676 DESKTOP-9435KM9:58837 ESTABLISHED TCP 127.0.0.1:49676 DESKTOP-9435KM9:58838 ESTABLISHED TCP 127.0.0.1:49676 DESKTOP-9435KM9:58843 ESTABLISHED TCP 127.0.0.1:49676 DESKTOP-9435KM9:58845 ESTABLISHED In the above command, we need to get the port numbers, local address, and remote address, so we will use NETSTAT –ano command. To get more information about this command, check the link below. https://www.ionos.com/digitalguide/server/tools/introduction-to-netstat/ The output of this command would be − PS C:\WINDOWS\system32> netstat -ano Active Connections Proto Local Address Foreign Address State PID TCP 0.0.0.0:135 0.0.0.0:0 LISTENING 1208 TCP 0.0.0.0:445 0.0.0.0:0 LISTENING 4 TCP 0.0.0.0:2869 0.0.0.0:0 LISTENING 4 TCP 0.0.0.0:5040 0.0.0.0:0 LISTENING 7864 TCP 0.0.0.0:5700 0.0.0.0:0 LISTENING 4 TCP 0.0.0.0:16861 0.0.0.0:0 LISTENING 26860 TCP 0.0.0.0:49664 0.0.0.0:0 LISTENING 760 TCP 0.0.0.0:49665 0.0.0.0:0 LISTENING 912 TCP 0.0.0.0:49666 0.0.0.0:0 LISTENING 1704 TCP 0.0.0.0:49667 0.0.0.0:0 LISTENING 2976 TCP 0.0.0.0:49668 0.0.0.0:0 LISTENING 3868 TCP 0.0.0.0:49669 0.0.0.0:0 LISTENING 3996 TCP 0.0.0.0:49670 0.0.0.0:0 LISTENING 720 TCP 127.0.0.1:515 0.0.0.0:0 LISTENING 9276 TCP 127.0.0.1:1001 0.0.0.0:0 LISTENING 4 TCP 127.0.0.1:8884 0.0.0.0:0 LISTENING 4 TCP 127.0.0.1:9012 0.0.0.0:0 LISTENING 15532 TCP 127.0.0.1:9012 127.0.0.1:56668 ESTABLISHED 15532 TCP 127.0.0.1:29885 0.0.0.0:0 LISTENING 26860 We got Process ID (PID) in this table and we can retrieve the processes with PID with Get-Process command and write a program for it which can correlate both. function Get-ProcessPorts{ [cmdletbinding()] Param( [parameter(Mandatory=$True, ValueFromPipeLine=$True)] [AllowEmptyCollection()] [string[]]$ProcessName ) Begin{ Write-Verbose "Declaring empty array to store the output" $portout = @() } Process{ Write-Verbose "Processes to get the port information" $processes = Get-Process $ProcessName foreach($proc in $processes){ # Get the port for the process. $mports = Netstat -ano | findstr $proc.ID # Separate each instance foreach($sport in $mports) # Split the netstat output and remove empty lines from the output. $out = $sport.Split('') | where{$_ -ne ""} $LCount = $out[1].LastIndexOf(':') $RCount = $out[2].LastIndexOf(':') $portout += [PSCustomObject]@{ 'Process' = $proc.Name 'PID' = $proc.ID 'Protocol' = $out[0] 'LocalAddress' = $out[1].SubString(0,$LCount) 'LocalPort' = $out[1].SubString($Lcount+1,($out[1].Length-$Lcount-1)) 'RemoteAddress' = $out[2].SubString(0,$RCount) 'RemotePort' = $out[2].SubString($RCount+1,($out[2].Length-$Rcount-1)) 'Connection' = $( # Checking if the connection contains any empty string. if(!($out[3] -match '\d')){$out[3]} ) } } } $portout | ft -AutoSize } End{ Write-Verbose "End of the program" } } Output − Process PID Protocol LocalAddress LocalPort RemoteAddress RemotePort Connection ------- --- -------- ------------ --------- ------------- ---------- ---------- avp 4252 TCP 127.0.0.1 49676 0.0.0.0 0 LISTENING avp 4252 TCP 127.0.0.1 49676 127.0.0.1 50304 ESTABLISHED avp 4252 TCP 127.0.0.1 49676 127.0.0.1 50338 ESTABLISHED avp 4252 TCP 127.0.0.1 49676 127.0.0.1 50347 ESTABLISHED avp 4252 TCP 127.0.0.1 49676 127.0.0.1 50357 ESTABLISHED avp 4252 TCP 127.0.0.1 49676 127.0.0.1 50366 ESTABLISHED avp 4252 TCP 127.0.0.1 49676 127.0.0.1 50370 ESTABLISHED avp 4252 TCP 127.0.0.1 49676 127.0.0.1 50375 ESTABLISHED avp 4252 TCP 127.0.0.1 49676 127.0.0.1 50376 ESTABLISHED avp 4252 TCP 127.0.0.1 49676 127.0.0.1 50377 ESTABLISHED avp 4252 TCP 127.0.0.1 49676 127.0.0.1 50378 ESTABLISHED avp 4252 TCP 127.0.0.1 49676 127.0.0.1 50379 ESTABLISHED avp 4252 TCP 127.0.0.1 49676 127.0.0.1 50380 ESTABLISHED avp 4252 TCP 127.0.0.1 49676 127.0.0.1 50385 ESTABLISHED avp 4252 TCP 127.0.0.1 49676 127.0.0.1 50387 ESTABLISHED WINWORD 25852 TCP 192.168.0.107 53584 99.83.135.170 443 ESTABLISHED WINWORD 25852 TCP 192.168.0.107 53592 99.83.135.170 443 ESTABLISHED VERBOSE: End of the program
[ { "code": null, "e": 1275, "s": 1062, "text": "When we use Get-Process cmdlet in PowerShell, it doesn’t have properties to get Port number the processes use. So here we will write a function that will provide us the ports number associated with the processes." }, { "code": null, "e": 1689, "s": 1275, "text": "There is one windows command NETSTAT which provides the Port number and the associated process ID but doesn’t provide the process name. We have Get-Process command which provides the process name and the PID (Process ID) so we can write a program that can associate both the commands and we can retrieve the process ID, local address, remote address, and if the state of the port like LISTENING, ESTABLISHED, etc." }, { "code": null, "e": 1737, "s": 1689, "text": "Let look at how the NETSTAT command looks like." }, { "code": null, "e": 3315, "s": 1737, "text": "PS C:\\WINDOWS\\system32> netstat \n\nActive Connections\n Proto Local Address Foreign Address State\n TCP 127.0.0.1:9012 DESKTOP-9435KM9:56668 ESTABLISHED\n TCP 127.0.0.1:29885 DESKTOP-9435KM9:56733 ESTABLISHED\n TCP 127.0.0.1:49676 DESKTOP-9435KM9:58748 ESTABLISHED\n TCP 127.0.0.1:49676 DESKTOP-9435KM9:58755 ESTABLISHED\n TCP 127.0.0.1:49676 DESKTOP-9435KM9:58766 ESTABLISHED\n TCP 127.0.0.1:49676 DESKTOP-9435KM9:58772 ESTABLISHED\n TCP 127.0.0.1:49676 DESKTOP-9435KM9:58780 ESTABLISHED\n TCP 127.0.0.1:49676 DESKTOP-9435KM9:58782 ESTABLISHED\n TCP 127.0.0.1:49676 DESKTOP-9435KM9:58788 ESTABLISHED\n TCP 127.0.0.1:49676 DESKTOP-9435KM9:58797 ESTABLISHED\n TCP 127.0.0.1:49676 DESKTOP-9435KM9:58799 ESTABLISHED\n TCP 127.0.0.1:49676 DESKTOP-9435KM9:58801 ESTABLISHED\n TCP 127.0.0.1:49676 DESKTOP-9435KM9:58810 ESTABLISHED\n TCP 127.0.0.1:49676 DESKTOP-9435KM9:58815 ESTABLISHED\n TCP 127.0.0.1:49676 DESKTOP-9435KM9:58833 ESTABLISHED\n TCP 127.0.0.1:49676 DESKTOP-9435KM9:58835 ESTABLISHED\n TCP 127.0.0.1:49676 DESKTOP-9435KM9:58836 ESTABLISHED\n TCP 127.0.0.1:49676 DESKTOP-9435KM9:58837 ESTABLISHED\n TCP 127.0.0.1:49676 DESKTOP-9435KM9:58838 ESTABLISHED\n TCP 127.0.0.1:49676 DESKTOP-9435KM9:58843 ESTABLISHED\n TCP 127.0.0.1:49676 DESKTOP-9435KM9:58845 ESTABLISHED" }, { "code": null, "e": 3508, "s": 3315, "text": "In the above command, we need to get the port numbers, local address, and remote address, so we will use NETSTAT –ano command. To get more information about this command, check the link below." }, { "code": null, "e": 3581, "s": 3508, "text": "https://www.ionos.com/digitalguide/server/tools/introduction-to-netstat/" }, { "code": null, "e": 3619, "s": 3581, "text": "The output of this command would be −" }, { "code": null, "e": 5231, "s": 3619, "text": "PS C:\\WINDOWS\\system32> netstat -ano\n \nActive Connections\n\n Proto Local Address Foreign Address State PID\n TCP 0.0.0.0:135 0.0.0.0:0 LISTENING 1208\n TCP 0.0.0.0:445 0.0.0.0:0 LISTENING 4\n TCP 0.0.0.0:2869 0.0.0.0:0 LISTENING 4\n TCP 0.0.0.0:5040 0.0.0.0:0 LISTENING 7864\n TCP 0.0.0.0:5700 0.0.0.0:0 LISTENING 4\n TCP 0.0.0.0:16861 0.0.0.0:0 LISTENING 26860\n TCP 0.0.0.0:49664 0.0.0.0:0 LISTENING 760\n TCP 0.0.0.0:49665 0.0.0.0:0 LISTENING 912\n TCP 0.0.0.0:49666 0.0.0.0:0 LISTENING 1704\n TCP 0.0.0.0:49667 0.0.0.0:0 LISTENING 2976\n TCP 0.0.0.0:49668 0.0.0.0:0 LISTENING 3868\n TCP 0.0.0.0:49669 0.0.0.0:0 LISTENING 3996\n TCP 0.0.0.0:49670 0.0.0.0:0 LISTENING 720\n TCP 127.0.0.1:515 0.0.0.0:0 LISTENING 9276\n TCP 127.0.0.1:1001 0.0.0.0:0 LISTENING 4\n TCP 127.0.0.1:8884 0.0.0.0:0 LISTENING 4\n TCP 127.0.0.1:9012 0.0.0.0:0 LISTENING 15532\n TCP 127.0.0.1:9012 127.0.0.1:56668 ESTABLISHED 15532\n TCP 127.0.0.1:29885 0.0.0.0:0 LISTENING 26860" }, { "code": null, "e": 5390, "s": 5231, "text": "We got Process ID (PID) in this table and we can retrieve the processes with PID with Get-Process command and write a program for it which can correlate both." }, { "code": null, "e": 7192, "s": 5390, "text": "function Get-ProcessPorts{\n [cmdletbinding()]\n Param(\n [parameter(Mandatory=$True, ValueFromPipeLine=$True)]\n [AllowEmptyCollection()]\n [string[]]$ProcessName\n )\n Begin{ \n Write-Verbose \"Declaring empty array to store the output\"\n $portout = @() \n }\n Process{\n Write-Verbose \"Processes to get the port information\" \n $processes = Get-Process $ProcessName \n foreach($proc in $processes){\n # Get the port for the process.\n $mports = Netstat -ano | findstr $proc.ID\n # Separate each instance\n foreach($sport in $mports)\n # Split the netstat output and remove empty lines from the output.\n $out = $sport.Split('') | where{$_ -ne \"\"}\n $LCount = $out[1].LastIndexOf(':')\n $RCount = $out[2].LastIndexOf(':')\n $portout += [PSCustomObject]@{ \n 'Process' = $proc.Name\n 'PID' = $proc.ID\n 'Protocol' = $out[0]\n 'LocalAddress' = $out[1].SubString(0,$LCount)\n 'LocalPort' = $out[1].SubString($Lcount+1,($out[1].Length-$Lcount-1))\n 'RemoteAddress' = $out[2].SubString(0,$RCount)\n 'RemotePort' = $out[2].SubString($RCount+1,($out[2].Length-$Rcount-1))\n 'Connection' = $(\n # Checking if the connection contains any empty string.\n if(!($out[3] -match '\\d')){$out[3]} \n )\n }\n } \n }\n $portout | ft -AutoSize\n }\n End{\n Write-Verbose \"End of the program\"\n }\n}" }, { "code": null, "e": 7201, "s": 7192, "text": "Output −" }, { "code": null, "e": 8826, "s": 7201, "text": "Process PID Protocol LocalAddress LocalPort RemoteAddress RemotePort Connection\n------- --- -------- ------------ --------- ------------- ---------- ----------\navp 4252 TCP 127.0.0.1 49676 0.0.0.0 0 LISTENING \navp 4252 TCP 127.0.0.1 49676 127.0.0.1 50304 ESTABLISHED\navp 4252 TCP 127.0.0.1 49676 127.0.0.1 50338 ESTABLISHED\navp 4252 TCP 127.0.0.1 49676 127.0.0.1 50347 ESTABLISHED\navp 4252 TCP 127.0.0.1 49676 127.0.0.1 50357 ESTABLISHED\navp 4252 TCP 127.0.0.1 49676 127.0.0.1 50366 ESTABLISHED\navp 4252 TCP 127.0.0.1 49676 127.0.0.1 50370 ESTABLISHED\navp 4252 TCP 127.0.0.1 49676 127.0.0.1 50375 ESTABLISHED\navp 4252 TCP 127.0.0.1 49676 127.0.0.1 50376 ESTABLISHED\navp 4252 TCP 127.0.0.1 49676 127.0.0.1 50377 ESTABLISHED\navp 4252 TCP 127.0.0.1 49676 127.0.0.1 50378 ESTABLISHED\navp 4252 TCP 127.0.0.1 49676 127.0.0.1 50379 ESTABLISHED\navp 4252 TCP 127.0.0.1 49676 127.0.0.1 50380 ESTABLISHED\navp 4252 TCP 127.0.0.1 49676 127.0.0.1 50385 ESTABLISHED\navp 4252 TCP 127.0.0.1 49676 127.0.0.1 50387 ESTABLISHED\nWINWORD 25852 TCP 192.168.0.107 53584 99.83.135.170 443 ESTABLISHED\nWINWORD 25852 TCP 192.168.0.107 53592 99.83.135.170 443 ESTABLISHED\n\nVERBOSE: End of the program" } ]
How to create Time Picker in ReactJS ? - GeeksforGeeks
22 Jan, 2021 Time pickers provide a simple way to select a single value from a pre-determined set. Material UI for React has this component available for us and it is very easy to integrate. We can create a Time Picker in ReactJS using the following approach: Creating React Application And Installing Module: Step 1: Create a React application using the following command: npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command: cd foldername Step 3: After creating the ReactJS application, Install the material-ui modules using the following command: npm install @material-ui/core Project Structure: It will look like the following. Project Structure App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. Javascript import React from 'react';import TextField from '@material-ui/core/TextField'; const App = () => { return ( <div style={{ margin: 'auto', display: 'block', width: 'fit-content' }}> <h3>How to create Time Picker in ReactJS?</h3> <TextField label="Choose Time" defaultValue="04:20" type="time" InputLabelProps={{ shrink: true, }} // 5 minutes inputProps={{ step: 300, }} /> </div> );} export default App; Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: Supported Browser: This module is supported by the following browsers: Chrome Microsoft Edge Explorer JavaScript ReactJS 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 Difference Between PUT and PATCH Request Remove elements from a JavaScript Array How to get character array from string in JavaScript? How to filter object array based on attributes? How to fetch data from an API in ReactJS ? How to redirect to another page in ReactJS ? How to pass data from child component to its parent in ReactJS ? How to pass data from one component to other component in ReactJS ? ReactJS Functional Components
[ { "code": null, "e": 25312, "s": 25284, "text": "\n22 Jan, 2021" }, { "code": null, "e": 25559, "s": 25312, "text": "Time pickers provide a simple way to select a single value from a pre-determined set. Material UI for React has this component available for us and it is very easy to integrate. We can create a Time Picker in ReactJS using the following approach:" }, { "code": null, "e": 25609, "s": 25559, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 25673, "s": 25609, "text": "Step 1: Create a React application using the following command:" }, { "code": null, "e": 25705, "s": 25673, "text": "npx create-react-app foldername" }, { "code": null, "e": 25805, "s": 25705, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:" }, { "code": null, "e": 25819, "s": 25805, "text": "cd foldername" }, { "code": null, "e": 25928, "s": 25819, "text": "Step 3: After creating the ReactJS application, Install the material-ui modules using the following command:" }, { "code": null, "e": 25958, "s": 25928, "text": "npm install @material-ui/core" }, { "code": null, "e": 26010, "s": 25958, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 26028, "s": 26010, "text": "Project Structure" }, { "code": null, "e": 26157, "s": 26028, "text": "App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code." }, { "code": null, "e": 26168, "s": 26157, "text": "Javascript" }, { "code": "import React from 'react';import TextField from '@material-ui/core/TextField'; const App = () => { return ( <div style={{ margin: 'auto', display: 'block', width: 'fit-content' }}> <h3>How to create Time Picker in ReactJS?</h3> <TextField label=\"Choose Time\" defaultValue=\"04:20\" type=\"time\" InputLabelProps={{ shrink: true, }} // 5 minutes inputProps={{ step: 300, }} /> </div> );} export default App;", "e": 26690, "s": 26168, "text": null }, { "code": null, "e": 26803, "s": 26690, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 26813, "s": 26803, "text": "npm start" }, { "code": null, "e": 26912, "s": 26813, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 26984, "s": 26912, "text": "Supported Browser: This module is supported by the following browsers: " }, { "code": null, "e": 26991, "s": 26984, "text": "Chrome" }, { "code": null, "e": 27006, "s": 26991, "text": "Microsoft Edge" }, { "code": null, "e": 27015, "s": 27006, "text": "Explorer" }, { "code": null, "e": 27026, "s": 27015, "text": "JavaScript" }, { "code": null, "e": 27034, "s": 27026, "text": "ReactJS" }, { "code": null, "e": 27051, "s": 27034, "text": "Web Technologies" }, { "code": null, "e": 27149, "s": 27051, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27210, "s": 27149, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27251, "s": 27210, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 27291, "s": 27251, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27345, "s": 27291, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 27393, "s": 27345, "text": "How to filter object array based on attributes?" }, { "code": null, "e": 27436, "s": 27393, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 27481, "s": 27436, "text": "How to redirect to another page in ReactJS ?" }, { "code": null, "e": 27546, "s": 27481, "text": "How to pass data from child component to its parent in ReactJS ?" }, { "code": null, "e": 27614, "s": 27546, "text": "How to pass data from one component to other component in ReactJS ?" } ]
PyQt5 - QSlider Widget & Signal
QSlider class object presents the user with a groove over which a handle can be moved. It is a classic widget to control a bounded value. Position of the handle on the groove is equivalent to an integer between the lower and the upper bounds of the control. A slider control can be displayed in horizontal or vertical manner by mentioning the orientation in the constructor. self.sp = QSlider(Qt.Horizontal) self.sp = QSlider(Qt.Vertical) The following table lists some of the frequently used methods of QSlider class − setMinimum() Sets the lower bound of the slider setMaximum() Sets the upper bound of the slider setSingleStep() Sets the increment/decrement step setValue() Sets the value of the control programmatically value() Returns the current value setTickInterval() Puts the number of ticks on the groove setTickPosition() Places the ticks on the groove. Values are − The following are the methods in QSlider Signals − valueChanged() When the slider's value has changed sliderPressed() When the user starts to drag the slider sliderMoved() When the user drags the slider sliderReleased() When the user releases the slider valueChanged() signal is the one which is most frequently used. The following example demonstrates the above functionality. A Label and a horizontal slider is placed in a vertical layout. Slider’s valueChanged() signal is connected to valuechange() method. self.sl.valueChanged.connect(self.valuechange) The slot function valuechange() reads current value of the slider and uses it as the size of font for label’s caption. size = self.sl.value() self.l1.setFont(QFont("Arial",size)) The complete code is as follows − import sys from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * class sliderdemo(QWidget): def __init__(self, parent = None): super(sliderdemo, self).__init__(parent) layout = QVBoxLayout() self.l1 = QLabel("Hello") self.l1.setAlignment(Qt.AlignCenter) layout.addWidget(self.l1) self.sl = QSlider(Qt.Horizontal) self.sl.setMinimum(10) self.sl.setMaximum(30) self.sl.setValue(20) self.sl.setTickPosition(QSlider.TicksBelow) self.sl.setTickInterval(5) layout.addWidget(self.sl) self.sl.valueChanged.connect(self.valuechange) self.setLayout(layout) self.setWindowTitle("SpinBox demo") def valuechange(self): size = self.sl.value() self.l1.setFont(QFont("Arial",size)) def main(): app = QApplication(sys.argv) ex = sliderdemo() ex.show() sys.exit(app.exec_()) if __name__ == '__main__': main() The above code produces the following output − The font size of the label changes as handle of the slider is moved across the handle. 146 Lectures 22.5 hours ALAA EID Print Add Notes Bookmark this page
[ { "code": null, "e": 2221, "s": 1963, "text": "QSlider class object presents the user with a groove over which a handle can be moved. It is a classic widget to control a bounded value. Position of the handle on the groove is equivalent to an integer between the lower and the upper bounds of the control." }, { "code": null, "e": 2338, "s": 2221, "text": "A slider control can be displayed in horizontal or vertical manner by mentioning the orientation in the constructor." }, { "code": null, "e": 2403, "s": 2338, "text": "self.sp = QSlider(Qt.Horizontal)\nself.sp = QSlider(Qt.Vertical)\n" }, { "code": null, "e": 2484, "s": 2403, "text": "The following table lists some of the frequently used methods of QSlider class −" }, { "code": null, "e": 2497, "s": 2484, "text": "setMinimum()" }, { "code": null, "e": 2532, "s": 2497, "text": "Sets the lower bound of the slider" }, { "code": null, "e": 2545, "s": 2532, "text": "setMaximum()" }, { "code": null, "e": 2580, "s": 2545, "text": "Sets the upper bound of the slider" }, { "code": null, "e": 2596, "s": 2580, "text": "setSingleStep()" }, { "code": null, "e": 2630, "s": 2596, "text": "Sets the increment/decrement step" }, { "code": null, "e": 2641, "s": 2630, "text": "setValue()" }, { "code": null, "e": 2688, "s": 2641, "text": "Sets the value of the control programmatically" }, { "code": null, "e": 2696, "s": 2688, "text": "value()" }, { "code": null, "e": 2722, "s": 2696, "text": "Returns the current value" }, { "code": null, "e": 2740, "s": 2722, "text": "setTickInterval()" }, { "code": null, "e": 2779, "s": 2740, "text": "Puts the number of ticks on the groove" }, { "code": null, "e": 2797, "s": 2779, "text": "setTickPosition()" }, { "code": null, "e": 2842, "s": 2797, "text": "Places the ticks on the groove. Values are −" }, { "code": null, "e": 2893, "s": 2842, "text": "The following are the methods in QSlider Signals −" }, { "code": null, "e": 2908, "s": 2893, "text": "valueChanged()" }, { "code": null, "e": 2944, "s": 2908, "text": "When the slider's value has changed" }, { "code": null, "e": 2960, "s": 2944, "text": "sliderPressed()" }, { "code": null, "e": 3000, "s": 2960, "text": "When the user starts to drag the slider" }, { "code": null, "e": 3014, "s": 3000, "text": "sliderMoved()" }, { "code": null, "e": 3045, "s": 3014, "text": "When the user drags the slider" }, { "code": null, "e": 3062, "s": 3045, "text": "sliderReleased()" }, { "code": null, "e": 3096, "s": 3062, "text": "When the user releases the slider" }, { "code": null, "e": 3160, "s": 3096, "text": "valueChanged() signal is the one which is most frequently used." }, { "code": null, "e": 3353, "s": 3160, "text": "The following example demonstrates the above functionality. A Label and a horizontal slider is placed in a vertical layout. Slider’s valueChanged() signal is connected to valuechange() method." }, { "code": null, "e": 3401, "s": 3353, "text": "self.sl.valueChanged.connect(self.valuechange)\n" }, { "code": null, "e": 3520, "s": 3401, "text": "The slot function valuechange() reads current value of the slider and uses it as the size of font for label’s caption." }, { "code": null, "e": 3581, "s": 3520, "text": "size = self.sl.value()\nself.l1.setFont(QFont(\"Arial\",size))\n" }, { "code": null, "e": 3615, "s": 3581, "text": "The complete code is as follows −" }, { "code": null, "e": 4572, "s": 3615, "text": "import sys\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtWidgets import *\n\nclass sliderdemo(QWidget):\n def __init__(self, parent = None):\n super(sliderdemo, self).__init__(parent)\n\n layout = QVBoxLayout()\n self.l1 = QLabel(\"Hello\")\n self.l1.setAlignment(Qt.AlignCenter)\n layout.addWidget(self.l1)\n\t\t\n self.sl = QSlider(Qt.Horizontal)\n self.sl.setMinimum(10)\n self.sl.setMaximum(30)\n self.sl.setValue(20)\n self.sl.setTickPosition(QSlider.TicksBelow)\n self.sl.setTickInterval(5)\n\t\t\n layout.addWidget(self.sl)\n self.sl.valueChanged.connect(self.valuechange)\n self.setLayout(layout)\n self.setWindowTitle(\"SpinBox demo\")\n\n def valuechange(self):\n size = self.sl.value()\n self.l1.setFont(QFont(\"Arial\",size))\n\t\t\ndef main():\n app = QApplication(sys.argv)\n ex = sliderdemo()\n ex.show()\n sys.exit(app.exec_())\n\t\nif __name__ == '__main__':\n main()" }, { "code": null, "e": 4619, "s": 4572, "text": "The above code produces the following output −" }, { "code": null, "e": 4706, "s": 4619, "text": "The font size of the label changes as handle of the slider is moved across the handle." }, { "code": null, "e": 4743, "s": 4706, "text": "\n 146 Lectures \n 22.5 hours \n" }, { "code": null, "e": 4753, "s": 4743, "text": " ALAA EID" }, { "code": null, "e": 4760, "s": 4753, "text": " Print" }, { "code": null, "e": 4771, "s": 4760, "text": " Add Notes" } ]
How to calculate the difference between two dates in PHP ? - GeeksforGeeks
03 Dec, 2021 In this article, we will see how to calculate the difference between 2 dates in PHP, along with understanding its implementation through the examples. Given two dates ie., start_date and end_date & we need to find the difference between the two dates. Consider the below example: Input: start_date: 2016-06-01 22:45:00 end_date: 2018-09-21 10:44:01 Output: 2 years, 3 months, 21 days, 11 hours, 59 minutes, 1 seconds Explanation: The difference of 2 dates will give the date in complete format. Method 1: Using date_diff() Function This function is used to find the difference between two dates. This function will return a DateInterval object on the success and returns FALSE on failure. Example: This example illustrates the use of the date_diff() function to calculate the difference between the 2 dates. PHP <?php // Creates DateTime objects $datetime1 = date_create('2016-06-01'); $datetime2 = date_create('2018-09-21'); // Calculates the difference between DateTime objects $interval = date_diff($datetime1, $datetime2); // Printing result in years & months format echo $interval->format('%R%y years %m months');?> Output: +2 years 3 months Method 2: To use the date-time mathematical formula to find the difference between two dates. It returns the years, months, days, hours, minutes, seconds between two specified dates. Example: In this example, we will be using the date-time mathematical formula to calculate the difference between the dates that will be returned in years, months, days, hours, minutes, seconds. PHP <?php // Declare and define two dates $date1 = strtotime("2016-06-01 22:45:00"); $date2 = strtotime("2018-09-21 10:44:01"); // Formulate the Difference between two dates $diff = abs($date2 - $date1); // To get the year divide the resultant date into // total seconds in a year (365*60*60*24) $years = floor($diff / (365*60*60*24)); // To get the month, subtract it with years and // divide the resultant date into // total seconds in a month (30*60*60*24) $months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24)); // To get the day, subtract it with years and // months and divide the resultant date into // total seconds in a days (60*60*24) $days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24)); // To get the hour, subtract it with years, // months & seconds and divide the resultant // date into total seconds in a hours (60*60) $hours = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24 - $days*60*60*24) / (60*60)); // To get the minutes, subtract it with years, // months, seconds and hours and divide the // resultant date into total seconds i.e. 60 $minutes = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24 - $days*60*60*24 - $hours*60*60)/ 60); // To get the minutes, subtract it with years, // months, seconds, hours and minutes $seconds = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24 - $days*60*60*24 - $hours*60*60 - $minutes*60)); // Print the result printf("%d years, %d months, %d days, %d hours, " . "%d minutes, %d seconds", $years, $months, $days, $hours, $minutes, $seconds);?> Output: 2 years, 3 months, 21 days, 11 hours, 59 minutes, 1 seconds Method 3: This method is used to get the total number of days between two specified dates. PHP <?php // Declare two dates $start_date = strtotime("2018-06-08"); $end_date = strtotime("2018-09-19"); // Get the difference and divide into // total no. seconds 60/60/24 to get // number of days echo "Difference between two dates: " . ($end_date - $start_date)/60/60/24;?> Output: Difference between two dates: 103 PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples. bhaskargeeksforgeeks Picked PHP PHP Programs Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? How to receive JSON POST with PHP ? PHP | Converting string to Date and DateTime How to pass JavaScript variables to PHP ? How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? How to call PHP function on the click of a Button ? How to run JavaScript from PHP? How to pass JavaScript variables to PHP ?
[ { "code": null, "e": 24678, "s": 24650, "text": "\n03 Dec, 2021" }, { "code": null, "e": 24930, "s": 24678, "text": "In this article, we will see how to calculate the difference between 2 dates in PHP, along with understanding its implementation through the examples. Given two dates ie., start_date and end_date & we need to find the difference between the two dates." }, { "code": null, "e": 24958, "s": 24930, "text": "Consider the below example:" }, { "code": null, "e": 25181, "s": 24958, "text": "Input: start_date: 2016-06-01 22:45:00 \n end_date: 2018-09-21 10:44:01\nOutput: 2 years, 3 months, 21 days, 11 hours, 59 minutes, 1 seconds\nExplanation: The difference of 2 dates will give the date in complete format." }, { "code": null, "e": 25218, "s": 25181, "text": "Method 1: Using date_diff() Function" }, { "code": null, "e": 25375, "s": 25218, "text": "This function is used to find the difference between two dates. This function will return a DateInterval object on the success and returns FALSE on failure." }, { "code": null, "e": 25494, "s": 25375, "text": "Example: This example illustrates the use of the date_diff() function to calculate the difference between the 2 dates." }, { "code": null, "e": 25498, "s": 25494, "text": "PHP" }, { "code": "<?php // Creates DateTime objects $datetime1 = date_create('2016-06-01'); $datetime2 = date_create('2018-09-21'); // Calculates the difference between DateTime objects $interval = date_diff($datetime1, $datetime2); // Printing result in years & months format echo $interval->format('%R%y years %m months');?>", "e": 25817, "s": 25498, "text": null }, { "code": null, "e": 25825, "s": 25817, "text": "Output:" }, { "code": null, "e": 25843, "s": 25825, "text": "+2 years 3 months" }, { "code": null, "e": 26026, "s": 25843, "text": "Method 2: To use the date-time mathematical formula to find the difference between two dates. It returns the years, months, days, hours, minutes, seconds between two specified dates." }, { "code": null, "e": 26221, "s": 26026, "text": "Example: In this example, we will be using the date-time mathematical formula to calculate the difference between the dates that will be returned in years, months, days, hours, minutes, seconds." }, { "code": null, "e": 26225, "s": 26221, "text": "PHP" }, { "code": "<?php // Declare and define two dates $date1 = strtotime(\"2016-06-01 22:45:00\"); $date2 = strtotime(\"2018-09-21 10:44:01\"); // Formulate the Difference between two dates $diff = abs($date2 - $date1); // To get the year divide the resultant date into // total seconds in a year (365*60*60*24) $years = floor($diff / (365*60*60*24)); // To get the month, subtract it with years and // divide the resultant date into // total seconds in a month (30*60*60*24) $months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24)); // To get the day, subtract it with years and // months and divide the resultant date into // total seconds in a days (60*60*24) $days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24)); // To get the hour, subtract it with years, // months & seconds and divide the resultant // date into total seconds in a hours (60*60) $hours = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24 - $days*60*60*24) / (60*60)); // To get the minutes, subtract it with years, // months, seconds and hours and divide the // resultant date into total seconds i.e. 60 $minutes = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24 - $days*60*60*24 - $hours*60*60)/ 60); // To get the minutes, subtract it with years, // months, seconds, hours and minutes $seconds = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24 - $days*60*60*24 - $hours*60*60 - $minutes*60)); // Print the result printf(\"%d years, %d months, %d days, %d hours, \" . \"%d minutes, %d seconds\", $years, $months, $days, $hours, $minutes, $seconds);?>", "e": 28005, "s": 26225, "text": null }, { "code": null, "e": 28013, "s": 28005, "text": "Output:" }, { "code": null, "e": 28073, "s": 28013, "text": "2 years, 3 months, 21 days, 11 hours, 59 minutes, 1 seconds" }, { "code": null, "e": 28164, "s": 28073, "text": "Method 3: This method is used to get the total number of days between two specified dates." }, { "code": null, "e": 28168, "s": 28164, "text": "PHP" }, { "code": "<?php // Declare two dates $start_date = strtotime(\"2018-06-08\"); $end_date = strtotime(\"2018-09-19\"); // Get the difference and divide into // total no. seconds 60/60/24 to get // number of days echo \"Difference between two dates: \" . ($end_date - $start_date)/60/60/24;?>", "e": 28456, "s": 28168, "text": null }, { "code": null, "e": 28464, "s": 28456, "text": "Output:" }, { "code": null, "e": 28498, "s": 28464, "text": "Difference between two dates: 103" }, { "code": null, "e": 28667, "s": 28498, "text": "PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples." }, { "code": null, "e": 28688, "s": 28667, "text": "bhaskargeeksforgeeks" }, { "code": null, "e": 28695, "s": 28688, "text": "Picked" }, { "code": null, "e": 28699, "s": 28695, "text": "PHP" }, { "code": null, "e": 28712, "s": 28699, "text": "PHP Programs" }, { "code": null, "e": 28729, "s": 28712, "text": "Web Technologies" }, { "code": null, "e": 28733, "s": 28729, "text": "PHP" }, { "code": null, "e": 28831, "s": 28733, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28881, "s": 28831, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 28921, "s": 28881, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 28957, "s": 28921, "text": "How to receive JSON POST with PHP ?" }, { "code": null, "e": 29002, "s": 28957, "text": "PHP | Converting string to Date and DateTime" }, { "code": null, "e": 29044, "s": 29002, "text": "How to pass JavaScript variables to PHP ?" }, { "code": null, "e": 29094, "s": 29044, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 29134, "s": 29094, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 29186, "s": 29134, "text": "How to call PHP function on the click of a Button ?" }, { "code": null, "e": 29218, "s": 29186, "text": "How to run JavaScript from PHP?" } ]
Tryit Editor v3.7
Tryit: Template 3
[]
Store mouse click event coordinates with Matplotlib
To store mouse event coordinates with matplotlib, we can use "button_press_event" event.− Set the figure size and adjust the padding between and around the subplots. Create a figure and a set of subplots. Plot a line in the range of 10 Bind the function *onclick* to the event *button_press_event*. Print the x and y data of the event. To display the figure, use show() method. from matplotlib import pyplot as plt plt.rcParams['backend'] = 'TkAgg' plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True # Function to print mouse click event coordinates def onclick(event): print([event.xdata, event.ydata]) # Create a figure and a set of subplots fig, ax = plt.subplots() # Plot a line in the range of 10 ax.plot(range(10)) # Bind the button_press_event with the onclick() method fig.canvas.mpl_connect('button_press_event', onclick) # Display the plot plt.show() On execution, it will produce the following output: Now, click anywhere on the plot and it will display that particular point's coordinates on the console: [6.277811659536052 6.218189947945731] [4.9416949672083685 3.7079096112932475] [8.221254287227506 3.4145010811941963]
[ { "code": null, "e": 1152, "s": 1062, "text": "To store mouse event coordinates with matplotlib, we can use \"button_press_event\" event.−" }, { "code": null, "e": 1228, "s": 1152, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1267, "s": 1228, "text": "Create a figure and a set of subplots." }, { "code": null, "e": 1298, "s": 1267, "text": "Plot a line in the range of 10" }, { "code": null, "e": 1361, "s": 1298, "text": "Bind the function *onclick* to the event *button_press_event*." }, { "code": null, "e": 1398, "s": 1361, "text": "Print the x and y data of the event." }, { "code": null, "e": 1440, "s": 1398, "text": "To display the figure, use show() method." }, { "code": null, "e": 1968, "s": 1440, "text": "from matplotlib import pyplot as plt\n\nplt.rcParams['backend'] = 'TkAgg'\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\n# Function to print mouse click event coordinates\ndef onclick(event):\n print([event.xdata, event.ydata])\n\n# Create a figure and a set of subplots\nfig, ax = plt.subplots()\n\n# Plot a line in the range of 10\nax.plot(range(10))\n\n# Bind the button_press_event with the onclick() method\nfig.canvas.mpl_connect('button_press_event', onclick)\n\n# Display the plot\nplt.show()" }, { "code": null, "e": 2020, "s": 1968, "text": "On execution, it will produce the following output:" }, { "code": null, "e": 2124, "s": 2020, "text": "Now, click anywhere on the plot and it will display that particular point's coordinates on the console:" }, { "code": null, "e": 2241, "s": 2124, "text": "[6.277811659536052 6.218189947945731]\n[4.9416949672083685 3.7079096112932475]\n[8.221254287227506 3.4145010811941963]" } ]
How to find the number of NA’s in each column of an R data frame?
Sometimes the data frame is filled with too many missing values/ NA’s and each column of the data frame contains at least one NA. In this case, we might want to find out how many missing values exists in each of the columns. Therefore, we can use colSums function along with is.na in the following manner: colSums(is.na(df)) #here df refers to data frame name. Consider the below data frame − Live Demo set.seed(109) x1<-sample(c(0:1,NA),20,replace=TRUE) x2<-sample(c(rpois(5,2),NA),20,replace=TRUE)df1<-data.frame(x1,x2) df1 x1 x2 1 0 1 2 1 NA 3 NA 0 4 NA 0 5 1 1 6 1 1 7 NA NA 8 NA NA 9 0 1 10 NA 1 11 1 1 12 0 1 13 NA 1 14 0 0 15 1 1 16 NA 0 17 1 1 18 1 NA 19 NA NA 20 0 0 Finding the number of NA’s in each column of the data frame df1 − colSums(is.na(df1)) x1 x2 6 4 Let’s have a look at another example − Live Demo y1<-sample(c(100,105,NA,115,120),20,replace=TRUE) y2<-sample(c(rnorm(3,1,0.04),NA),20,replace=TRUE) df2<-data.frame(y1,y2) df2 y1 y2 1 NA NA 2 NA NA 3 105 NA 4 115 0.9910075 5 120 NA 6 120 0.9547570 7 105 0.9547570 8 105 1.0468139 9 120 0.9910075 10 115 0.9547570 11 115 0.9910075 12 100 0.9910075 13 NA 1.0468139 14 120 1.0468139 15 NA 1.0468139 16 115 NA 17 115 1.0468139 18 100 NA 19 120 0.9910075 20 120 0.9910075 Finding the number of NA’s in each column of the data frame df2 − colSums(is.na(df2)) y1 y2 3 3
[ { "code": null, "e": 1423, "s": 1062, "text": "Sometimes the data frame is filled with too many missing values/ NA’s and each column of the data frame contains at least one NA. In this case, we might want to find out how many missing values exists in each of the columns. Therefore, we can use colSums function along with is.na in the following manner: colSums(is.na(df)) #here df refers to data frame name." }, { "code": null, "e": 1455, "s": 1423, "text": "Consider the below data frame −" }, { "code": null, "e": 1466, "s": 1455, "text": " Live Demo" }, { "code": null, "e": 1589, "s": 1466, "text": "set.seed(109)\nx1<-sample(c(0:1,NA),20,replace=TRUE)\nx2<-sample(c(rpois(5,2),NA),20,replace=TRUE)df1<-data.frame(x1,x2)\ndf1" }, { "code": null, "e": 1771, "s": 1589, "text": " x1 x2\n1 0 1\n2 1 NA\n3 NA 0\n4 NA 0\n5 1 1\n6 1 1\n7 NA NA\n8 NA NA\n9 0 1\n10 NA 1\n11 1 1\n12 0 1\n13 NA 1\n14 0 0\n15 1 1\n16 NA 0\n17 1 1\n18 1 NA\n19 NA NA\n20 0 0" }, { "code": null, "e": 1837, "s": 1771, "text": "Finding the number of NA’s in each column of the data frame df1 −" }, { "code": null, "e": 1857, "s": 1837, "text": "colSums(is.na(df1))" }, { "code": null, "e": 1867, "s": 1857, "text": "x1 x2\n6 4" }, { "code": null, "e": 1906, "s": 1867, "text": "Let’s have a look at another example −" }, { "code": null, "e": 1917, "s": 1906, "text": " Live Demo" }, { "code": null, "e": 2044, "s": 1917, "text": "y1<-sample(c(100,105,NA,115,120),20,replace=TRUE)\ny2<-sample(c(rnorm(3,1,0.04),NA),20,replace=TRUE)\ndf2<-data.frame(y1,y2)\ndf2" }, { "code": null, "e": 2335, "s": 2044, "text": "y1 y2\n1 NA NA\n2 NA NA\n3 105 NA\n4 115 0.9910075\n5 120 NA\n6 120 0.9547570\n7 105 0.9547570\n8 105 1.0468139\n9 120 0.9910075\n10 115 0.9547570\n11 115 0.9910075\n12 100 0.9910075\n13 NA 1.0468139\n14 120 1.0468139\n15 NA 1.0468139\n16 115 NA\n17 115 1.0468139\n18 100 NA\n19 120 0.9910075\n20 120 0.9910075" }, { "code": null, "e": 2401, "s": 2335, "text": "Finding the number of NA’s in each column of the data frame df2 −" }, { "code": null, "e": 2421, "s": 2401, "text": "colSums(is.na(df2))" }, { "code": null, "e": 2431, "s": 2421, "text": "y1 y2\n3 3" } ]
How to Create a Timer using Jetpack Compose in Android? - GeeksforGeeks
18 Jul, 2021 Jetpack Compose is a modern toolkit for building native Android UI. Jetpack Compose simplifies and accelerates UI development on Android with less code, powerful tools, and intuitive Kotlin APIs. In this article, we are going to create a Timer using Jetpack Compose. Below is the sample video to show what we are going to build. Step 1: Create a new project To create a new project in Android Studio using Jetpack Compose please refer to How to Create a New Project in Android Studio Canary Version with Jetpack Compose. Step 2: Working with MainActivity.kt Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail. Kotlin import androidx.compose.ui.unit.dpimport androidx.activity.compose.setContentimport android.os.Bundleimport androidx.activity.ComponentActivityimport androidx.compose.material.Surfaceimport androidx.compose.material.Textimport androidx.compose.runtime.Composableimport androidx.compose.ui.Modifierimport androidx.compose.foundation.Canvasimport androidx.compose.foundation.layout.Boximport androidx.compose.foundation.layout.fillMaxSizeimport androidx.compose.foundation.layout.sizeimport androidx.compose.material.*import androidx.compose.runtime.*import androidx.compose.ui.Alignmentimport androidx.compose.ui.geometry.Offsetimport androidx.compose.ui.geometry.Sizeimport androidx.compose.ui.graphics.Colorimport androidx.compose.ui.graphics.PointModeimport androidx.compose.ui.graphics.StrokeCapimport androidx.compose.ui.graphics.drawscope.Strokeimport androidx.compose.ui.layout.onSizeChangedimport androidx.compose.ui.text.font.FontWeightimport androidx.compose.ui.unit.Dpimport androidx.compose.ui.unit.IntSizeimport androidx.compose.ui.unit.spimport kotlinx.coroutines.delayimport kotlin.math.PIimport kotlin.math.cosimport kotlin.math.sin class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { Surface( color = Color(0xFF101010), modifier = Modifier.fillMaxSize() ) { Box( contentAlignment = Alignment.Center ) { // call the function Timer // and pass the values // it is defined below. Timer( totalTime = 100L * 1000L, handleColor = Color.Green, inactiveBarColor = Color.DarkGray, activeBarColor = Color(0xFF37B900), modifier = Modifier.size(200.dp) ) } } } }} // create a composable to // Draw arc and handle@Composablefun Timer( // total time of the timer totalTime: Long, // circular handle color handleColor: Color, // color of inactive bar / progress bar inactiveBarColor: Color, // color of active bar activeBarColor: Color, modifier: Modifier = Modifier, // set initial value to 1 initialValue: Float = 1f, strokeWidth: Dp = 5.dp) { // create variable for // size of the composable var size by remember { mutableStateOf(IntSize.Zero) } // create variable for value var value by remember { mutableStateOf(initialValue) } // create variable for current time var currentTime by remember { mutableStateOf(totalTime) } // create variable for isTimerRunning var isTimerRunning by remember { mutableStateOf(false) } LaunchedEffect(key1 = currentTime, key2 = isTimerRunning) { if(currentTime > 0 && isTimerRunning) { delay(100L) currentTime -= 100L value = currentTime / totalTime.toFloat() } } Box( contentAlignment = Alignment.Center, modifier = modifier .onSizeChanged { size = it } ) { // draw the timer Canvas(modifier = modifier) { // draw the inactive arc with following parameters drawArc( color = inactiveBarColor, // assign the color startAngle = -215f, // assign the start angle sweepAngle = 250f, // arc angles useCenter = false, // prevents our arc to connect at te ends size = Size(size.width.toFloat(), size.height.toFloat()), // to make ends of arc round style = Stroke(strokeWidth.toPx(), cap = StrokeCap.Round) ) // draw the active arc with following parameters drawArc( color = activeBarColor, // assign the color startAngle = -215f, // assign the start angle sweepAngle = 250f * value, // reduce the sweep angle // with the current value useCenter = false, // prevents our arc to connect at te ends size = Size(size.width.toFloat(), size.height.toFloat()), // to make ends of arc round style = Stroke(strokeWidth.toPx(), cap = StrokeCap.Round) ) // calculate the value from arc pointer position val center = Offset(size.width / 2f, size.height / 2f) val beta = (250f * value + 145f) * (PI / 180f).toFloat() val r = size.width / 2f val a = cos(beta) * r val b = sin(beta) * r // draw the circular pointer/ cap drawPoints( listOf(Offset(center.x + a, center.y + b)), pointMode = PointMode.Points, color = handleColor, strokeWidth = (strokeWidth * 3f).toPx(), cap = StrokeCap.Round // make the pointer round ) } // add value of the timer Text( text = (currentTime / 1000L).toString(), fontSize = 44.sp, fontWeight = FontWeight.Bold, color = Color.White ) // create button to start or stop the timer Button( onClick = { if(currentTime <= 0L) { currentTime = totalTime isTimerRunning = true } else { isTimerRunning = !isTimerRunning } }, modifier = Modifier.align(Alignment.BottomCenter), // change button color colors = ButtonDefaults.buttonColors( backgroundColor = if (!isTimerRunning || currentTime <= 0L) { Color.Green } else { Color.Red } ) ) { Text( // change the text of button based on values text = if (isTimerRunning && currentTime >= 0L) "Stop" else if (!isTimerRunning && currentTime >= 0L) "Start" else "Restart" ) } }} Output: Android-Jetpack Android Kotlin Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Retrofit with Kotlin Coroutine in Android Android Listview in Java with Example Flutter - Custom Bottom Navigation Bar How to Read Data from SQLite Database in Android? How to Change the Background Color After Clicking the Button in Android? Android UI Layouts Retrofit with Kotlin Coroutine in Android Kotlin Array Android Menus MVP (Model View Presenter) Architecture Pattern in Android with Example
[ { "code": null, "e": 25036, "s": 25008, "text": "\n18 Jul, 2021" }, { "code": null, "e": 25366, "s": 25036, "text": "Jetpack Compose is a modern toolkit for building native Android UI. Jetpack Compose simplifies and accelerates UI development on Android with less code, powerful tools, and intuitive Kotlin APIs. In this article, we are going to create a Timer using Jetpack Compose. Below is the sample video to show what we are going to build. " }, { "code": null, "e": 25395, "s": 25366, "text": "Step 1: Create a new project" }, { "code": null, "e": 25558, "s": 25395, "text": "To create a new project in Android Studio using Jetpack Compose please refer to How to Create a New Project in Android Studio Canary Version with Jetpack Compose." }, { "code": null, "e": 25595, "s": 25558, "text": "Step 2: Working with MainActivity.kt" }, { "code": null, "e": 25781, "s": 25595, "text": "Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 25788, "s": 25781, "text": "Kotlin" }, { "code": "import androidx.compose.ui.unit.dpimport androidx.activity.compose.setContentimport android.os.Bundleimport androidx.activity.ComponentActivityimport androidx.compose.material.Surfaceimport androidx.compose.material.Textimport androidx.compose.runtime.Composableimport androidx.compose.ui.Modifierimport androidx.compose.foundation.Canvasimport androidx.compose.foundation.layout.Boximport androidx.compose.foundation.layout.fillMaxSizeimport androidx.compose.foundation.layout.sizeimport androidx.compose.material.*import androidx.compose.runtime.*import androidx.compose.ui.Alignmentimport androidx.compose.ui.geometry.Offsetimport androidx.compose.ui.geometry.Sizeimport androidx.compose.ui.graphics.Colorimport androidx.compose.ui.graphics.PointModeimport androidx.compose.ui.graphics.StrokeCapimport androidx.compose.ui.graphics.drawscope.Strokeimport androidx.compose.ui.layout.onSizeChangedimport androidx.compose.ui.text.font.FontWeightimport androidx.compose.ui.unit.Dpimport androidx.compose.ui.unit.IntSizeimport androidx.compose.ui.unit.spimport kotlinx.coroutines.delayimport kotlin.math.PIimport kotlin.math.cosimport kotlin.math.sin class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { Surface( color = Color(0xFF101010), modifier = Modifier.fillMaxSize() ) { Box( contentAlignment = Alignment.Center ) { // call the function Timer // and pass the values // it is defined below. Timer( totalTime = 100L * 1000L, handleColor = Color.Green, inactiveBarColor = Color.DarkGray, activeBarColor = Color(0xFF37B900), modifier = Modifier.size(200.dp) ) } } } }} // create a composable to // Draw arc and handle@Composablefun Timer( // total time of the timer totalTime: Long, // circular handle color handleColor: Color, // color of inactive bar / progress bar inactiveBarColor: Color, // color of active bar activeBarColor: Color, modifier: Modifier = Modifier, // set initial value to 1 initialValue: Float = 1f, strokeWidth: Dp = 5.dp) { // create variable for // size of the composable var size by remember { mutableStateOf(IntSize.Zero) } // create variable for value var value by remember { mutableStateOf(initialValue) } // create variable for current time var currentTime by remember { mutableStateOf(totalTime) } // create variable for isTimerRunning var isTimerRunning by remember { mutableStateOf(false) } LaunchedEffect(key1 = currentTime, key2 = isTimerRunning) { if(currentTime > 0 && isTimerRunning) { delay(100L) currentTime -= 100L value = currentTime / totalTime.toFloat() } } Box( contentAlignment = Alignment.Center, modifier = modifier .onSizeChanged { size = it } ) { // draw the timer Canvas(modifier = modifier) { // draw the inactive arc with following parameters drawArc( color = inactiveBarColor, // assign the color startAngle = -215f, // assign the start angle sweepAngle = 250f, // arc angles useCenter = false, // prevents our arc to connect at te ends size = Size(size.width.toFloat(), size.height.toFloat()), // to make ends of arc round style = Stroke(strokeWidth.toPx(), cap = StrokeCap.Round) ) // draw the active arc with following parameters drawArc( color = activeBarColor, // assign the color startAngle = -215f, // assign the start angle sweepAngle = 250f * value, // reduce the sweep angle // with the current value useCenter = false, // prevents our arc to connect at te ends size = Size(size.width.toFloat(), size.height.toFloat()), // to make ends of arc round style = Stroke(strokeWidth.toPx(), cap = StrokeCap.Round) ) // calculate the value from arc pointer position val center = Offset(size.width / 2f, size.height / 2f) val beta = (250f * value + 145f) * (PI / 180f).toFloat() val r = size.width / 2f val a = cos(beta) * r val b = sin(beta) * r // draw the circular pointer/ cap drawPoints( listOf(Offset(center.x + a, center.y + b)), pointMode = PointMode.Points, color = handleColor, strokeWidth = (strokeWidth * 3f).toPx(), cap = StrokeCap.Round // make the pointer round ) } // add value of the timer Text( text = (currentTime / 1000L).toString(), fontSize = 44.sp, fontWeight = FontWeight.Bold, color = Color.White ) // create button to start or stop the timer Button( onClick = { if(currentTime <= 0L) { currentTime = totalTime isTimerRunning = true } else { isTimerRunning = !isTimerRunning } }, modifier = Modifier.align(Alignment.BottomCenter), // change button color colors = ButtonDefaults.buttonColors( backgroundColor = if (!isTimerRunning || currentTime <= 0L) { Color.Green } else { Color.Red } ) ) { Text( // change the text of button based on values text = if (isTimerRunning && currentTime >= 0L) \"Stop\" else if (!isTimerRunning && currentTime >= 0L) \"Start\" else \"Restart\" ) } }}", "e": 32143, "s": 25788, "text": null }, { "code": null, "e": 32151, "s": 32143, "text": "Output:" }, { "code": null, "e": 32167, "s": 32151, "text": "Android-Jetpack" }, { "code": null, "e": 32175, "s": 32167, "text": "Android" }, { "code": null, "e": 32182, "s": 32175, "text": "Kotlin" }, { "code": null, "e": 32190, "s": 32182, "text": "Android" }, { "code": null, "e": 32288, "s": 32190, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32297, "s": 32288, "text": "Comments" }, { "code": null, "e": 32310, "s": 32297, "text": "Old Comments" }, { "code": null, "e": 32352, "s": 32310, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 32390, "s": 32352, "text": "Android Listview in Java with Example" }, { "code": null, "e": 32429, "s": 32390, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 32479, "s": 32429, "text": "How to Read Data from SQLite Database in Android?" }, { "code": null, "e": 32552, "s": 32479, "text": "How to Change the Background Color After Clicking the Button in Android?" }, { "code": null, "e": 32571, "s": 32552, "text": "Android UI Layouts" }, { "code": null, "e": 32613, "s": 32571, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 32626, "s": 32613, "text": "Kotlin Array" }, { "code": null, "e": 32640, "s": 32626, "text": "Android Menus" } ]
DSatur Algorithm for Graph Coloring - GeeksforGeeks
08 Nov, 2021 Graph colouring is the task of assigning colours to the vertices of a graph so that: pairs of adjacent vertices are assigned different colours, and the number of different colours used across the graph is minimal. The following graph has been coloured using just three colours (red, blue and green here). This is actually the minimum number of colours needed for this particular graph – that is, we cannot colour this graph using fewer than three colours while ensuring that adjacent vertices are coloured differently. Proper three-colouring of a graph The minimum number of colours needed to colour a graph G is known as the chromatic number and is usually denoted by χ(G). Determining the chromatic number of a graph is NP-hard. The corresponding decision problem of deciding whether a k-colouring exists for a graph G is also NP-complete. Similar posts on this website have already described the greedy algorithm for graph colouring. This algorithm is simple to apply, but the number of colours used in its solutions depends very much on the order that the vertices are considered. In the best case, the right ordering will produce a solution using χ(G) colours; however bad orderings can result in solutions using many additional colours. The DSatur algorithm (abbreviated from “degree of saturation”) has similar behaviour to the Greedy algorithm. The difference lies in the way that it generates the vertex ordering. Specifically, the next vertex to colour is always chosen as the uncoloured vertex with the highest saturation degree. The saturation degree of a vertex is defined as the number of different colours currently assigned to neighbouring vertices. Other rules are also then used to break ties. Let G be a graph with n vertices and m edges. In addition, assume that we will use the colour labels 0, 1, 2, ..., n-1. (More than n colours are never required in a solution). The DSatur algorithm operates as follows Let v be the uncoloured vertex in G with the largest saturation degree. In cases of ties, choose the vertex among these with the largest degree in the subgraph induced by the uncoloured vertices. Further ties can be broken arbitrarily.Assign v to colour i, where i is the smallest integer from the set {0, 1, 2, ..., n} that is not currently assigned to any neighbour of v.If there remain uncoloured vertices, repeat all steps again, otherwise, end at this step. Let v be the uncoloured vertex in G with the largest saturation degree. In cases of ties, choose the vertex among these with the largest degree in the subgraph induced by the uncoloured vertices. Further ties can be broken arbitrarily. Assign v to colour i, where i is the smallest integer from the set {0, 1, 2, ..., n} that is not currently assigned to any neighbour of v. If there remain uncoloured vertices, repeat all steps again, otherwise, end at this step. The DSatur algorithm is similar to the Greedy algorithm in that once a vertex has been selected, it is assigned to the lowest colour label not assigned to any of its neighbours. The actions of Step 1, therefore, provide the main power behind the algorithm in that they prioritise vertices that are seen to be the “most constrained” – that is, vertices that currently have the fewest colour options available to them. Consequently, these “more constrained” vertices are dealt with first, allowing the less constrained vertices to be coloured later. Analysis of DSatur Because the DSatur algorithm generates a vertex ordering during execution, the number of colours it uses is more predictable than the greedy algorithm. Its solutions also tend to have fewer colours than those of the greedy algorithm. One feature of the algorithm is that, if a graph is composed of multiple components, then all vertices of a single component will be coloured before the other vertices are considered. DSatur is also exact for several graph topologies including bipartite graphs, cycle graphs and wheel graphs. (With these graphs, a solution using χ(G) colours will always be produced.) The overall complexity of the DSatur algorithm is O(n2), where n is the number of vertices in the graph. This can be achieved by performing n separate applications of an O(n) process that: Identifies the next vertex to colour according to DSatur’s selection rules. Colours this vertex. Below we present a C++ implementation of DSatur that operates in O((n + m) log n) time, where m is the number of edges in the graph. This is much faster than O(n2) for all but the densest of graphs. This implementation involves using a red-black binary tree to store all vertices that are not yet coloured, together with their saturation degrees and their degrees in the subgraph induced by the uncoloured vertices. Red-black trees are a type of self-balancing binary tree that are used with the set container in C++’s standard template library. This allows the selection of the next vertex to colour (according to DSatur’s selection rules) to be performed in constant time. It also allows items to be inserted and removed in logarithmic time. C++ // A C++ program to implement the DSatur algorithm for graph// coloring #include <iostream>#include <set>#include <tuple>#include <vector>using namespace std; // Struct to store information// on each uncoloured vertexstruct nodeInfo { int sat; // Saturation degree of the vertex int deg; // Degree in the uncoloured subgraph int vertex; // Index of vertex};struct maxSat { bool operator()(const nodeInfo& lhs, const nodeInfo& rhs) const { // Compares two nodes by // saturation degree, then // degree in the subgraph, // then vertex label return tie(lhs.sat, lhs.deg, lhs.vertex) > tie(rhs.sat, rhs.deg, rhs.vertex); }}; // Class representing// an undirected graphclass Graph { // Number of vertices int n; // Number of vertices vector<vector<int> > adj; public: // Constructor and destructor Graph(int numNodes) { n = numNodes; adj.resize(n, vector<int>()); } ~Graph() { adj.clear(); } // Function to add an edge to graph void addEdge(int u, int v); // Colour the graph // using the DSatur algorithm void DSatur();}; void Graph::addEdge(int u, int v){ adj[u].push_back(v); adj[v].push_back(u);} // Assigns colors (starting from 0)// to all vertices and// prints the assignment of colorsvoid Graph::DSatur(){ int u, i; vector<bool> used(n, false); vector<int> c(n), d(n); vector<set<int> > adjCols(n); set<nodeInfo, maxSat> Q; set<nodeInfo, maxSat>::iterator maxPtr; // Initialise the data structures. // These are a (binary // tree) priority queue, a set // of colours adjacent to // each uncoloured vertex // (initially empty) and the // degree d(v) of each uncoloured // vertex in the graph // induced by uncoloured vertices for (u = 0; u < n; u++) { c[u] = -1; d[u] = adj[u].size(); adjCols[u] = set<int>(); Q.emplace(nodeInfo{ 0, d[u], u }); } while (!Q.empty()) { // Choose the vertex u // with highest saturation // degree, breaking ties with d. // Remove u from the priority queue maxPtr = Q.begin(); u = (*maxPtr).vertex; Q.erase(maxPtr); // Identify the lowest feasible // colour i for vertex u for (int v : adj[u]) if (c[v] != -1) used] = true; for (i = 0; i < used.size(); i++) if (used[i] == false) break; for (int v : adj[u]) if (c[v] != -1) used] = false; // Assign vertex u to colour i c[u] = i; // Update the saturation degrees and // degrees of all uncoloured neighbours; // hence modify their corresponding // elements in the priority queue for (int v : adj[u]) { if (c[v] == -1) { Q.erase( { int(adjCols[v].size()), d[v], v }); adjCols[v].insert(i); d[v]--; Q.emplace(nodeInfo{ int(adjCols[v].size()), d[v], v }); } } } // The full graph has been coloured. // Print the result for (u = 0; u < n; u++) cout << "Vertex " << u << " ---> Color " << c[u] << endl;} // Driver Codeint main(){ Graph G1(5); G1.addEdge(0, 1); G1.addEdge(0, 2); G1.addEdge(1, 2); G1.addEdge(1, 3); G1.addEdge(2, 3); G1.addEdge(3, 4); cout << "Coloring of graph G1 \n"; G1.DSatur(); Graph G2(5); G2.addEdge(0, 1); G2.addEdge(0, 2); G2.addEdge(1, 2); G2.addEdge(1, 4); G2.addEdge(2, 4); G2.addEdge(4, 3); cout << "\nColoring of graph G2 \n"; G2.DSatur(); return 0;} Coloring of graph G1 Vertex 0 ---> Color 0 Vertex 1 ---> Color 2 Vertex 2 ---> Color 1 Vertex 3 ---> Color 0 Vertex 4 ---> Color 1 Coloring of graph G2 Vertex 0 ---> Color 0 Vertex 1 ---> Color 2 Vertex 2 ---> Color 1 Vertex 3 ---> Color 1 Vertex 4 ---> Color 0 The first part of this implementation involves initialising the data structures. This involves looping through each of the vertices and populating the red-black tree. This takes O(n log n) time. In the main part of the algorithm, the red-black tree allows the selection of the next vertex u to colour to be performed in constant time. Once u has been coloured, items corresponding to the uncoloured neighbours of u need to be updated in the red-black tree. Doing this for every vertex results in a total run time of O(m log n). Consequently, the overall run time is O((n log n) + (m log n)) = O((n+m) log n). Further information on this algorithm and others for graph colouring can be found in the book: A Guide to Graph Colouring: Algorithms and Applications (2021) rhydianlewis Binary Tree Graph Coloring Algorithms Combinatorial Graph Graph Combinatorial Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments DSA Sheet by Love Babbar Difference between Informed and Uninformed Search in AI SCAN (Elevator) Disk Scheduling Algorithms Quadratic Probing in Hashing K means Clustering - Introduction Write a program to print all permutations of a given string Permutation and Combination in Python itertools.combinations() module in Python to print all possible combinations Combinational Sum Count ways to reach the nth stair using step 1, 2 or 3
[ { "code": null, "e": 24301, "s": 24273, "text": "\n08 Nov, 2021" }, { "code": null, "e": 24386, "s": 24301, "text": "Graph colouring is the task of assigning colours to the vertices of a graph so that:" }, { "code": null, "e": 24449, "s": 24386, "text": "pairs of adjacent vertices are assigned different colours, and" }, { "code": null, "e": 24515, "s": 24449, "text": "the number of different colours used across the graph is minimal." }, { "code": null, "e": 24820, "s": 24515, "text": "The following graph has been coloured using just three colours (red, blue and green here). This is actually the minimum number of colours needed for this particular graph – that is, we cannot colour this graph using fewer than three colours while ensuring that adjacent vertices are coloured differently." }, { "code": null, "e": 24854, "s": 24820, "text": "Proper three-colouring of a graph" }, { "code": null, "e": 25145, "s": 24854, "text": "The minimum number of colours needed to colour a graph G is known as the chromatic number and is usually denoted by χ(G). Determining the chromatic number of a graph is NP-hard. The corresponding decision problem of deciding whether a k-colouring exists for a graph G is also NP-complete. " }, { "code": null, "e": 25547, "s": 25145, "text": "Similar posts on this website have already described the greedy algorithm for graph colouring. This algorithm is simple to apply, but the number of colours used in its solutions depends very much on the order that the vertices are considered. In the best case, the right ordering will produce a solution using χ(G) colours; however bad orderings can result in solutions using many additional colours. " }, { "code": null, "e": 26017, "s": 25547, "text": "The DSatur algorithm (abbreviated from “degree of saturation”) has similar behaviour to the Greedy algorithm. The difference lies in the way that it generates the vertex ordering. Specifically, the next vertex to colour is always chosen as the uncoloured vertex with the highest saturation degree. The saturation degree of a vertex is defined as the number of different colours currently assigned to neighbouring vertices. Other rules are also then used to break ties. " }, { "code": null, "e": 26234, "s": 26017, "text": "Let G be a graph with n vertices and m edges. In addition, assume that we will use the colour labels 0, 1, 2, ..., n-1. (More than n colours are never required in a solution). The DSatur algorithm operates as follows" }, { "code": null, "e": 26697, "s": 26234, "text": "Let v be the uncoloured vertex in G with the largest saturation degree. In cases of ties, choose the vertex among these with the largest degree in the subgraph induced by the uncoloured vertices. Further ties can be broken arbitrarily.Assign v to colour i, where i is the smallest integer from the set {0, 1, 2, ..., n} that is not currently assigned to any neighbour of v.If there remain uncoloured vertices, repeat all steps again, otherwise, end at this step." }, { "code": null, "e": 26933, "s": 26697, "text": "Let v be the uncoloured vertex in G with the largest saturation degree. In cases of ties, choose the vertex among these with the largest degree in the subgraph induced by the uncoloured vertices. Further ties can be broken arbitrarily." }, { "code": null, "e": 27072, "s": 26933, "text": "Assign v to colour i, where i is the smallest integer from the set {0, 1, 2, ..., n} that is not currently assigned to any neighbour of v." }, { "code": null, "e": 27162, "s": 27072, "text": "If there remain uncoloured vertices, repeat all steps again, otherwise, end at this step." }, { "code": null, "e": 27710, "s": 27162, "text": "The DSatur algorithm is similar to the Greedy algorithm in that once a vertex has been selected, it is assigned to the lowest colour label not assigned to any of its neighbours. The actions of Step 1, therefore, provide the main power behind the algorithm in that they prioritise vertices that are seen to be the “most constrained” – that is, vertices that currently have the fewest colour options available to them. Consequently, these “more constrained” vertices are dealt with first, allowing the less constrained vertices to be coloured later." }, { "code": null, "e": 27729, "s": 27710, "text": "Analysis of DSatur" }, { "code": null, "e": 28333, "s": 27729, "text": "Because the DSatur algorithm generates a vertex ordering during execution, the number of colours it uses is more predictable than the greedy algorithm. Its solutions also tend to have fewer colours than those of the greedy algorithm. One feature of the algorithm is that, if a graph is composed of multiple components, then all vertices of a single component will be coloured before the other vertices are considered. DSatur is also exact for several graph topologies including bipartite graphs, cycle graphs and wheel graphs. (With these graphs, a solution using χ(G) colours will always be produced.) " }, { "code": null, "e": 28522, "s": 28333, "text": "The overall complexity of the DSatur algorithm is O(n2), where n is the number of vertices in the graph. This can be achieved by performing n separate applications of an O(n) process that:" }, { "code": null, "e": 28598, "s": 28522, "text": "Identifies the next vertex to colour according to DSatur’s selection rules." }, { "code": null, "e": 28619, "s": 28598, "text": "Colours this vertex." }, { "code": null, "e": 29364, "s": 28619, "text": "Below we present a C++ implementation of DSatur that operates in O((n + m) log n) time, where m is the number of edges in the graph. This is much faster than O(n2) for all but the densest of graphs. This implementation involves using a red-black binary tree to store all vertices that are not yet coloured, together with their saturation degrees and their degrees in the subgraph induced by the uncoloured vertices. Red-black trees are a type of self-balancing binary tree that are used with the set container in C++’s standard template library. This allows the selection of the next vertex to colour (according to DSatur’s selection rules) to be performed in constant time. It also allows items to be inserted and removed in logarithmic time. " }, { "code": null, "e": 29368, "s": 29364, "text": "C++" }, { "code": "// A C++ program to implement the DSatur algorithm for graph// coloring #include <iostream>#include <set>#include <tuple>#include <vector>using namespace std; // Struct to store information// on each uncoloured vertexstruct nodeInfo { int sat; // Saturation degree of the vertex int deg; // Degree in the uncoloured subgraph int vertex; // Index of vertex};struct maxSat { bool operator()(const nodeInfo& lhs, const nodeInfo& rhs) const { // Compares two nodes by // saturation degree, then // degree in the subgraph, // then vertex label return tie(lhs.sat, lhs.deg, lhs.vertex) > tie(rhs.sat, rhs.deg, rhs.vertex); }}; // Class representing// an undirected graphclass Graph { // Number of vertices int n; // Number of vertices vector<vector<int> > adj; public: // Constructor and destructor Graph(int numNodes) { n = numNodes; adj.resize(n, vector<int>()); } ~Graph() { adj.clear(); } // Function to add an edge to graph void addEdge(int u, int v); // Colour the graph // using the DSatur algorithm void DSatur();}; void Graph::addEdge(int u, int v){ adj[u].push_back(v); adj[v].push_back(u);} // Assigns colors (starting from 0)// to all vertices and// prints the assignment of colorsvoid Graph::DSatur(){ int u, i; vector<bool> used(n, false); vector<int> c(n), d(n); vector<set<int> > adjCols(n); set<nodeInfo, maxSat> Q; set<nodeInfo, maxSat>::iterator maxPtr; // Initialise the data structures. // These are a (binary // tree) priority queue, a set // of colours adjacent to // each uncoloured vertex // (initially empty) and the // degree d(v) of each uncoloured // vertex in the graph // induced by uncoloured vertices for (u = 0; u < n; u++) { c[u] = -1; d[u] = adj[u].size(); adjCols[u] = set<int>(); Q.emplace(nodeInfo{ 0, d[u], u }); } while (!Q.empty()) { // Choose the vertex u // with highest saturation // degree, breaking ties with d. // Remove u from the priority queue maxPtr = Q.begin(); u = (*maxPtr).vertex; Q.erase(maxPtr); // Identify the lowest feasible // colour i for vertex u for (int v : adj[u]) if (c[v] != -1) used] = true; for (i = 0; i < used.size(); i++) if (used[i] == false) break; for (int v : adj[u]) if (c[v] != -1) used] = false; // Assign vertex u to colour i c[u] = i; // Update the saturation degrees and // degrees of all uncoloured neighbours; // hence modify their corresponding // elements in the priority queue for (int v : adj[u]) { if (c[v] == -1) { Q.erase( { int(adjCols[v].size()), d[v], v }); adjCols[v].insert(i); d[v]--; Q.emplace(nodeInfo{ int(adjCols[v].size()), d[v], v }); } } } // The full graph has been coloured. // Print the result for (u = 0; u < n; u++) cout << \"Vertex \" << u << \" ---> Color \" << c[u] << endl;} // Driver Codeint main(){ Graph G1(5); G1.addEdge(0, 1); G1.addEdge(0, 2); G1.addEdge(1, 2); G1.addEdge(1, 3); G1.addEdge(2, 3); G1.addEdge(3, 4); cout << \"Coloring of graph G1 \\n\"; G1.DSatur(); Graph G2(5); G2.addEdge(0, 1); G2.addEdge(0, 2); G2.addEdge(1, 2); G2.addEdge(1, 4); G2.addEdge(2, 4); G2.addEdge(4, 3); cout << \"\\nColoring of graph G2 \\n\"; G2.DSatur(); return 0;}", "e": 33147, "s": 29368, "text": null }, { "code": null, "e": 33422, "s": 33147, "text": "Coloring of graph G1 \nVertex 0 ---> Color 0\nVertex 1 ---> Color 2\nVertex 2 ---> Color 1\nVertex 3 ---> Color 0\nVertex 4 ---> Color 1\n\nColoring of graph G2 \nVertex 0 ---> Color 0\nVertex 1 ---> Color 2\nVertex 2 ---> Color 1\nVertex 3 ---> Color 1\nVertex 4 ---> Color 0" }, { "code": null, "e": 34031, "s": 33422, "text": "The first part of this implementation involves initialising the data structures. This involves looping through each of the vertices and populating the red-black tree. This takes O(n log n) time. In the main part of the algorithm, the red-black tree allows the selection of the next vertex u to colour to be performed in constant time. Once u has been coloured, items corresponding to the uncoloured neighbours of u need to be updated in the red-black tree. Doing this for every vertex results in a total run time of O(m log n). Consequently, the overall run time is O((n log n) + (m log n)) = O((n+m) log n)." }, { "code": null, "e": 34190, "s": 34031, "text": "Further information on this algorithm and others for graph colouring can be found in the book: A Guide to Graph Colouring: Algorithms and Applications (2021) " }, { "code": null, "e": 34203, "s": 34190, "text": "rhydianlewis" }, { "code": null, "e": 34215, "s": 34203, "text": "Binary Tree" }, { "code": null, "e": 34230, "s": 34215, "text": "Graph Coloring" }, { "code": null, "e": 34241, "s": 34230, "text": "Algorithms" }, { "code": null, "e": 34255, "s": 34241, "text": "Combinatorial" }, { "code": null, "e": 34261, "s": 34255, "text": "Graph" }, { "code": null, "e": 34267, "s": 34261, "text": "Graph" }, { "code": null, "e": 34281, "s": 34267, "text": "Combinatorial" }, { "code": null, "e": 34292, "s": 34281, "text": "Algorithms" }, { "code": null, "e": 34390, "s": 34292, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34399, "s": 34390, "text": "Comments" }, { "code": null, "e": 34412, "s": 34399, "text": "Old Comments" }, { "code": null, "e": 34437, "s": 34412, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 34493, "s": 34437, "text": "Difference between Informed and Uninformed Search in AI" }, { "code": null, "e": 34536, "s": 34493, "text": "SCAN (Elevator) Disk Scheduling Algorithms" }, { "code": null, "e": 34565, "s": 34536, "text": "Quadratic Probing in Hashing" }, { "code": null, "e": 34599, "s": 34565, "text": "K means Clustering - Introduction" }, { "code": null, "e": 34659, "s": 34599, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 34697, "s": 34659, "text": "Permutation and Combination in Python" }, { "code": null, "e": 34774, "s": 34697, "text": "itertools.combinations() module in Python to print all possible combinations" }, { "code": null, "e": 34792, "s": 34774, "text": "Combinational Sum" } ]
Reinforcement Learning: let’s teach a taxi-cab how to drive | by Valentina Alto | Towards Data Science
Reinforcement Learning is a subfield of Machine Learning whose tasks differ from ‘standard’ ways of learning. Indeed, rather than being provided with historical data and make predictions or inferences on them, you want your reinforcement algorithm to learn, from scratch, from the surrounding environment. Basically, you want it to behave as you would have done in a similar situation (if you want to learn more about the structure of RL, click here to read my former article). In this article, I’m going to show you how to implement an RL solution using Python and its library gym-OpenAI, which you can easily install by running on your Jupyter console pip install gym. The problem I’m going to present to you is the following: Your environment consists of a 5x5 matrix, where each cell is a position your taxi can stay at. Then, you have 4 coordinates which represent pick-up and drop-off locations, which are (0,0), (0,4), (4,0), (4,3) (for the sake of coherence with Python language, the first index is 0 rather than 1). We will refer to them as R,G,Y,B and we will index their location with, respectively, 0,1,2,3. Finally, there is one passenger which can be either picked up or dropped off, as well as being transported (hence spending time on the cab). Specifically, this passenger wants to reach point B. Now, if we import our gym module and initialize the taxi environment, we can see that it replicates what we have been saying so far: import gymenv = gym.make("Taxi-v2").envenv.render() As you can see, we have our 5x5 space with our 4 locations, where the blue letter represents the current passenger’s location, while the purple one is the drop-off location. We also have our taxi/agent in that space, which is the yellow rectangle, as well as some walls, represented by the symbol ‘|’. Now there are two elements which need our attention: states and actions. Let’s first examine our actions. According to the module imported, the agent can act in 6 ways: 0: going down (south) 1: going up (north) 2: going right (east) 3: going left (west) 4: picking up 5: dropping off Secondly, how many states do we have? Well, at least 25: indeed, having a 5x5 space, we know that the cab can simply occupy those cells. Furthermore, the taxi can be also in a state of picking up or dropping off the passenger (regardless of its being actually there: remember that the taxi will proceed by attempts), hence we have 4 more states. Finally, we have to compute those states where the passenger is actually picked up, dropped off (+ 4 states, since the locations where the passenger could be are 4) or simply transported (+ 1 state). So, in total, we have 5x5x4x5=500 states. Each state of our agent, which is represented by a vector of values [row of taxi, col of taxi, passenger index, destination index], is consequently encoded with a value between 0 and 499. Namely, we can replicate the location of our previous picture like so: state = env.encode(4, 2, 3, 2) print("State:", state)env.s = stateenv.render() As you can see, knowing that our taxi is in position (4,2) and that passenger’s index=3 and drop-off location=2, we can derive that the encoded state is 454. For the following experiment, we will use this starting point, but before diving into that, we need to introduce one last element: the rewarding system. The rewarding system is the main idea behind reinforcement learning: the agent is rewarded any time it acts well, otherwise it is ‘punished’ with a negative reward. In this specific case, an embedded rewarding table P is created as soon as the env is created. The logic is the following: if the taxi correctly pick-up/drop-off the passenger, it is rewarded with +20 points if the taxi does an illegal pick-up/drop-off, it is punished with -10 points for each step which does not include the states above, it loses 1 point So let’s see how it looks like for our state 454: env.P[454] The first thing to notice is that each entry of our P table is a dictionary with the structure {action: [(probability, nextstate, reward, done)]} Action: it ranges from 0 to 5 Probability: in this case, is always 1 Nextstate: it is the state which occurs if that action is done reward: the reward/penalty which is linked to that action done: if True, it means the episode it’s over, otherwise it is not. Let’s try to read our result: the first line is telling us that, if we go down (action 0=south), we will remain in the same position since we have a boundary, hence the reward is -1 and the episode is not over; the second line, which corresponds to the action=north, will bring our taxi towards the position 354, but the reward is always -1 and the episode is not over. The reasoning is the same for all the actions. Note that if the action is picking up or dropping off, since the taxi is not in the proper locations (R,Y,G,B), like in the last two lines (corresponding to actions 4 and 5) it receives a penalty of -10. Now it’s time to train our algorithm. The algorithm we are going to use is called Q-learning. I’ve already provided an explanation of the idea behind in this article, hence here I won’t dive any deeper. The procedure is explained by the following code: import random# setting yperparameterslr = 0.1 #learning rategamma = 0.6 #discount factorepsilon = 0.1 #trade-off between exploration and exploitationfor i in range(1, 1000): #we will see 1000 episodes state = env.reset() #let's reset our envepochs, penalties, reward, = 0, 0, 0 done = False while not done: if random.uniform(0, 1) < epsilon: action = env.action_space.sample() # explore action space else: action = np.argmax(q_table[state]) # exploit learned valuesnext_state, reward, done, info = env.step(action) old_value = q_table[state, action] next_max = np.max(q_table[next_state]) new_value = (1 - alpha) * old_value + lr * (reward + gamma * next_max) q_table[state, action] = new_valueif reward == -10: penalties += 1state = next_state epochs += 1 Now, imagine you have to decide which is the action which maximizes your utility (translated, which leads to the best way possible towards your passenger in position 3). Your answer will probably be north, hence action 1: indeed, it will be the fastest way to reach the location (4,3), where your passenger is located. What would say our algorithm? np.argmax(q_table[454]) #argmax function return the position of the #maximum value among those in the vector examined 1 As you can see, the argmax function return position 1, which corresponds to action ‘north’. So, for each position, our q-table will tell us which is the action which maximizes current and future rewards.
[ { "code": null, "e": 650, "s": 172, "text": "Reinforcement Learning is a subfield of Machine Learning whose tasks differ from ‘standard’ ways of learning. Indeed, rather than being provided with historical data and make predictions or inferences on them, you want your reinforcement algorithm to learn, from scratch, from the surrounding environment. Basically, you want it to behave as you would have done in a similar situation (if you want to learn more about the structure of RL, click here to read my former article)." }, { "code": null, "e": 901, "s": 650, "text": "In this article, I’m going to show you how to implement an RL solution using Python and its library gym-OpenAI, which you can easily install by running on your Jupyter console pip install gym. The problem I’m going to present to you is the following:" }, { "code": null, "e": 1486, "s": 901, "text": "Your environment consists of a 5x5 matrix, where each cell is a position your taxi can stay at. Then, you have 4 coordinates which represent pick-up and drop-off locations, which are (0,0), (0,4), (4,0), (4,3) (for the sake of coherence with Python language, the first index is 0 rather than 1). We will refer to them as R,G,Y,B and we will index their location with, respectively, 0,1,2,3. Finally, there is one passenger which can be either picked up or dropped off, as well as being transported (hence spending time on the cab). Specifically, this passenger wants to reach point B." }, { "code": null, "e": 1619, "s": 1486, "text": "Now, if we import our gym module and initialize the taxi environment, we can see that it replicates what we have been saying so far:" }, { "code": null, "e": 1671, "s": 1619, "text": "import gymenv = gym.make(\"Taxi-v2\").envenv.render()" }, { "code": null, "e": 1973, "s": 1671, "text": "As you can see, we have our 5x5 space with our 4 locations, where the blue letter represents the current passenger’s location, while the purple one is the drop-off location. We also have our taxi/agent in that space, which is the yellow rectangle, as well as some walls, represented by the symbol ‘|’." }, { "code": null, "e": 2046, "s": 1973, "text": "Now there are two elements which need our attention: states and actions." }, { "code": null, "e": 2142, "s": 2046, "text": "Let’s first examine our actions. According to the module imported, the agent can act in 6 ways:" }, { "code": null, "e": 2164, "s": 2142, "text": "0: going down (south)" }, { "code": null, "e": 2184, "s": 2164, "text": "1: going up (north)" }, { "code": null, "e": 2206, "s": 2184, "text": "2: going right (east)" }, { "code": null, "e": 2227, "s": 2206, "text": "3: going left (west)" }, { "code": null, "e": 2241, "s": 2227, "text": "4: picking up" }, { "code": null, "e": 2257, "s": 2241, "text": "5: dropping off" }, { "code": null, "e": 2845, "s": 2257, "text": "Secondly, how many states do we have? Well, at least 25: indeed, having a 5x5 space, we know that the cab can simply occupy those cells. Furthermore, the taxi can be also in a state of picking up or dropping off the passenger (regardless of its being actually there: remember that the taxi will proceed by attempts), hence we have 4 more states. Finally, we have to compute those states where the passenger is actually picked up, dropped off (+ 4 states, since the locations where the passenger could be are 4) or simply transported (+ 1 state). So, in total, we have 5x5x4x5=500 states." }, { "code": null, "e": 3104, "s": 2845, "text": "Each state of our agent, which is represented by a vector of values [row of taxi, col of taxi, passenger index, destination index], is consequently encoded with a value between 0 and 499. Namely, we can replicate the location of our previous picture like so:" }, { "code": null, "e": 3183, "s": 3104, "text": "state = env.encode(4, 2, 3, 2) print(\"State:\", state)env.s = stateenv.render()" }, { "code": null, "e": 3494, "s": 3183, "text": "As you can see, knowing that our taxi is in position (4,2) and that passenger’s index=3 and drop-off location=2, we can derive that the encoded state is 454. For the following experiment, we will use this starting point, but before diving into that, we need to introduce one last element: the rewarding system." }, { "code": null, "e": 3782, "s": 3494, "text": "The rewarding system is the main idea behind reinforcement learning: the agent is rewarded any time it acts well, otherwise it is ‘punished’ with a negative reward. In this specific case, an embedded rewarding table P is created as soon as the env is created. The logic is the following:" }, { "code": null, "e": 3867, "s": 3782, "text": "if the taxi correctly pick-up/drop-off the passenger, it is rewarded with +20 points" }, { "code": null, "e": 3944, "s": 3867, "text": "if the taxi does an illegal pick-up/drop-off, it is punished with -10 points" }, { "code": null, "e": 4016, "s": 3944, "text": "for each step which does not include the states above, it loses 1 point" }, { "code": null, "e": 4066, "s": 4016, "text": "So let’s see how it looks like for our state 454:" }, { "code": null, "e": 4077, "s": 4066, "text": "env.P[454]" }, { "code": null, "e": 4223, "s": 4077, "text": "The first thing to notice is that each entry of our P table is a dictionary with the structure {action: [(probability, nextstate, reward, done)]}" }, { "code": null, "e": 4253, "s": 4223, "text": "Action: it ranges from 0 to 5" }, { "code": null, "e": 4292, "s": 4253, "text": "Probability: in this case, is always 1" }, { "code": null, "e": 4355, "s": 4292, "text": "Nextstate: it is the state which occurs if that action is done" }, { "code": null, "e": 4413, "s": 4355, "text": "reward: the reward/penalty which is linked to that action" }, { "code": null, "e": 4481, "s": 4413, "text": "done: if True, it means the episode it’s over, otherwise it is not." }, { "code": null, "e": 5102, "s": 4481, "text": "Let’s try to read our result: the first line is telling us that, if we go down (action 0=south), we will remain in the same position since we have a boundary, hence the reward is -1 and the episode is not over; the second line, which corresponds to the action=north, will bring our taxi towards the position 354, but the reward is always -1 and the episode is not over. The reasoning is the same for all the actions. Note that if the action is picking up or dropping off, since the taxi is not in the proper locations (R,Y,G,B), like in the last two lines (corresponding to actions 4 and 5) it receives a penalty of -10." }, { "code": null, "e": 5305, "s": 5102, "text": "Now it’s time to train our algorithm. The algorithm we are going to use is called Q-learning. I’ve already provided an explanation of the idea behind in this article, hence here I won’t dive any deeper." }, { "code": null, "e": 5355, "s": 5305, "text": "The procedure is explained by the following code:" }, { "code": null, "e": 6235, "s": 5355, "text": "import random# setting yperparameterslr = 0.1 #learning rategamma = 0.6 #discount factorepsilon = 0.1 #trade-off between exploration and exploitationfor i in range(1, 1000): #we will see 1000 episodes state = env.reset() #let's reset our envepochs, penalties, reward, = 0, 0, 0 done = False while not done: if random.uniform(0, 1) < epsilon: action = env.action_space.sample() # explore action space else: action = np.argmax(q_table[state]) # exploit learned valuesnext_state, reward, done, info = env.step(action) old_value = q_table[state, action] next_max = np.max(q_table[next_state]) new_value = (1 - alpha) * old_value + lr * (reward + gamma * next_max) q_table[state, action] = new_valueif reward == -10: penalties += 1state = next_state epochs += 1 " }, { "code": null, "e": 6584, "s": 6235, "text": "Now, imagine you have to decide which is the action which maximizes your utility (translated, which leads to the best way possible towards your passenger in position 3). Your answer will probably be north, hence action 1: indeed, it will be the fastest way to reach the location (4,3), where your passenger is located. What would say our algorithm?" }, { "code": null, "e": 6702, "s": 6584, "text": "np.argmax(q_table[454]) #argmax function return the position of the #maximum value among those in the vector examined" }, { "code": null, "e": 6704, "s": 6702, "text": "1" } ]
Scikit Learn - Dimensionality Reduction using PCA
Dimensionality reduction, an unsupervised machine learning method is used to reduce the number of feature variables for each data sample selecting set of principal features. Principal Component Analysis (PCA) is one of the popular algorithms for dimensionality reduction. Principal Component Analysis (PCA) is used for linear dimensionality reduction using Singular Value Decomposition (SVD) of the data to project it to a lower dimensional space. While decomposition using PCA, input data is centered but not scaled for each feature before applying the SVD. The Scikit-learn ML library provides sklearn.decomposition.PCA module that is implemented as a transformer object which learns n components in its fit() method. It can also be used on new data to project it on these components. The below example will use sklearn.decomposition.PCA module to find best 5 Principal components from Pima Indians Diabetes dataset. from pandas import read_csv from sklearn.decomposition import PCA path = r'C:\Users\Leekha\Desktop\pima-indians-diabetes.csv' names = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', ‘class'] dataframe = read_csv(path, names = names) array = dataframe.values X = array[:,0:8] Y = array[:,8] pca = PCA(n_components = 5) fit = pca.fit(X) print(("Explained Variance: %s") % (fit.explained_variance_ratio_)) print(fit.components_) Explained Variance: [0.88854663 0.06159078 0.02579012 0.01308614 0.00744094] [ [-2.02176587e-03 9.78115765e-02 1.60930503e-02 6.07566861e-029.93110844e-01 1.40108085e-02 5.37167919e-04 -3.56474430e-03] [-2.26488861e-02 -9.72210040e-01 -1.41909330e-01 5.78614699e-029.46266913e-02 -4.69729766e-02 -8.16804621e-04 -1.40168181e-01] [-2.24649003e-02 1.43428710e-01 -9.22467192e-01 -3.07013055e-012.09773019e-02 -1.32444542e-01 -6.39983017e-04 -1.25454310e-01] [-4.90459604e-02 1.19830016e-01 -2.62742788e-01 8.84369380e-01-6.55503615e-02 1.92801728e-01 2.69908637e-03 -3.01024330e-01] [ 1.51612874e-01 -8.79407680e-02 -2.32165009e-01 2.59973487e-01-1.72312241e-04 2.14744823e-02 1.64080684e-03 9.20504903e-01] ] Incremental Principal Component Analysis (IPCA) is used to address the biggest limitation of Principal Component Analysis (PCA) and that is PCA only supports batch processing, means all the input data to be processed should fit in the memory. The Scikit-learn ML library provides sklearn.decomposition.IPCA module that makes it possible to implement Out-of-Core PCA either by using its partial_fit method on sequentially fetched chunks of data or by enabling use of np.memmap, a memory mapped file, without loading the entire file into memory. Same as PCA, while decomposition using IPCA, input data is centered but not scaled for each feature before applying the SVD. The below example will use sklearn.decomposition.IPCA module on Sklearn digit dataset. from sklearn.datasets import load_digits from sklearn.decomposition import IncrementalPCA X, _ = load_digits(return_X_y = True) transformer = IncrementalPCA(n_components = 10, batch_size = 100) transformer.partial_fit(X[:100, :]) X_transformed = transformer.fit_transform(X) X_transformed.shape (1797, 10) Here, we can partially fit on smaller batches of data (as we did on 100 per batch) or you can let the fit() function to divide the data into batches. Kernel Principal Component Analysis, an extension of PCA, achieves non-linear dimensionality reduction using kernels. It supports both transform and inverse_transform. The Scikit-learn ML library provides sklearn.decomposition.KernelPCA module. The below example will use sklearn.decomposition.KernelPCA module on Sklearn digit dataset. We are using sigmoid kernel. from sklearn.datasets import load_digits from sklearn.decomposition import KernelPCA X, _ = load_digits(return_X_y = True) transformer = KernelPCA(n_components = 10, kernel = 'sigmoid') X_transformed = transformer.fit_transform(X) X_transformed.shape (1797, 10) Principal Component Analysis (PCA) using randomized SVD is used to project data to a lower-dimensional space preserving most of the variance by dropping the singular vector of components associated with lower singular values. Here, the sklearn.decomposition.PCA module with the optional parameter svd_solver=’randomized’ is going to be very useful. The below example will use sklearn.decomposition.PCA module with the optional parameter svd_solver=’randomized’ to find best 7 Principal components from Pima Indians Diabetes dataset. from pandas import read_csv from sklearn.decomposition import PCA path = r'C:\Users\Leekha\Desktop\pima-indians-diabetes.csv' names = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class'] dataframe = read_csv(path, names = names) array = dataframe.values X = array[:,0:8] Y = array[:,8] pca = PCA(n_components = 7,svd_solver = 'randomized') fit = pca.fit(X) print(("Explained Variance: %s") % (fit.explained_variance_ratio_)) print(fit.components_) Explained Variance: [8.88546635e-01 6.15907837e-02 2.57901189e-02 1.30861374e-027.44093864e-03 3.02614919e-03 5.12444875e-04] [ [-2.02176587e-03 9.78115765e-02 1.60930503e-02 6.07566861e-029.93110844e-01 1.40108085e-02 5.37167919e-04 -3.56474430e-03] [-2.26488861e-02 -9.72210040e-01 -1.41909330e-01 5.78614699e-029.46266913e-02 -4.69729766e-02 -8.16804621e-04 -1.40168181e-01] [-2.24649003e-02 1.43428710e-01 -9.22467192e-01 -3.07013055e-012.09773019e-02 -1.32444542e-01 -6.39983017e-04 -1.25454310e-01] [-4.90459604e-02 1.19830016e-01 -2.62742788e-01 8.84369380e-01-6.55503615e-02 1.92801728e-01 2.69908637e-03 -3.01024330e-01] [ 1.51612874e-01 -8.79407680e-02 -2.32165009e-01 2.59973487e-01-1.72312241e-04 2.14744823e-02 1.64080684e-03 9.20504903e-01] [-5.04730888e-03 5.07391813e-02 7.56365525e-02 2.21363068e-01-6.13326472e-03 -9.70776708e-01 -2.02903702e-03 -1.51133239e-02] [ 9.86672995e-01 8.83426114e-04 -1.22975947e-03 -3.76444746e-041.42307394e-03 -2.73046214e-03 -6.34402965e-03 -1.62555343e-01] ] 11 Lectures 2 hours PARTHA MAJUMDAR Print Add Notes Bookmark this page
[ { "code": null, "e": 2493, "s": 2221, "text": "Dimensionality reduction, an unsupervised machine learning method is used to reduce the number of feature variables for each data sample selecting set of principal features. Principal Component Analysis (PCA) is one of the popular algorithms for dimensionality reduction." }, { "code": null, "e": 2780, "s": 2493, "text": "Principal Component Analysis (PCA) is used for linear dimensionality reduction using Singular Value Decomposition (SVD) of the data to project it to a lower dimensional space. While decomposition using PCA, input data is centered but not scaled for each feature before applying the SVD." }, { "code": null, "e": 3008, "s": 2780, "text": "The Scikit-learn ML library provides sklearn.decomposition.PCA module that is implemented as a transformer object which learns n components in its fit() method. It can also be used on new data to project it on these components." }, { "code": null, "e": 3140, "s": 3008, "text": "The below example will use sklearn.decomposition.PCA module to find best 5 Principal components from Pima Indians Diabetes dataset." }, { "code": null, "e": 3582, "s": 3140, "text": "from pandas import read_csv\nfrom sklearn.decomposition import PCA\npath = r'C:\\Users\\Leekha\\Desktop\\pima-indians-diabetes.csv'\nnames = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', ‘class']\ndataframe = read_csv(path, names = names)\narray = dataframe.values\nX = array[:,0:8]\nY = array[:,8]\npca = PCA(n_components = 5)\nfit = pca.fit(X)\nprint((\"Explained Variance: %s\") % (fit.explained_variance_ratio_))\nprint(fit.components_)" }, { "code": null, "e": 4306, "s": 3582, "text": "Explained Variance: [0.88854663 0.06159078 0.02579012 0.01308614 0.00744094]\n[\n [-2.02176587e-03 9.78115765e-02 1.60930503e-02 6.07566861e-029.93110844e-01 1.40108085e-02 5.37167919e-04 -3.56474430e-03]\n [-2.26488861e-02 -9.72210040e-01 -1.41909330e-01 5.78614699e-029.46266913e-02 -4.69729766e-02 -8.16804621e-04 -1.40168181e-01]\n [-2.24649003e-02 1.43428710e-01 -9.22467192e-01 -3.07013055e-012.09773019e-02 -1.32444542e-01 -6.39983017e-04 -1.25454310e-01]\n [-4.90459604e-02 1.19830016e-01 -2.62742788e-01 8.84369380e-01-6.55503615e-02 1.92801728e-01 2.69908637e-03 -3.01024330e-01]\n [ 1.51612874e-01 -8.79407680e-02 -2.32165009e-01 2.59973487e-01-1.72312241e-04 2.14744823e-02 1.64080684e-03 9.20504903e-01]\n]\n" }, { "code": null, "e": 4549, "s": 4306, "text": "Incremental Principal Component Analysis (IPCA) is used to address the biggest limitation of Principal Component Analysis (PCA) and that is PCA only supports batch processing, means all the input data to be processed should fit in the memory." }, { "code": null, "e": 4850, "s": 4549, "text": "The Scikit-learn ML library provides sklearn.decomposition.IPCA module that makes it possible to implement Out-of-Core PCA either by using its partial_fit method on sequentially fetched chunks of data or by enabling use of np.memmap, a memory mapped file, without loading the entire file into memory." }, { "code": null, "e": 4975, "s": 4850, "text": "Same as PCA, while decomposition using IPCA, input data is centered but not scaled for each feature before applying the SVD." }, { "code": null, "e": 5062, "s": 4975, "text": "The below example will use sklearn.decomposition.IPCA module on Sklearn digit dataset." }, { "code": null, "e": 5357, "s": 5062, "text": "from sklearn.datasets import load_digits\nfrom sklearn.decomposition import IncrementalPCA\nX, _ = load_digits(return_X_y = True)\ntransformer = IncrementalPCA(n_components = 10, batch_size = 100)\ntransformer.partial_fit(X[:100, :])\nX_transformed = transformer.fit_transform(X)\nX_transformed.shape" }, { "code": null, "e": 5369, "s": 5357, "text": "(1797, 10)\n" }, { "code": null, "e": 5519, "s": 5369, "text": "Here, we can partially fit on smaller batches of data (as we did on 100 per batch) or you can let the fit() function to divide the data into batches." }, { "code": null, "e": 5687, "s": 5519, "text": "Kernel Principal Component Analysis, an extension of PCA, achieves non-linear dimensionality reduction using kernels. It supports both transform and inverse_transform." }, { "code": null, "e": 5764, "s": 5687, "text": "The Scikit-learn ML library provides sklearn.decomposition.KernelPCA module." }, { "code": null, "e": 5885, "s": 5764, "text": "The below example will use sklearn.decomposition.KernelPCA module on Sklearn digit dataset. We are using sigmoid kernel." }, { "code": null, "e": 6136, "s": 5885, "text": "from sklearn.datasets import load_digits\nfrom sklearn.decomposition import KernelPCA\nX, _ = load_digits(return_X_y = True)\ntransformer = KernelPCA(n_components = 10, kernel = 'sigmoid')\nX_transformed = transformer.fit_transform(X)\nX_transformed.shape" }, { "code": null, "e": 6148, "s": 6136, "text": "(1797, 10)\n" }, { "code": null, "e": 6497, "s": 6148, "text": "Principal Component Analysis (PCA) using randomized SVD is used to project data to a lower-dimensional space preserving most of the variance by dropping the singular vector of components associated with lower singular values. Here, the sklearn.decomposition.PCA module with the optional parameter svd_solver=’randomized’ is going to be very useful." }, { "code": null, "e": 6681, "s": 6497, "text": "The below example will use sklearn.decomposition.PCA module with the optional parameter svd_solver=’randomized’ to find best 7 Principal components from Pima Indians Diabetes dataset." }, { "code": null, "e": 7149, "s": 6681, "text": "from pandas import read_csv\nfrom sklearn.decomposition import PCA\npath = r'C:\\Users\\Leekha\\Desktop\\pima-indians-diabetes.csv'\nnames = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class']\ndataframe = read_csv(path, names = names)\narray = dataframe.values\nX = array[:,0:8]\nY = array[:,8]\npca = PCA(n_components = 7,svd_solver = 'randomized')\nfit = pca.fit(X)\nprint((\"Explained Variance: %s\") % (fit.explained_variance_ratio_))\nprint(fit.components_)" }, { "code": null, "e": 8181, "s": 7149, "text": "Explained Variance: [8.88546635e-01 6.15907837e-02 2.57901189e-02 1.30861374e-027.44093864e-03 3.02614919e-03 5.12444875e-04]\n[\n [-2.02176587e-03 9.78115765e-02 1.60930503e-02 6.07566861e-029.93110844e-01 1.40108085e-02 5.37167919e-04 -3.56474430e-03]\n [-2.26488861e-02 -9.72210040e-01 -1.41909330e-01 5.78614699e-029.46266913e-02 -4.69729766e-02 -8.16804621e-04 -1.40168181e-01]\n [-2.24649003e-02 1.43428710e-01 -9.22467192e-01 -3.07013055e-012.09773019e-02 -1.32444542e-01 -6.39983017e-04 -1.25454310e-01]\n [-4.90459604e-02 1.19830016e-01 -2.62742788e-01 8.84369380e-01-6.55503615e-02 1.92801728e-01 2.69908637e-03 -3.01024330e-01]\n [ 1.51612874e-01 -8.79407680e-02 -2.32165009e-01 2.59973487e-01-1.72312241e-04 2.14744823e-02 1.64080684e-03 9.20504903e-01]\n [-5.04730888e-03 5.07391813e-02 7.56365525e-02 2.21363068e-01-6.13326472e-03 -9.70776708e-01 -2.02903702e-03 -1.51133239e-02]\n [ 9.86672995e-01 8.83426114e-04 -1.22975947e-03 -3.76444746e-041.42307394e-03 -2.73046214e-03 -6.34402965e-03 -1.62555343e-01]\n]\n" }, { "code": null, "e": 8214, "s": 8181, "text": "\n 11 Lectures \n 2 hours \n" }, { "code": null, "e": 8231, "s": 8214, "text": " PARTHA MAJUMDAR" }, { "code": null, "e": 8238, "s": 8231, "text": " Print" }, { "code": null, "e": 8249, "s": 8238, "text": " Add Notes" } ]
Round off a number to the next multiple of 5 using JavaScript - GeeksforGeeks
27 Aug, 2019 Given a positive integer n and the task is to round the number to the next whole number having divisible by 5. Examples: Input : 46 Output : 50 Input : 21 Output : 25 Input : 30 Output : 30 Approach 1: Take the number in a variable. Divide it by 5 and get the decimal value. Take the ceil value of the decimal value by using math.ceil(). Multiply it by 5 to get the result. <script> function round(x) { return Math.ceil(x / 5) * 5; } var n = 34;console.log(round(n)); </script> Output: 35 Approach 2: Take the number in a variable. If it is divisible by 5, return the same number. Else divide it by 5, take floor value and again multiply it by 5 and add 5 as well. <script> function round(x) { if (x % 5 == 0) { return int(Math.floor(x / 5)) * 5; } else { return (int(Math.floor(x / 5)) * 5) + 5; } } var n = 34;console.log(round(n)); </script> Output: 35 javascript-math JavaScript-Misc JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Convert a string to an integer in JavaScript 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 Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 37914, "s": 37886, "text": "\n27 Aug, 2019" }, { "code": null, "e": 38025, "s": 37914, "text": "Given a positive integer n and the task is to round the number to the next whole number having divisible by 5." }, { "code": null, "e": 38035, "s": 38025, "text": "Examples:" }, { "code": null, "e": 38109, "s": 38035, "text": "Input : 46 \nOutput : 50\n\nInput : 21\nOutput : 25\n\nInput : 30 \nOutput : 30\n" }, { "code": null, "e": 38121, "s": 38109, "text": "Approach 1:" }, { "code": null, "e": 38152, "s": 38121, "text": "Take the number in a variable." }, { "code": null, "e": 38194, "s": 38152, "text": "Divide it by 5 and get the decimal value." }, { "code": null, "e": 38257, "s": 38194, "text": "Take the ceil value of the decimal value by using math.ceil()." }, { "code": null, "e": 38293, "s": 38257, "text": "Multiply it by 5 to get the result." }, { "code": "<script> function round(x) { return Math.ceil(x / 5) * 5; } var n = 34;console.log(round(n)); </script>", "e": 38411, "s": 38293, "text": null }, { "code": null, "e": 38419, "s": 38411, "text": "Output:" }, { "code": null, "e": 38423, "s": 38419, "text": "35\n" }, { "code": null, "e": 38435, "s": 38423, "text": "Approach 2:" }, { "code": null, "e": 38466, "s": 38435, "text": "Take the number in a variable." }, { "code": null, "e": 38515, "s": 38466, "text": "If it is divisible by 5, return the same number." }, { "code": null, "e": 38599, "s": 38515, "text": "Else divide it by 5, take floor value and again multiply it by 5 and add 5 as well." }, { "code": "<script> function round(x) { if (x % 5 == 0) { return int(Math.floor(x / 5)) * 5; } else { return (int(Math.floor(x / 5)) * 5) + 5; } } var n = 34;console.log(round(n)); </script>", "e": 38829, "s": 38599, "text": null }, { "code": null, "e": 38837, "s": 38829, "text": "Output:" }, { "code": null, "e": 38841, "s": 38837, "text": "35\n" }, { "code": null, "e": 38857, "s": 38841, "text": "javascript-math" }, { "code": null, "e": 38873, "s": 38857, "text": "JavaScript-Misc" }, { "code": null, "e": 38884, "s": 38873, "text": "JavaScript" }, { "code": null, "e": 38901, "s": 38884, "text": "Web Technologies" }, { "code": null, "e": 38928, "s": 38901, "text": "Web technologies Questions" }, { "code": null, "e": 39026, "s": 38928, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39035, "s": 39026, "text": "Comments" }, { "code": null, "e": 39048, "s": 39035, "text": "Old Comments" }, { "code": null, "e": 39093, "s": 39048, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 39162, "s": 39093, "text": "How to calculate the number of days between two dates in javascript?" }, { "code": null, "e": 39223, "s": 39162, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 39295, "s": 39223, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 39322, "s": 39295, "text": "File uploading in React.js" }, { "code": null, "e": 39364, "s": 39322, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 39397, "s": 39364, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 39459, "s": 39397, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 39502, "s": 39459, "text": "How to fetch data from an API in ReactJS ?" } ]
Wrap Around Concept and TCP Sequence Number
23 Jun, 2022 Prerequisite – TCP | Services and Segment structure Transmission Control Protocol (TCP) is one of the most important protocols of the internet protocol. It provides full transport-layer service to applications and generates a virtual circuit between sender and receiver that is active for the duration of the transmission. Its segment consists of a TCP header, TCP options, and the data that the segment transports. Sequence Numbers – The 32-bit sequence number field defines the number assigned to the first byte of data contained in this segment. TCP is a stream transport protocol. To ensure connectivity, each byte to be transmitted is numbered. During connection establishment, each party uses a Random number generator to create an initial sequence number (ISN), which is usually different in each direction. We know that a TCP sequence number is 32 bit. So it has finite (from 0 to (232-1) = 4 Giga sequence numbers) and it means we will be able to send only 4GB of data with a unique sequence number not more than that. It helps with the allocation of a sequence number that does not conflict with other data bytes transmitted over a TCP connection. An ISN is unique to each connection and separated by each device. Wrap Around Concept – It can happen at a high rate of traffic, all the sequence numbers got used up. The sequence number for every packet has to be unique, but since it is finite (4 Giga) at some point in time the Sequence number is completely consumed up. The sequence numbers which were used, when available can be used again as per requirement and this reusing of sequence numbers is known as Wraparound concept. In simple words “Using the sequence numbers again and again once all of them got used up, in order to maintain the continuity of data transfer ” is called Wrap around the concept. This helps to send more and more data without worrying about how much data is to be sent. As the sequence numbers can be used again and again, so there is no limit on the quantity of data. When and how wrap around is implemented? For example, if I am downloading software of size 4GB+ 2 bytes, but the sequence number available is only 4GB the rest two-byte won’t get any sequence number. In this kind of cases, the sequence numbers are wrapped, i.e., they are used again and again as per the requirement. This wrapping is affected by the random initial sequence number. We may get a lesser number of the sequence number in the beginning but after all sequence number is consumed again the sequence number will start from 0. From wherever we start using sequence numbers we will get 232 sequence numbers. Hence we can say that reusing a sequence number as per the requirement is the wrap concept of the TCP sequence number. Now if we have a wrap concept then a new concept comes, i.e., Wrap Around Time which depends on wrap-around sequence numbers. Wrap Around Time – Time taken to wrap around is called wrap-around time. It means if we start from sequence number 0 (or it may be anything), after how much time we are going to again use this same sequence number. Wrap around time is the time taken to start reusing the same sequence number also it can be said that the time taken to repeat the sequence number is as per the requirement. Wrap-around time depends on the sequence numbers and bandwidth. As the bandwidth is the rate of bits at which bits (sequence number) are consumed. The faster is the consumption rate, the faster is the consumption of sequence numbers. Wrap Around Time = (Total sequence number) / (Bandwidth) = (232) / (Bandwidth) Why is Wrap Around possible? There is a concept termed as Life Time, in the worst case a packet will require 3 minutes (180sec) to reach the destination (i.e., the lifetime of the packet). In today’s technology, the same sequence number will be available after 180 sec but we are not going to use it before wrap-around time. As long as Wrap Around Time > Life Time of a packet there will be no problem in using the same sequence number. After wrap-around the time the lifetime of the segments finishes, which means in that very time, a timeout occurs. After all sequence numbers are used and their lifetime finishes there is no harm in using the same sequence number again. Reducing Wrap Around Time – If the total number of bits to be consumed is equal to the sequence number then there will be no need to wrap around the sequence number. But this is not possible and we are going to use wrap-around concept. Since wrap-around time is directly dependent on a number of the Sequence numbers and inversely dependent on Bandwidth (Rate at which data will flow). More the Sequence numbers available, higher will be wrap-around time. Lesser the bandwidth, the higher the wrap-around time. So in order to reduce the wrap-around time, we need to: Reduce the sequence numbers or Increase the bandwidth (possible) Reduce the sequence numbers or Increase the bandwidth (possible) Example-1: Given n bits how many sequence numbers are possible? Explanation – For 1 bit, 2 numbers are possible, i.e., 0 and 1 For 2 bits, 4 numbers are possible, i.e., 00, 01, 10, 11 for 3 bits 8 numbers are possible, i.e., 000, 001, 010, 011, 100, 101, 110, 111 .. and so on for n bits 2^n numbers are possible i.e., from 0 to 2n-1 (in binary). Example-2: Given n number of sequence numbers how many bits are required to represent the set? Explanation – Let us need x number of bits, we know that 2x = n => x log(2) = log(n) We will have, => x = log(n) Taking base 2 of given logs. Example-3: Bandwidth of channel is given as 1 GBps. How long can a packet stay in the link without worrying about the problem of having 2 packets with the same sequence numbers? Explanation – Bandwidth = 1 GBps = 230 Sequence numbers = 232 So, Wrap around time: = Sequence number/Bandwidth =232 / 230 =22 =4 seconds Example-4: GATE-CS-2014-(Set-3) | Question 65 Example-5: GATE CS 2018 | Question 32 Bhumika_Rani Stark17 niharikatanwar61 krishna_97 Picked Technical Scripter 2018 Computer Networks GATE CS Technical Scripter Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GSM in Wireless Communication Secure Socket Layer (SSL) Wireless Application Protocol Mobile Internet Protocol (or Mobile IP) Advanced Encryption Standard (AES) ACID Properties in DBMS Types of Operating Systems Normal Forms in DBMS Page Replacement Algorithms in Operating Systems Inter Process Communication (IPC)
[ { "code": null, "e": 54, "s": 26, "text": "\n23 Jun, 2022" }, { "code": null, "e": 471, "s": 54, "text": "Prerequisite – TCP | Services and Segment structure Transmission Control Protocol (TCP) is one of the most important protocols of the internet protocol. It provides full transport-layer service to applications and generates a virtual circuit between sender and receiver that is active for the duration of the transmission. Its segment consists of a TCP header, TCP options, and the data that the segment transports. " }, { "code": null, "e": 1280, "s": 471, "text": "Sequence Numbers – The 32-bit sequence number field defines the number assigned to the first byte of data contained in this segment. TCP is a stream transport protocol. To ensure connectivity, each byte to be transmitted is numbered. During connection establishment, each party uses a Random number generator to create an initial sequence number (ISN), which is usually different in each direction. We know that a TCP sequence number is 32 bit. So it has finite (from 0 to (232-1) = 4 Giga sequence numbers) and it means we will be able to send only 4GB of data with a unique sequence number not more than that. It helps with the allocation of a sequence number that does not conflict with other data bytes transmitted over a TCP connection. An ISN is unique to each connection and separated by each device. " }, { "code": null, "e": 1697, "s": 1280, "text": "Wrap Around Concept – It can happen at a high rate of traffic, all the sequence numbers got used up. The sequence number for every packet has to be unique, but since it is finite (4 Giga) at some point in time the Sequence number is completely consumed up. The sequence numbers which were used, when available can be used again as per requirement and this reusing of sequence numbers is known as Wraparound concept. " }, { "code": null, "e": 2067, "s": 1697, "text": "In simple words “Using the sequence numbers again and again once all of them got used up, in order to maintain the continuity of data transfer ” is called Wrap around the concept. This helps to send more and more data without worrying about how much data is to be sent. As the sequence numbers can be used again and again, so there is no limit on the quantity of data. " }, { "code": null, "e": 2604, "s": 2067, "text": "When and how wrap around is implemented? For example, if I am downloading software of size 4GB+ 2 bytes, but the sequence number available is only 4GB the rest two-byte won’t get any sequence number. In this kind of cases, the sequence numbers are wrapped, i.e., they are used again and again as per the requirement. This wrapping is affected by the random initial sequence number. We may get a lesser number of the sequence number in the beginning but after all sequence number is consumed again the sequence number will start from 0. " }, { "code": null, "e": 2930, "s": 2604, "text": "From wherever we start using sequence numbers we will get 232 sequence numbers. Hence we can say that reusing a sequence number as per the requirement is the wrap concept of the TCP sequence number. Now if we have a wrap concept then a new concept comes, i.e., Wrap Around Time which depends on wrap-around sequence numbers. " }, { "code": null, "e": 3554, "s": 2930, "text": "Wrap Around Time – Time taken to wrap around is called wrap-around time. It means if we start from sequence number 0 (or it may be anything), after how much time we are going to again use this same sequence number. Wrap around time is the time taken to start reusing the same sequence number also it can be said that the time taken to repeat the sequence number is as per the requirement. Wrap-around time depends on the sequence numbers and bandwidth. As the bandwidth is the rate of bits at which bits (sequence number) are consumed. The faster is the consumption rate, the faster is the consumption of sequence numbers. " }, { "code": null, "e": 3636, "s": 3556, "text": "Wrap Around Time\n= (Total sequence number) / (Bandwidth)\n= (232) / (Bandwidth) " }, { "code": null, "e": 4311, "s": 3636, "text": "Why is Wrap Around possible? There is a concept termed as Life Time, in the worst case a packet will require 3 minutes (180sec) to reach the destination (i.e., the lifetime of the packet). In today’s technology, the same sequence number will be available after 180 sec but we are not going to use it before wrap-around time. As long as Wrap Around Time > Life Time of a packet there will be no problem in using the same sequence number. After wrap-around the time the lifetime of the segments finishes, which means in that very time, a timeout occurs. After all sequence numbers are used and their lifetime finishes there is no harm in using the same sequence number again. " }, { "code": null, "e": 4698, "s": 4311, "text": "Reducing Wrap Around Time – If the total number of bits to be consumed is equal to the sequence number then there will be no need to wrap around the sequence number. But this is not possible and we are going to use wrap-around concept. Since wrap-around time is directly dependent on a number of the Sequence numbers and inversely dependent on Bandwidth (Rate at which data will flow). " }, { "code": null, "e": 4881, "s": 4698, "text": "More the Sequence numbers available, higher will be wrap-around time. Lesser the bandwidth, the higher the wrap-around time. So in order to reduce the wrap-around time, we need to: " }, { "code": null, "e": 4949, "s": 4881, "text": "Reduce the sequence numbers or Increase the bandwidth (possible) " }, { "code": null, "e": 4982, "s": 4949, "text": "Reduce the sequence numbers or " }, { "code": null, "e": 5018, "s": 4982, "text": "Increase the bandwidth (possible) " }, { "code": null, "e": 5366, "s": 5018, "text": "Example-1: Given n bits how many sequence numbers are possible? Explanation – For 1 bit, 2 numbers are possible, i.e., 0 and 1 For 2 bits, 4 numbers are possible, i.e., 00, 01, 10, 11 for 3 bits 8 numbers are possible, i.e., 000, 001, 010, 011, 100, 101, 110, 111 .. and so on for n bits 2^n numbers are possible i.e., from 0 to 2n-1 (in binary). " }, { "code": null, "e": 5527, "s": 5366, "text": "Example-2: Given n number of sequence numbers how many bits are required to represent the set? Explanation – Let us need x number of bits, we know that 2x = n " }, { "code": null, "e": 5549, "s": 5527, "text": "=> x log(2) = log(n) " }, { "code": null, "e": 5565, "s": 5549, "text": "We will have, " }, { "code": null, "e": 5580, "s": 5565, "text": "=> x = log(n) " }, { "code": null, "e": 5610, "s": 5580, "text": "Taking base 2 of given logs. " }, { "code": null, "e": 5804, "s": 5610, "text": "Example-3: Bandwidth of channel is given as 1 GBps. How long can a packet stay in the link without worrying about the problem of having 2 packets with the same sequence numbers? Explanation – " }, { "code": null, "e": 5932, "s": 5804, "text": "Bandwidth = 1 GBps = 230 \nSequence numbers = 232\n\nSo, Wrap around time: \n= Sequence number/Bandwidth\n=232 / 230\n=22\n=4 seconds " }, { "code": null, "e": 5979, "s": 5932, "text": "Example-4: GATE-CS-2014-(Set-3) | Question 65 " }, { "code": null, "e": 6018, "s": 5979, "text": "Example-5: GATE CS 2018 | Question 32 " }, { "code": null, "e": 6031, "s": 6018, "text": "Bhumika_Rani" }, { "code": null, "e": 6039, "s": 6031, "text": "Stark17" }, { "code": null, "e": 6056, "s": 6039, "text": "niharikatanwar61" }, { "code": null, "e": 6067, "s": 6056, "text": "krishna_97" }, { "code": null, "e": 6074, "s": 6067, "text": "Picked" }, { "code": null, "e": 6098, "s": 6074, "text": "Technical Scripter 2018" }, { "code": null, "e": 6116, "s": 6098, "text": "Computer Networks" }, { "code": null, "e": 6124, "s": 6116, "text": "GATE CS" }, { "code": null, "e": 6143, "s": 6124, "text": "Technical Scripter" }, { "code": null, "e": 6161, "s": 6143, "text": "Computer Networks" }, { "code": null, "e": 6259, "s": 6161, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6289, "s": 6259, "text": "GSM in Wireless Communication" }, { "code": null, "e": 6315, "s": 6289, "text": "Secure Socket Layer (SSL)" }, { "code": null, "e": 6345, "s": 6315, "text": "Wireless Application Protocol" }, { "code": null, "e": 6385, "s": 6345, "text": "Mobile Internet Protocol (or Mobile IP)" }, { "code": null, "e": 6420, "s": 6385, "text": "Advanced Encryption Standard (AES)" }, { "code": null, "e": 6444, "s": 6420, "text": "ACID Properties in DBMS" }, { "code": null, "e": 6471, "s": 6444, "text": "Types of Operating Systems" }, { "code": null, "e": 6492, "s": 6471, "text": "Normal Forms in DBMS" }, { "code": null, "e": 6541, "s": 6492, "text": "Page Replacement Algorithms in Operating Systems" } ]
Golang Maps
10 Sep, 2021 In Go language, a map is a powerful, ingenious, and versatile data structure. Golang Maps is a collection of unordered pairs of key-value. It is widely used because it provides fast lookups and values that can retrieve, update or delete with the help of keys. It is a reference to a hash table. Due to its reference type it is inexpensive to pass, for example, for a 64-bit machine it takes 8 bytes and for a 32-bit machine, it takes 4 bytes. In the maps, a key must be unique and always in the type which is comparable using == operator or the type which support != operator. So, most of the built-in type can be used as a key like an int, float64, rune, string, comparable array and structure, pointer, etc. The data types like slice and noncomparable arrays and structs or the custom data types which are not comparable don’t use as a map key. In maps, the values are not unique like keys and can be of any type like int, float64, rune, string, pointer, reference type, map type, etc. The type of keys and type of values must be of the same type, different types of keys and values in the same maps are not allowed. But the type of key and the type values can differ. The map is also known as a hash map, hash table, unordered map, dictionary, or associative array. In maps, you can only add value when the map is initialized if you try to add value in the uninitialized map, then the compiler will throw an error. In Go language, maps can create and initialize using two different ways: 1. Simple: In this method, you can create and initialize a map without the use of make() function: Creating Map: You can simply create a map using the given syntax: // An Empty map map[Key_Type]Value_Type{} // Map with key-value pair map[Key_Type]Value_Type{key1: value1, ..., keyN: valueN} Example: Chapters descriptions off, selected captions settings, opens captions settings dialog captions off, selected English This is a modal window. Beginning of dialog window. Escape will cancel and close the window. End of dialog window. var mymap map[int]string In maps, the zero value of the map is nil and a nil map doesn’t contain any key. If you try to add a key-value pair in the nil map, then the compiler will throw runtime error. Initializing map using map literals: Map literal is the easiest way to initialize a map with data just simply separate the key-value pair with a colon and the last trailing colon is necessary if you do not use, then the compiler will give an error. Example: Go // Go program to illustrate how to// create and initialize mapspackage main import "fmt" func main() { // Creating and initializing empty map // Using var keyword var map_1 map[int]int // Checking if the map is nil or not if map_1 == nil { fmt.Println("True") } else { fmt.Println("False") } // Creating and initializing a map // Using shorthand declaration and // using map literals map_2 := map[int]string{ 90: "Dog", 91: "Cat", 92: "Cow", 93: "Bird", 94: "Rabbit", } fmt.Println("Map-2: ", map_2)} Output: True Map-2: map[90:Dog 91:Cat 92:Cow 93:Bird 94:Rabbit] 2. Using make function: You can also create a map using make() function. This function is an inbuilt function and in this method, you just need to pass the type of the map and it will return an initialized map.] Syntax: make(map[Key_Type]Value_Type, initial_Capacity) make(map[Key_Type]Value_Type) Example: Go // Go program to illustrate how to// create and initialize a map// Using make() functionpackage main import "fmt" func main() { // Creating a map // Using make() function var My_map = make(map[float64]string) fmt.Println(My_map) // As we already know that make() function // always returns a map which is initialized // So, we can add values in it My_map[1.3] = "Rohit" My_map[1.5] = "Sumit" fmt.Println(My_map)} Output: map[] map[1.3:Rohit 1.5:Sumit] 1. How to iterate over a map?: You can iterate a map using the range for loop. The value of this loop may vary because the map is an unordered collection. Example: Go // Go program to illustrate how// to iterate the map using for// rang loop package main import "fmt" // Main functionfunc main() { // Creating and initializing a map m_a_p := map[int]string{ 90: "Dog", 91: "Cat", 92: "Cow", 93: "Bird", 94: "Rabbit", } // Iterating map using for rang loop for id, pet := range m_a_p { fmt.Println(id, pet) }} Output: 90 Dog 91 Cat 92 Cow 93 Bird 94 Rabbit 2. How to add key-value pairs in the map?: In maps, you are allowed to add key-value pairs in the initialized map using the given syntax: map_name[key]=value In maps, if you try to add an already existing key, then it will simply override or update the value of that key with the new value. Example: Go // Go program to illustrate how to add// a key-value pair in the map using// make() functionpackage main import "fmt" // Main functionfunc main() { // Creating and initializing a map m_a_p := map[int]string{ 90: "Dog", 91: "Cat", 92: "Cow", 93: "Bird", 94: "Rabbit", } fmt.Println("Original map: ", m_a_p) // Adding new key-value pairs in the map m_a_p[95] = "Parrot" m_a_p[96] = "Crow" fmt.Println("Map after adding new key-value pair:\n", m_a_p) // Updating values of the map m_a_p[91] = "PIG" m_a_p[93] = "DONKEY" fmt.Println("\nMap after updating values of the map:\n", m_a_p)} Output: Original map: map[90:Dog 91:Cat 92:Cow 93:Bird 94:Rabbit] Map after adding new key-value pair: map[90:Dog 91:Cat 92:Cow 93:Bird 94:Rabbit 95:Parrot 96:Crow] Map after updating values of the map: map[90:Dog 91:PIG 92:Cow 93:DONKEY 94:Rabbit 95:Parrot 96:Crow] 3. How to retrieve a value related to a key in the maps?: In maps, you can retrieve a value with the help of key using the following syntax: map_name[key] If the key doesn’t exist in the given map, then it will return zero value of the map, i.e, nil. And if the key exists in the given map, then it will return the value related to that key. Example: Go // Go program to illustrate how to// retrieve the value of the key package main import "fmt" // Main functionfunc main() { // Creating and initializing a map m_a_p := map[int]string{ 90: "Dog", 91: "Cat", 92: "Cow", 93: "Bird", 94: "Rabbit", } fmt.Println("Original map: ", m_a_p) // Retrieving values with the help of keys value_1 := m_a_p[90] value_2 := m_a_p[93] fmt.Println("Value of key[90]: ", value_1) fmt.Println("Value of key[93]: ", value_2)} Output: Original map: map[90:Dog 91:Cat 92:Cow 93:Bird 94:Rabbit] Value of key[90]: Dog Value of key[93]: Bird 4. How to check the existence of the key in the map?: In maps, you can check whether the given key exists or not using the following syntax: // With value // It will gives the value and check result value, check_variable_name:= map_name[key] or // Without value using the blank identifier // It will only give check result _, check_variable_name:= map_name[key] Here, if the value of the check_variable_name is true which means the key exists in the given map and if the value of check_variable_name is false which means the key does not exist in the given map. Example: Go // Go program to illustrate how to// check the key is available or not package main import "fmt" // Main functionfunc main() { // Creating and initializing a map m_a_p := map[int]string{ 90: "Dog", 91: "Cat", 92: "Cow", 93: "Bird", 94: "Rabbit", } fmt.Println("Original map: ", m_a_p) // Checking the key is available // or not in the m_a_p map pet_name, ok := m_a_p[90] fmt.Println("\nKey present or not:", ok) fmt.Println("Value:", pet_name) // Using blank identifier _, ok1 := m_a_p[92] fmt.Println("\nKey present or not:", ok1)} Output: Original map: map[90:Dog 91:Cat 92:Cow 93:Bird 94:Rabbit] Key present or not: true Value: Dog Key present or not: true 5. How to delete key from the map?: In maps, you are allowed to delete the key present in the map using the delete() function. It is inbuilt function and does not return any value and does not do anything if the key does not present in the given map. In this function, you just simply pass the map and key which you want to delete from the map. Syntax: delete(map_name, key) Example: Go // Go program to illustrate how to delete a key package main import "fmt" // Main functionfunc main() { // Creating and initializing a map m_a_p := map[int]string{ 90: "Dog", 91: "Cat", 92: "Cow", 93: "Bird", 94: "Rabbit", } fmt.Println("Original map: ", m_a_p) // Deleting keys // Using delete function delete(m_a_p, 90) delete(m_a_p, 93) fmt.Println("Map after deletion: ", m_a_p)} Output: Original map: map[90:Dog 91:Cat 92:Cow 93:Bird 94:Rabbit] Map after deletion: map[91:Cat 92:Cow 94:Rabbit] 6. Modifying map: As we know that maps are of reference type. So, when we assign an existing map to a new variable, both the maps still refer to the same underlying data structure. So, when we update one map it will reflect in another map. Example: Go // Go program to illustrate the// modification concept in map package main import "fmt" // Main functionfunc main() { // Creating and initializing a map m_a_p := map[int]string{ 90: "Dog", 91: "Cat", 92: "Cow", 93: "Bird", 94: "Rabbit", } fmt.Println("Original map: ", m_a_p) // Assigned the map into a new variable new_map := m_a_p // Perform modification in new_map new_map[96] = "Parrot" new_map[98] = "Pig" // Display after modification fmt.Println("New map: ", new_map) fmt.Println("\nModification done in old map:\n", m_a_p)} Output: Original map: map[90:Dog 91:Cat 92:Cow 93:Bird 94:Rabbit] New map: map[90:Dog 91:Cat 92:Cow 93:Bird 94:Rabbit 96:Parrot 98:Pig] Modification done in old map: map[90:Dog 91:Cat 92:Cow 93:Bird 94:Rabbit 96:Parrot 98:Pig] surinderdawra388 Golang Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. strings.Replace() Function in Golang With Examples fmt.Sprintf() Function in Golang With Examples How to Split a String in Golang? Interfaces in Golang How to Parse JSON in Golang? How to Trim a String in Golang? How to convert a string in lower case in Golang? Different Ways to Find the Type of Variable in Golang How to compare times in Golang? Inheritance in GoLang
[ { "code": null, "e": 28, "s": 0, "text": "\n10 Sep, 2021" }, { "code": null, "e": 288, "s": 28, "text": "In Go language, a map is a powerful, ingenious, and versatile data structure. Golang Maps is a collection of unordered pairs of key-value. It is widely used because it provides fast lookups and values that can retrieve, update or delete with the help of keys." }, { "code": null, "e": 323, "s": 288, "text": "It is a reference to a hash table." }, { "code": null, "e": 471, "s": 323, "text": "Due to its reference type it is inexpensive to pass, for example, for a 64-bit machine it takes 8 bytes and for a 32-bit machine, it takes 4 bytes." }, { "code": null, "e": 875, "s": 471, "text": "In the maps, a key must be unique and always in the type which is comparable using == operator or the type which support != operator. So, most of the built-in type can be used as a key like an int, float64, rune, string, comparable array and structure, pointer, etc. The data types like slice and noncomparable arrays and structs or the custom data types which are not comparable don’t use as a map key." }, { "code": null, "e": 1016, "s": 875, "text": "In maps, the values are not unique like keys and can be of any type like int, float64, rune, string, pointer, reference type, map type, etc." }, { "code": null, "e": 1199, "s": 1016, "text": "The type of keys and type of values must be of the same type, different types of keys and values in the same maps are not allowed. But the type of key and the type values can differ." }, { "code": null, "e": 1297, "s": 1199, "text": "The map is also known as a hash map, hash table, unordered map, dictionary, or associative array." }, { "code": null, "e": 1446, "s": 1297, "text": "In maps, you can only add value when the map is initialized if you try to add value in the uninitialized map, then the compiler will throw an error." }, { "code": null, "e": 1520, "s": 1446, "text": "In Go language, maps can create and initialize using two different ways: " }, { "code": null, "e": 1619, "s": 1520, "text": "1. Simple: In this method, you can create and initialize a map without the use of make() function:" }, { "code": null, "e": 1685, "s": 1619, "text": "Creating Map: You can simply create a map using the given syntax:" }, { "code": null, "e": 1812, "s": 1685, "text": "// An Empty map\nmap[Key_Type]Value_Type{}\n\n// Map with key-value pair\nmap[Key_Type]Value_Type{key1: value1, ..., keyN: valueN}" }, { "code": null, "e": 1822, "s": 1812, "text": "Example: " }, { "code": null, "e": 1831, "s": 1822, "text": "Chapters" }, { "code": null, "e": 1858, "s": 1831, "text": "descriptions off, selected" }, { "code": null, "e": 1908, "s": 1858, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 1931, "s": 1908, "text": "captions off, selected" }, { "code": null, "e": 1939, "s": 1931, "text": "English" }, { "code": null, "e": 1963, "s": 1939, "text": "This is a modal window." }, { "code": null, "e": 2032, "s": 1963, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 2054, "s": 2032, "text": "End of dialog window." }, { "code": null, "e": 2079, "s": 2054, "text": "var mymap map[int]string" }, { "code": null, "e": 2505, "s": 2079, "text": "In maps, the zero value of the map is nil and a nil map doesn’t contain any key. If you try to add a key-value pair in the nil map, then the compiler will throw runtime error. Initializing map using map literals: Map literal is the easiest way to initialize a map with data just simply separate the key-value pair with a colon and the last trailing colon is necessary if you do not use, then the compiler will give an error. " }, { "code": null, "e": 2514, "s": 2505, "text": "Example:" }, { "code": null, "e": 2517, "s": 2514, "text": "Go" }, { "code": "// Go program to illustrate how to// create and initialize mapspackage main import \"fmt\" func main() { // Creating and initializing empty map // Using var keyword var map_1 map[int]int // Checking if the map is nil or not if map_1 == nil { fmt.Println(\"True\") } else { fmt.Println(\"False\") } // Creating and initializing a map // Using shorthand declaration and // using map literals map_2 := map[int]string{ 90: \"Dog\", 91: \"Cat\", 92: \"Cow\", 93: \"Bird\", 94: \"Rabbit\", } fmt.Println(\"Map-2: \", map_2)}", "e": 3149, "s": 2517, "text": null }, { "code": null, "e": 3157, "s": 3149, "text": "Output:" }, { "code": null, "e": 3214, "s": 3157, "text": "True\nMap-2: map[90:Dog 91:Cat 92:Cow 93:Bird 94:Rabbit]" }, { "code": null, "e": 3426, "s": 3214, "text": "2. Using make function: You can also create a map using make() function. This function is an inbuilt function and in this method, you just need to pass the type of the map and it will return an initialized map.]" }, { "code": null, "e": 3434, "s": 3426, "text": "Syntax:" }, { "code": null, "e": 3512, "s": 3434, "text": "make(map[Key_Type]Value_Type, initial_Capacity)\nmake(map[Key_Type]Value_Type)" }, { "code": null, "e": 3521, "s": 3512, "text": "Example:" }, { "code": null, "e": 3524, "s": 3521, "text": "Go" }, { "code": "// Go program to illustrate how to// create and initialize a map// Using make() functionpackage main import \"fmt\" func main() { // Creating a map // Using make() function var My_map = make(map[float64]string) fmt.Println(My_map) // As we already know that make() function // always returns a map which is initialized // So, we can add values in it My_map[1.3] = \"Rohit\" My_map[1.5] = \"Sumit\" fmt.Println(My_map)}", "e": 3969, "s": 3524, "text": null }, { "code": null, "e": 3978, "s": 3969, "text": "Output: " }, { "code": null, "e": 4009, "s": 3978, "text": "map[]\nmap[1.3:Rohit 1.5:Sumit]" }, { "code": null, "e": 4164, "s": 4009, "text": "1. How to iterate over a map?: You can iterate a map using the range for loop. The value of this loop may vary because the map is an unordered collection." }, { "code": null, "e": 4173, "s": 4164, "text": "Example:" }, { "code": null, "e": 4176, "s": 4173, "text": "Go" }, { "code": "// Go program to illustrate how// to iterate the map using for// rang loop package main import \"fmt\" // Main functionfunc main() { // Creating and initializing a map m_a_p := map[int]string{ 90: \"Dog\", 91: \"Cat\", 92: \"Cow\", 93: \"Bird\", 94: \"Rabbit\", } // Iterating map using for rang loop for id, pet := range m_a_p { fmt.Println(id, pet) }}", "e": 4582, "s": 4176, "text": null }, { "code": null, "e": 4590, "s": 4582, "text": "Output:" }, { "code": null, "e": 4629, "s": 4590, "text": "90 Dog\n91 Cat\n92 Cow\n93 Bird\n94 Rabbit" }, { "code": null, "e": 4767, "s": 4629, "text": "2. How to add key-value pairs in the map?: In maps, you are allowed to add key-value pairs in the initialized map using the given syntax:" }, { "code": null, "e": 4787, "s": 4767, "text": "map_name[key]=value" }, { "code": null, "e": 4920, "s": 4787, "text": "In maps, if you try to add an already existing key, then it will simply override or update the value of that key with the new value." }, { "code": null, "e": 4929, "s": 4920, "text": "Example:" }, { "code": null, "e": 4932, "s": 4929, "text": "Go" }, { "code": "// Go program to illustrate how to add// a key-value pair in the map using// make() functionpackage main import \"fmt\" // Main functionfunc main() { // Creating and initializing a map m_a_p := map[int]string{ 90: \"Dog\", 91: \"Cat\", 92: \"Cow\", 93: \"Bird\", 94: \"Rabbit\", } fmt.Println(\"Original map: \", m_a_p) // Adding new key-value pairs in the map m_a_p[95] = \"Parrot\" m_a_p[96] = \"Crow\" fmt.Println(\"Map after adding new key-value pair:\\n\", m_a_p) // Updating values of the map m_a_p[91] = \"PIG\" m_a_p[93] = \"DONKEY\" fmt.Println(\"\\nMap after updating values of the map:\\n\", m_a_p)}", "e": 5589, "s": 4932, "text": null }, { "code": null, "e": 5598, "s": 5589, "text": "Output: " }, { "code": null, "e": 5861, "s": 5598, "text": "Original map: map[90:Dog 91:Cat 92:Cow 93:Bird 94:Rabbit]\nMap after adding new key-value pair:\n map[90:Dog 91:Cat 92:Cow 93:Bird 94:Rabbit 95:Parrot 96:Crow]\n\nMap after updating values of the map:\n map[90:Dog 91:PIG 92:Cow 93:DONKEY 94:Rabbit 95:Parrot 96:Crow]" }, { "code": null, "e": 6002, "s": 5861, "text": "3. How to retrieve a value related to a key in the maps?: In maps, you can retrieve a value with the help of key using the following syntax:" }, { "code": null, "e": 6016, "s": 6002, "text": "map_name[key]" }, { "code": null, "e": 6203, "s": 6016, "text": "If the key doesn’t exist in the given map, then it will return zero value of the map, i.e, nil. And if the key exists in the given map, then it will return the value related to that key." }, { "code": null, "e": 6212, "s": 6203, "text": "Example:" }, { "code": null, "e": 6215, "s": 6212, "text": "Go" }, { "code": "// Go program to illustrate how to// retrieve the value of the key package main import \"fmt\" // Main functionfunc main() { // Creating and initializing a map m_a_p := map[int]string{ 90: \"Dog\", 91: \"Cat\", 92: \"Cow\", 93: \"Bird\", 94: \"Rabbit\", } fmt.Println(\"Original map: \", m_a_p) // Retrieving values with the help of keys value_1 := m_a_p[90] value_2 := m_a_p[93] fmt.Println(\"Value of key[90]: \", value_1) fmt.Println(\"Value of key[93]: \", value_2)}", "e": 6732, "s": 6215, "text": null }, { "code": null, "e": 6740, "s": 6732, "text": "Output:" }, { "code": null, "e": 6846, "s": 6740, "text": "Original map: map[90:Dog 91:Cat 92:Cow 93:Bird 94:Rabbit]\nValue of key[90]: Dog\nValue of key[93]: Bird" }, { "code": null, "e": 6987, "s": 6846, "text": "4. How to check the existence of the key in the map?: In maps, you can check whether the given key exists or not using the following syntax:" }, { "code": null, "e": 7210, "s": 6987, "text": "// With value\n// It will gives the value and check result\nvalue, check_variable_name:= map_name[key]\n\nor\n\n// Without value using the blank identifier\n// It will only give check result\n_, check_variable_name:= map_name[key]" }, { "code": null, "e": 7411, "s": 7210, "text": "Here, if the value of the check_variable_name is true which means the key exists in the given map and if the value of check_variable_name is false which means the key does not exist in the given map. " }, { "code": null, "e": 7420, "s": 7411, "text": "Example:" }, { "code": null, "e": 7423, "s": 7420, "text": "Go" }, { "code": "// Go program to illustrate how to// check the key is available or not package main import \"fmt\" // Main functionfunc main() { // Creating and initializing a map m_a_p := map[int]string{ 90: \"Dog\", 91: \"Cat\", 92: \"Cow\", 93: \"Bird\", 94: \"Rabbit\", } fmt.Println(\"Original map: \", m_a_p) // Checking the key is available // or not in the m_a_p map pet_name, ok := m_a_p[90] fmt.Println(\"\\nKey present or not:\", ok) fmt.Println(\"Value:\", pet_name) // Using blank identifier _, ok1 := m_a_p[92] fmt.Println(\"\\nKey present or not:\", ok1)}", "e": 8031, "s": 7423, "text": null }, { "code": null, "e": 8040, "s": 8031, "text": "Output: " }, { "code": null, "e": 8162, "s": 8040, "text": "Original map: map[90:Dog 91:Cat 92:Cow 93:Bird 94:Rabbit]\n\nKey present or not: true\nValue: Dog\n\nKey present or not: true" }, { "code": null, "e": 8507, "s": 8162, "text": "5. How to delete key from the map?: In maps, you are allowed to delete the key present in the map using the delete() function. It is inbuilt function and does not return any value and does not do anything if the key does not present in the given map. In this function, you just simply pass the map and key which you want to delete from the map." }, { "code": null, "e": 8516, "s": 8507, "text": "Syntax: " }, { "code": null, "e": 8538, "s": 8516, "text": "delete(map_name, key)" }, { "code": null, "e": 8547, "s": 8538, "text": "Example:" }, { "code": null, "e": 8550, "s": 8547, "text": "Go" }, { "code": "// Go program to illustrate how to delete a key package main import \"fmt\" // Main functionfunc main() { // Creating and initializing a map m_a_p := map[int]string{ 90: \"Dog\", 91: \"Cat\", 92: \"Cow\", 93: \"Bird\", 94: \"Rabbit\", } fmt.Println(\"Original map: \", m_a_p) // Deleting keys // Using delete function delete(m_a_p, 90) delete(m_a_p, 93) fmt.Println(\"Map after deletion: \", m_a_p)}", "e": 9000, "s": 8550, "text": null }, { "code": null, "e": 9008, "s": 9000, "text": "Output:" }, { "code": null, "e": 9117, "s": 9008, "text": "Original map: map[90:Dog 91:Cat 92:Cow 93:Bird 94:Rabbit]\nMap after deletion: map[91:Cat 92:Cow 94:Rabbit]" }, { "code": null, "e": 9357, "s": 9117, "text": "6. Modifying map: As we know that maps are of reference type. So, when we assign an existing map to a new variable, both the maps still refer to the same underlying data structure. So, when we update one map it will reflect in another map." }, { "code": null, "e": 9366, "s": 9357, "text": "Example:" }, { "code": null, "e": 9369, "s": 9366, "text": "Go" }, { "code": "// Go program to illustrate the// modification concept in map package main import \"fmt\" // Main functionfunc main() { // Creating and initializing a map m_a_p := map[int]string{ 90: \"Dog\", 91: \"Cat\", 92: \"Cow\", 93: \"Bird\", 94: \"Rabbit\", } fmt.Println(\"Original map: \", m_a_p) // Assigned the map into a new variable new_map := m_a_p // Perform modification in new_map new_map[96] = \"Parrot\" new_map[98] = \"Pig\" // Display after modification fmt.Println(\"New map: \", new_map) fmt.Println(\"\\nModification done in old map:\\n\", m_a_p)}", "e": 9976, "s": 9369, "text": null }, { "code": null, "e": 9984, "s": 9976, "text": "Output:" }, { "code": null, "e": 10207, "s": 9984, "text": "Original map: map[90:Dog 91:Cat 92:Cow 93:Bird 94:Rabbit]\nNew map: map[90:Dog 91:Cat 92:Cow 93:Bird 94:Rabbit 96:Parrot 98:Pig]\n\nModification done in old map:\n map[90:Dog 91:Cat 92:Cow 93:Bird 94:Rabbit 96:Parrot 98:Pig]" }, { "code": null, "e": 10224, "s": 10207, "text": "surinderdawra388" }, { "code": null, "e": 10231, "s": 10224, "text": "Golang" }, { "code": null, "e": 10243, "s": 10231, "text": "Go Language" }, { "code": null, "e": 10341, "s": 10243, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 10392, "s": 10341, "text": "strings.Replace() Function in Golang With Examples" }, { "code": null, "e": 10439, "s": 10392, "text": "fmt.Sprintf() Function in Golang With Examples" }, { "code": null, "e": 10472, "s": 10439, "text": "How to Split a String in Golang?" }, { "code": null, "e": 10493, "s": 10472, "text": "Interfaces in Golang" }, { "code": null, "e": 10522, "s": 10493, "text": "How to Parse JSON in Golang?" }, { "code": null, "e": 10554, "s": 10522, "text": "How to Trim a String in Golang?" }, { "code": null, "e": 10603, "s": 10554, "text": "How to convert a string in lower case in Golang?" }, { "code": null, "e": 10657, "s": 10603, "text": "Different Ways to Find the Type of Variable in Golang" }, { "code": null, "e": 10689, "s": 10657, "text": "How to compare times in Golang?" } ]
Find cost price from given selling price and profit or loss percentage
23 Jun, 2022 Given the Selling Price(SP) and percentage profit or loss of a product. The task is to Calculate the cost price(CP) of the product.Examples: Input: SP = 1020, Profit Percentage = 20 Output: CP = 850 Input: SP = 900, Loss Percentage = 10 Output: CP = 1000 Approach: Formula to calculate cost price if selling price and profit percentage are given: CP = ( SP * 100 ) / ( 100 + percentage profit). Formula to calculate cost price if selling price and loss percentage are given: CP = ( SP * 100 ) / ( 100 – percentage loss ). Below is the required implementation: C++ Java Python3 C# PHP Javascript // C++ implementation to find Cost price#include <iostream>using namespace std; // Function to calculate cost price with profitfloat CPwithProfit(int sellingPrice, int profit){ float costPrice; // required formula to calculate CP with profit costPrice = (sellingPrice * 100.0) / (100 + profit); return costPrice;} // Function to calculate cost price with lossfloat CPwithLoss(int sellingPrice, int loss){ float costPrice; // required formula to calculate CP with loss costPrice = (sellingPrice * 100.0) / (100 - loss); return costPrice;} // Driver codeint main(){ int SP, profit, loss; SP = 1020; profit = 20; cout << "Cost Price = " << CPwithProfit(SP, profit) << endl; SP = 900; loss = 10; cout << "Cost Price = " << CPwithLoss(SP, loss) << endl; SP = 42039; profit = 8; cout << "Cost Price = " << CPwithProfit(SP, profit) << endl; return 0;} // Java implementation to find Cost priceimport java.util.*; class solution{ // Function to calculate cost price with profitstatic float CPwithProfit(int sellingPrice, int profit){ float costPrice; // required formula to calculate CP with profit costPrice = (sellingPrice * 100) / (100 + profit); return costPrice;} // Function to calculate cost price with lossstatic float CPwithLoss(int sellingPrice, int loss){ float costPrice; // required formula to calculate CP with loss costPrice = (sellingPrice * 100) / (100 - loss); return costPrice;} // Driver codepublic static void main(String args[]){ int SP, profit, loss; SP = 1020; profit = 20; System.out.println("Cost Price = "+CPwithProfit(SP, profit)); SP = 900; loss = 10; System.out.println("Cost Price = "+CPwithLoss(SP, loss)); SP = 42039; profit = 8; System.out.println("Cost Price = "+CPwithProfit(SP, profit)); }}// This code is contribute by// Shashank_Sharma # Python 3 implementation to find Cost price # Function to calculate cost price with profitdef CPwithProfit(sellingPrice, profit): # required formula to calculate CP with profit costPrice = ((sellingPrice * 100.0) / (100 + profit)) return costPrice # Function to calculate cost price with lossdef CPwithLoss(sellingPrice, loss): # required formula to calculate CP with loss costPrice = ((sellingPrice * 100.0) / (100 - loss)) return costPrice # Driver codeif __name__ == '__main__': SP = 1020 profit = 20 print("Cost Price =", CPwithProfit(SP, profit)) SP = 900 loss = 10 print("Cost Price =", CPwithLoss(SP, loss)) SP = 42039 profit = 8 print("Cost Price =", int(CPwithProfit(SP, profit))) # This code is contributed by# Surendra_Gangwar // Csharp implementation to find Cost price using System; class solution{ // Function to calculate cost price with profitstatic float CPwithProfit(int sellingPrice, int profit){ float costPrice; // required formula to calculate CP with profit costPrice = (sellingPrice * 100) / (100 + profit); return costPrice;} // Function to calculate cost price with lossstatic float CPwithLoss(int sellingPrice, int loss){ float costPrice; // required formula to calculate CP with loss costPrice = (sellingPrice * 100) / (100 - loss); return costPrice;} // Driver codepublic static void Main(){ int SP, profit, loss; SP = 1020; profit = 20; Console.WriteLine("Cost Price = "+CPwithProfit(SP, profit)); SP = 900; loss = 10; Console.WriteLine("Cost Price = "+CPwithLoss(SP, loss)); SP = 42039; profit = 8; Console.WriteLine("Cost Price = "+CPwithProfit(SP, profit)); }// This code is contribute by Ryuga } <?php// PHP implementation to find Cost price // Function to calculate cost price with profitfunction CPwithProfit($sellingPrice, $profit){ // required formula to calculate CP with profit $costPrice = ($sellingPrice * 100.0) / (100 + $profit); return $costPrice;} // Function to calculate cost price with lossfunction CPwithLoss($sellingPrice, $loss){ // required formula to calculate CP with loss $costPrice = ($sellingPrice * 100.0) / (100 - $loss); return $costPrice;} // Driver code $SP = 1020; $profit = 20; echo("Cost Price = "); echo(CPwithProfit($SP, $profit)); echo("\n"); $SP = 900; $loss = 10; echo("Cost Price = "); echo(CPwithLoss($SP, $loss)); echo("\n"); $SP = 42039; $profit = 8; echo("Cost Price = "); echo(CPwithProfit($SP, $profit)); echo("\n"); //This code is contributed by Shivi_Aggarwal?> // javascript implementation to find Cost price // Function to calculate cost price with profit function CPwithProfit(sellingPrice, profit){ var costPrice; // required formula to calculate CP with profit costPrice = (sellingPrice * 100) / (100 + profit); return costPrice;} // Function to calculate cost price with lossfunction CPwithLoss( sellingPrice, loss){ var costPrice; // required formula to calculate CP with loss costPrice = (sellingPrice * 100) / (100 - loss); return costPrice;} // Driver code var SP, profit, loss; SP = 1020; profit = 20; document.write("Cost Price = " + CPwithProfit(SP, profit) + "<br>"); SP = 900; loss = 10; document.write("Cost Price = " + CPwithLoss(SP, loss) + "<br>"); SP = 42039; profit = 8; document.write("Cost Price = " + CPwithProfit(SP, profit) + "<br>"); // This code is contributed by bunnyram19. </script> Cost Price = 850 Cost Price = 1000 Cost Price = 38925 Time Complexity: O(1) Auxiliary Space: O(1) Shashank_Sharma ankthon Shivi_Aggarwal SURENDRA_GANGWAR bunnyram19 simmytarika5 rishav1329 Profit and Loss Mathematical School Programming Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n23 Jun, 2022" }, { "code": null, "e": 195, "s": 52, "text": "Given the Selling Price(SP) and percentage profit or loss of a product. The task is to Calculate the cost price(CP) of the product.Examples: " }, { "code": null, "e": 312, "s": 195, "text": "Input: SP = 1020, Profit Percentage = 20\nOutput: CP = 850\n\nInput: SP = 900, Loss Percentage = 10\nOutput: CP = 1000" }, { "code": null, "e": 326, "s": 314, "text": "Approach: " }, { "code": null, "e": 409, "s": 326, "text": "Formula to calculate cost price if selling price and profit percentage are given: " }, { "code": null, "e": 457, "s": 409, "text": "CP = ( SP * 100 ) / ( 100 + percentage profit)." }, { "code": null, "e": 538, "s": 457, "text": "Formula to calculate cost price if selling price and loss percentage are given: " }, { "code": null, "e": 585, "s": 538, "text": "CP = ( SP * 100 ) / ( 100 – percentage loss )." }, { "code": null, "e": 625, "s": 585, "text": "Below is the required implementation: " }, { "code": null, "e": 629, "s": 625, "text": "C++" }, { "code": null, "e": 634, "s": 629, "text": "Java" }, { "code": null, "e": 642, "s": 634, "text": "Python3" }, { "code": null, "e": 645, "s": 642, "text": "C#" }, { "code": null, "e": 649, "s": 645, "text": "PHP" }, { "code": null, "e": 660, "s": 649, "text": "Javascript" }, { "code": "// C++ implementation to find Cost price#include <iostream>using namespace std; // Function to calculate cost price with profitfloat CPwithProfit(int sellingPrice, int profit){ float costPrice; // required formula to calculate CP with profit costPrice = (sellingPrice * 100.0) / (100 + profit); return costPrice;} // Function to calculate cost price with lossfloat CPwithLoss(int sellingPrice, int loss){ float costPrice; // required formula to calculate CP with loss costPrice = (sellingPrice * 100.0) / (100 - loss); return costPrice;} // Driver codeint main(){ int SP, profit, loss; SP = 1020; profit = 20; cout << \"Cost Price = \" << CPwithProfit(SP, profit) << endl; SP = 900; loss = 10; cout << \"Cost Price = \" << CPwithLoss(SP, loss) << endl; SP = 42039; profit = 8; cout << \"Cost Price = \" << CPwithProfit(SP, profit) << endl; return 0;}", "e": 1568, "s": 660, "text": null }, { "code": "// Java implementation to find Cost priceimport java.util.*; class solution{ // Function to calculate cost price with profitstatic float CPwithProfit(int sellingPrice, int profit){ float costPrice; // required formula to calculate CP with profit costPrice = (sellingPrice * 100) / (100 + profit); return costPrice;} // Function to calculate cost price with lossstatic float CPwithLoss(int sellingPrice, int loss){ float costPrice; // required formula to calculate CP with loss costPrice = (sellingPrice * 100) / (100 - loss); return costPrice;} // Driver codepublic static void main(String args[]){ int SP, profit, loss; SP = 1020; profit = 20; System.out.println(\"Cost Price = \"+CPwithProfit(SP, profit)); SP = 900; loss = 10; System.out.println(\"Cost Price = \"+CPwithLoss(SP, loss)); SP = 42039; profit = 8; System.out.println(\"Cost Price = \"+CPwithProfit(SP, profit)); }}// This code is contribute by// Shashank_Sharma", "e": 2549, "s": 1568, "text": null }, { "code": "# Python 3 implementation to find Cost price # Function to calculate cost price with profitdef CPwithProfit(sellingPrice, profit): # required formula to calculate CP with profit costPrice = ((sellingPrice * 100.0) / (100 + profit)) return costPrice # Function to calculate cost price with lossdef CPwithLoss(sellingPrice, loss): # required formula to calculate CP with loss costPrice = ((sellingPrice * 100.0) / (100 - loss)) return costPrice # Driver codeif __name__ == '__main__': SP = 1020 profit = 20 print(\"Cost Price =\", CPwithProfit(SP, profit)) SP = 900 loss = 10 print(\"Cost Price =\", CPwithLoss(SP, loss)) SP = 42039 profit = 8 print(\"Cost Price =\", int(CPwithProfit(SP, profit))) # This code is contributed by# Surendra_Gangwar", "e": 3429, "s": 2549, "text": null }, { "code": "// Csharp implementation to find Cost price using System; class solution{ // Function to calculate cost price with profitstatic float CPwithProfit(int sellingPrice, int profit){ float costPrice; // required formula to calculate CP with profit costPrice = (sellingPrice * 100) / (100 + profit); return costPrice;} // Function to calculate cost price with lossstatic float CPwithLoss(int sellingPrice, int loss){ float costPrice; // required formula to calculate CP with loss costPrice = (sellingPrice * 100) / (100 - loss); return costPrice;} // Driver codepublic static void Main(){ int SP, profit, loss; SP = 1020; profit = 20; Console.WriteLine(\"Cost Price = \"+CPwithProfit(SP, profit)); SP = 900; loss = 10; Console.WriteLine(\"Cost Price = \"+CPwithLoss(SP, loss)); SP = 42039; profit = 8; Console.WriteLine(\"Cost Price = \"+CPwithProfit(SP, profit)); }// This code is contribute by Ryuga }", "e": 4380, "s": 3429, "text": null }, { "code": "<?php// PHP implementation to find Cost price // Function to calculate cost price with profitfunction CPwithProfit($sellingPrice, $profit){ // required formula to calculate CP with profit $costPrice = ($sellingPrice * 100.0) / (100 + $profit); return $costPrice;} // Function to calculate cost price with lossfunction CPwithLoss($sellingPrice, $loss){ // required formula to calculate CP with loss $costPrice = ($sellingPrice * 100.0) / (100 - $loss); return $costPrice;} // Driver code $SP = 1020; $profit = 20; echo(\"Cost Price = \"); echo(CPwithProfit($SP, $profit)); echo(\"\\n\"); $SP = 900; $loss = 10; echo(\"Cost Price = \"); echo(CPwithLoss($SP, $loss)); echo(\"\\n\"); $SP = 42039; $profit = 8; echo(\"Cost Price = \"); echo(CPwithProfit($SP, $profit)); echo(\"\\n\"); //This code is contributed by Shivi_Aggarwal?>", "e": 5264, "s": 4380, "text": null }, { "code": "// javascript implementation to find Cost price // Function to calculate cost price with profit function CPwithProfit(sellingPrice, profit){ var costPrice; // required formula to calculate CP with profit costPrice = (sellingPrice * 100) / (100 + profit); return costPrice;} // Function to calculate cost price with lossfunction CPwithLoss( sellingPrice, loss){ var costPrice; // required formula to calculate CP with loss costPrice = (sellingPrice * 100) / (100 - loss); return costPrice;} // Driver code var SP, profit, loss; SP = 1020; profit = 20; document.write(\"Cost Price = \" + CPwithProfit(SP, profit) + \"<br>\"); SP = 900; loss = 10; document.write(\"Cost Price = \" + CPwithLoss(SP, loss) + \"<br>\"); SP = 42039; profit = 8; document.write(\"Cost Price = \" + CPwithProfit(SP, profit) + \"<br>\"); // This code is contributed by bunnyram19. </script>", "e": 6203, "s": 5264, "text": null }, { "code": null, "e": 6257, "s": 6203, "text": "Cost Price = 850\nCost Price = 1000\nCost Price = 38925" }, { "code": null, "e": 6281, "s": 6259, "text": "Time Complexity: O(1)" }, { "code": null, "e": 6303, "s": 6281, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 6319, "s": 6303, "text": "Shashank_Sharma" }, { "code": null, "e": 6327, "s": 6319, "text": "ankthon" }, { "code": null, "e": 6342, "s": 6327, "text": "Shivi_Aggarwal" }, { "code": null, "e": 6359, "s": 6342, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 6370, "s": 6359, "text": "bunnyram19" }, { "code": null, "e": 6383, "s": 6370, "text": "simmytarika5" }, { "code": null, "e": 6394, "s": 6383, "text": "rishav1329" }, { "code": null, "e": 6410, "s": 6394, "text": "Profit and Loss" }, { "code": null, "e": 6423, "s": 6410, "text": "Mathematical" }, { "code": null, "e": 6442, "s": 6423, "text": "School Programming" }, { "code": null, "e": 6455, "s": 6442, "text": "Mathematical" } ]
What are the Best Ways to Write a SQL Query?
03 Jul, 2022 An SQL Query is used to retrieve the required data from the database. However, there may be multiple SQL queries that yield the same results but with different levels of efficiency. An inefficient query can drain the database resources, reduce the database speed or result in a loss of service for other users. So it is very important to optimize the query to obtain the best database performance. Let us consider some sample tables to understand these different methods to optimize a query. Customers : Table Customers contains the details of the prospective customers for a shop. Products : Table Products contains the details of the products available in the shop. Orders : Table Orders contains the details of the products ordered by the customers from the shop. Now that we have analyzed the tables Customers, Products and Orders, the different ways to optimize a query are given below with query examples from these tables: It is very important to provide the correct formatting while writing a query. This enhances the readability of the query and also makes reviewing and troubleshooting it easier. Some of the rules for formatting a query are given below: Put each statement in the query in a new line. Put SQL keywords in the query in uppercase. Use CamelCase capitalization in the query and avoid underscore(Write ProductName and not Product_Name). Example: This is a query that displays the CustomerID and LastName of the customers that have currently ordered products and are younger than 50 years. Select distinct Customers.CustomerID, Customers.LastName from Customers INNER join Orders on Customers.CustomerID = Orders.CustomerID where Customers.Age < 50; The above query looks unreadable as all the statements are in one line and the keywords are in lower case. So an optimized version is given below using the rules for formatting specified earlier. SELECT DISTINCT Customers.CustomerID, Customers.LastName FROM Customers INNER JOIN Orders ON Customers.CustomerID = Orders.CustomerID WHERE Customers.Age < 50; SELECT * is used to obtain all the data from a table. So it should not be used unless all of the data is actually required for a given condition as it is highly inefficient and slows the execution time of the query. It is much better to use SELECT along with the specific fields required to optimize the query. Example: This is a query that displays all the data in the table Customers when only the CustomerID and LastName was required. SELECT * FROM Customers; It is better to use the select statement with the fields CustomerID and LastName to obtain the desired result. SELECT CustomerID, LastName FROM Customers; A correlated subquery is a nested query that depends on the outer query for its values. If there are millions of users in the database, the correlated subquery is inefficient and takes a lot of time as it will need to run millions of times. In that case, an inner join is more efficient. Example: This is a query that displays the CustomerID of the customers that have currently ordered products using a correlated subquery. SELECT CustomerID FROM Customers WHERE EXISTS (SELECT * FROM Orders WHERE Customers.CustomerID = Orders.CustomerID); It is better to use the inner join in this case to obtain the same result. SELECT DISTINCT Customers.CustomerID FROM Customers INNER JOIN Orders ON Customers.CustomerID = Orders.CustomerID; Note: It is best to avoid a correlated subquery if almost all of the rows are needed from the database. However, in some cases, they are inevitable and have to be used. In case only limited results are required, it is better to use the LIMIT statement. This statement limits the records and only displays the number of records specified. For Example: If there is a large database of a million records and only the first ten are required, it is better to use the LIMIT statement as this will ensure that only the relevant records are obtained without overtaxing the system. Example: This is a query that displays the customer details with limit 3: SELECT * FROM Customers LIMIT 3; The DISTINCT clause is used to obtain distinct results from a query by eliminating the duplicates. However, this increases the execution time of the query as all the duplicate fields are grouped together. So, it is better to avoid the DISTINCT clause as much as possible. As an alternative, the GROUP BY clause can be used to obtain distinct results. Example: This is a query that displays the distinct LastName of all the customers using the DISTINCT clause. select distinct LastName from Customers; The distinct LastName of the customers can also be obtained using the GROUP BY clause which is demonstrated by the next example: SELECT LastName FROM CUSTOMERS GROUP BY LastName; Functions in SQL are used to perform specific actions. However, they are quite inefficient as they do not allow the usage of indexes which in turn slows the execution time of the query. So it is better to avoid functions in a query as much as possible to ensure its optimization. Example: This is a query that displays the details of the products whose name starts with 'Sha'. SELECT * FROM Products WHERE SUBSTR(ProductName, 1, 3) = 'Sha'; It is better to avoid the function and use the LIKE clause instead to obtain the same result. SELECT * FROM Products WHERE ProductName LIKE 'Sha%'; It is highly likely that indexes are not in use when OR, AND, NOT operators are used. In the case of large databases, it is better to find replacements for these to speed up the execution time of the query. Examples of this for OR and AND operators are given below: Example 1: This is a query that displays the details of the customers with CustomerID 73001, 73004 and 73005 using the OR operator. SELECT * FROM Customers WHERE CustomerID = 73001 OR CustomerID = 73004 OR CustomerID = 73005; It is better to use the IN operator in this case to obtain the same result. SELECT * FROM Customers WHERE CustomerID IN (73001, 73004, 73005); Example 2: This is a query that displays the details of the customers with age between 25 and 50 using the AND operator. SELECT * FROM Customers WHERE age >= 25 AND age <= 50; It is better to use the BETWEEN operator in this case to obtain the same result. SELECT * FROM Customers WHERE age BETWEEN 25 AND 50; The HAVING clause is used with the GROUP BY clause to enforce conditions as the WHERE clause cannot be used with aggregate functions. However, the HAVING clause does not allow the usage of indexes which slows the execution time of the query. So it is better to use the WHERE clause instead of the HAVING clause whenever possible. Example: This is a query that displays the Customer FirstNames with the count of customers who have them for the customers aged more than 25. This is done using the HAVING clause. SELECT FirstName, COUNT(*) FROM Customers GROUP BY FirstName HAVING Age > 25; It is better to use the WHERE clause in this case as it applies the condition to individual rows rather than the HAVING clause that applies the condition to the result from the GROUP BY clause. SELECT FirstName, COUNT(*) FROM Customers where Age > 25 GROUP BY FirstName; Using the WHERE clause for creating joins results in a Cartesian Product where the number of rows is the product of the number of rows of the two tables. This is obviously problematic for large databases as more database resources are required. So it is much better to use INNER JOIN as that only combines the rows from both tables which satisfy the required condition. Example: This is a query that displays the CustomerID of the customers that have currently ordered products using the WHERE clause. SELECT DISTINCT Customers.CustomerID FROM Customers, Orders WHERE Customers.CustomerID = Orders.CustomerID; It is better to use the Inner join in this case to obtain the same result. SELECT DISTINCT Customers.CustomerID FROM Customers INNER JOIN Orders ON Customers.CustomerID = Orders.CustomerID; Wildcard characters such as % and _ are used to filter out the results of a LIKE clause. However, they should not be used at the beginning of the pattern as this disables the database from using the index. In that case, a full table scan is required to match the pattern which consumes more database resources. So it is better to avoid the wildcard characters at the beginning of the pattern and only use them at the end if possible. Example: SELECT * FROM Customers WHERE FirstName LIKE '%A%' The above query is inefficient as it uses the wildcard character % at the beginning of the pattern. A much more efficient version of the query that avoids this is given below: SELECT * FROM Customers WHERE FirstName LIKE 'A%' Marketing SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Update Multiple Columns in Single Update Statement in SQL? SQL Interview Questions SQL | Views Difference between DELETE, DROP and TRUNCATE MySQL | Group_CONCAT() Function Window functions in SQL SQL | GROUP BY Difference between DDL and DML in DBMS Difference between DELETE and TRUNCATE SQL Correlated Subqueries
[ { "code": null, "e": 52, "s": 24, "text": "\n03 Jul, 2022" }, { "code": null, "e": 450, "s": 52, "text": "An SQL Query is used to retrieve the required data from the database. However, there may be multiple SQL queries that yield the same results but with different levels of efficiency. An inefficient query can drain the database resources, reduce the database speed or result in a loss of service for other users. So it is very important to optimize the query to obtain the best database performance." }, { "code": null, "e": 544, "s": 450, "text": "Let us consider some sample tables to understand these different methods to optimize a query." }, { "code": null, "e": 634, "s": 544, "text": "Customers : Table Customers contains the details of the prospective customers for a shop." }, { "code": null, "e": 720, "s": 634, "text": "Products : Table Products contains the details of the products available in the shop." }, { "code": null, "e": 819, "s": 720, "text": "Orders : Table Orders contains the details of the products ordered by the customers from the shop." }, { "code": null, "e": 982, "s": 819, "text": "Now that we have analyzed the tables Customers, Products and Orders, the different ways to optimize a query are given below with query examples from these tables:" }, { "code": null, "e": 1217, "s": 982, "text": "It is very important to provide the correct formatting while writing a query. This enhances the readability of the query and also makes reviewing and troubleshooting it easier. Some of the rules for formatting a query are given below:" }, { "code": null, "e": 1264, "s": 1217, "text": "Put each statement in the query in a new line." }, { "code": null, "e": 1308, "s": 1264, "text": "Put SQL keywords in the query in uppercase." }, { "code": null, "e": 1412, "s": 1308, "text": "Use CamelCase capitalization in the query and avoid underscore(Write ProductName and not Product_Name)." }, { "code": null, "e": 1564, "s": 1412, "text": "Example: This is a query that displays the CustomerID and LastName of the customers that have currently ordered products and are younger than 50 years." }, { "code": null, "e": 1725, "s": 1564, "text": "Select distinct Customers.CustomerID, Customers.LastName from Customers INNER join Orders on Customers.CustomerID = Orders.CustomerID where Customers.Age < 50;\n" }, { "code": null, "e": 1921, "s": 1725, "text": "The above query looks unreadable as all the statements are in one line and the keywords are in lower case. So an optimized version is given below using the rules for formatting specified earlier." }, { "code": null, "e": 2082, "s": 1921, "text": "SELECT DISTINCT Customers.CustomerID, Customers.LastName\nFROM Customers INNER JOIN Orders\nON Customers.CustomerID = Orders.CustomerID\nWHERE Customers.Age < 50;\n" }, { "code": null, "e": 2393, "s": 2082, "text": "SELECT * is used to obtain all the data from a table. So it should not be used unless all of the data is actually required for a given condition as it is highly inefficient and slows the execution time of the query. It is much better to use SELECT along with the specific fields required to optimize the query." }, { "code": null, "e": 2520, "s": 2393, "text": "Example: This is a query that displays all the data in the table Customers when only the CustomerID and LastName was required." }, { "code": null, "e": 2547, "s": 2520, "text": "SELECT * \nFROM Customers;\n" }, { "code": null, "e": 2658, "s": 2547, "text": "It is better to use the select statement with the fields CustomerID and LastName to obtain the desired result." }, { "code": null, "e": 2704, "s": 2658, "text": "SELECT CustomerID, LastName \nFROM Customers;\n" }, { "code": null, "e": 2992, "s": 2704, "text": "A correlated subquery is a nested query that depends on the outer query for its values. If there are millions of users in the database, the correlated subquery is inefficient and takes a lot of time as it will need to run millions of times. In that case, an inner join is more efficient." }, { "code": null, "e": 3129, "s": 2992, "text": "Example: This is a query that displays the CustomerID of the customers that have currently ordered products using a correlated subquery." }, { "code": null, "e": 3261, "s": 3129, "text": "SELECT CustomerID\nFROM Customers\nWHERE EXISTS (SELECT * FROM Orders\n WHERE Customers.CustomerID = Orders.CustomerID);\n" }, { "code": null, "e": 3336, "s": 3261, "text": "It is better to use the inner join in this case to obtain the same result." }, { "code": null, "e": 3452, "s": 3336, "text": "SELECT DISTINCT Customers.CustomerID\nFROM Customers INNER JOIN Orders\nON Customers.CustomerID = Orders.CustomerID;\n" }, { "code": null, "e": 3621, "s": 3452, "text": "Note: It is best to avoid a correlated subquery if almost all of the rows are needed from the database. However, in some cases, they are inevitable and have to be used." }, { "code": null, "e": 4025, "s": 3621, "text": "In case only limited results are required, it is better to use the LIMIT statement. This statement limits the records and only displays the number of records specified. For Example: If there is a large database of a million records and only the first ten are required, it is better to use the LIMIT statement as this will ensure that only the relevant records are obtained without overtaxing the system." }, { "code": null, "e": 4099, "s": 4025, "text": "Example: This is a query that displays the customer details with limit 3:" }, { "code": null, "e": 4134, "s": 4099, "text": "SELECT *\nFROM Customers \nLIMIT 3;\n" }, { "code": null, "e": 4485, "s": 4134, "text": "The DISTINCT clause is used to obtain distinct results from a query by eliminating the duplicates. However, this increases the execution time of the query as all the duplicate fields are grouped together. So, it is better to avoid the DISTINCT clause as much as possible. As an alternative, the GROUP BY clause can be used to obtain distinct results." }, { "code": null, "e": 4594, "s": 4485, "text": "Example: This is a query that displays the distinct LastName of all the customers using the DISTINCT clause." }, { "code": null, "e": 4636, "s": 4594, "text": "select distinct LastName\nfrom Customers;\n" }, { "code": null, "e": 4765, "s": 4636, "text": "The distinct LastName of the customers can also be obtained using the GROUP BY clause which is demonstrated by the next example:" }, { "code": null, "e": 4817, "s": 4765, "text": "SELECT LastName\nFROM CUSTOMERS\nGROUP BY LastName;\n" }, { "code": null, "e": 5097, "s": 4817, "text": "Functions in SQL are used to perform specific actions. However, they are quite inefficient as they do not allow the usage of indexes which in turn slows the execution time of the query. So it is better to avoid functions in a query as much as possible to ensure its optimization." }, { "code": null, "e": 5194, "s": 5097, "text": "Example: This is a query that displays the details of the products whose name starts with 'Sha'." }, { "code": null, "e": 5259, "s": 5194, "text": "SELECT *\nFROM Products\nWHERE SUBSTR(ProductName, 1, 3) = 'Sha';\n" }, { "code": null, "e": 5353, "s": 5259, "text": "It is better to avoid the function and use the LIKE clause instead to obtain the same result." }, { "code": null, "e": 5408, "s": 5353, "text": "SELECT *\nFROM Products\nWHERE ProductName LIKE 'Sha%';\n" }, { "code": null, "e": 5615, "s": 5408, "text": "It is highly likely that indexes are not in use when OR, AND, NOT operators are used. In the case of large databases, it is better to find replacements for these to speed up the execution time of the query." }, { "code": null, "e": 5674, "s": 5615, "text": "Examples of this for OR and AND operators are given below:" }, { "code": null, "e": 5806, "s": 5674, "text": "Example 1: This is a query that displays the details of the customers with CustomerID 73001, 73004 and 73005 using the OR operator." }, { "code": null, "e": 5902, "s": 5806, "text": "SELECT * \nFROM Customers\nWHERE CustomerID = 73001\nOR CustomerID = 73004\nOR CustomerID = 73005;\n" }, { "code": null, "e": 5978, "s": 5902, "text": "It is better to use the IN operator in this case to obtain the same result." }, { "code": null, "e": 6047, "s": 5978, "text": "SELECT * \nFROM Customers\nWHERE CustomerID IN (73001, 73004, 73005);\n" }, { "code": null, "e": 6168, "s": 6047, "text": "Example 2: This is a query that displays the details of the customers with age between 25 and 50 using the AND operator." }, { "code": null, "e": 6225, "s": 6168, "text": "SELECT * \nFROM Customers\nWHERE age >= 25 AND age <= 50;\n" }, { "code": null, "e": 6306, "s": 6225, "text": "It is better to use the BETWEEN operator in this case to obtain the same result." }, { "code": null, "e": 6361, "s": 6306, "text": "SELECT * \nFROM Customers\nWHERE age BETWEEN 25 AND 50;\n" }, { "code": null, "e": 6691, "s": 6361, "text": "The HAVING clause is used with the GROUP BY clause to enforce conditions as the WHERE clause cannot be used with aggregate functions. However, the HAVING clause does not allow the usage of indexes which slows the execution time of the query. So it is better to use the WHERE clause instead of the HAVING clause whenever possible." }, { "code": null, "e": 6871, "s": 6691, "text": "Example: This is a query that displays the Customer FirstNames with the count of customers who have them for the customers aged more than 25. This is done using the HAVING clause." }, { "code": null, "e": 6950, "s": 6871, "text": "SELECT FirstName, COUNT(*)\nFROM Customers\nGROUP BY FirstName\nHAVING Age > 25;\n" }, { "code": null, "e": 7144, "s": 6950, "text": "It is better to use the WHERE clause in this case as it applies the condition to individual rows rather than the HAVING clause that applies the condition to the result from the GROUP BY clause." }, { "code": null, "e": 7222, "s": 7144, "text": "SELECT FirstName, COUNT(*)\nFROM Customers\nwhere Age > 25\nGROUP BY FirstName;\n" }, { "code": null, "e": 7592, "s": 7222, "text": "Using the WHERE clause for creating joins results in a Cartesian Product where the number of rows is the product of the number of rows of the two tables. This is obviously problematic for large databases as more database resources are required. So it is much better to use INNER JOIN as that only combines the rows from both tables which satisfy the required condition." }, { "code": null, "e": 7724, "s": 7592, "text": "Example: This is a query that displays the CustomerID of the customers that have currently ordered products using the WHERE clause." }, { "code": null, "e": 7833, "s": 7724, "text": "SELECT DISTINCT Customers.CustomerID\nFROM Customers, Orders\nWHERE Customers.CustomerID = Orders.CustomerID;\n" }, { "code": null, "e": 7908, "s": 7833, "text": "It is better to use the Inner join in this case to obtain the same result." }, { "code": null, "e": 8024, "s": 7908, "text": "SELECT DISTINCT Customers.CustomerID\nFROM Customers INNER JOIN Orders\nON Customers.CustomerID = Orders.CustomerID;\n" }, { "code": null, "e": 8458, "s": 8024, "text": "Wildcard characters such as % and _ are used to filter out the results of a LIKE clause. However, they should not be used at the beginning of the pattern as this disables the database from using the index. In that case, a full table scan is required to match the pattern which consumes more database resources. So it is better to avoid the wildcard characters at the beginning of the pattern and only use them at the end if possible." }, { "code": null, "e": 8467, "s": 8458, "text": "Example:" }, { "code": null, "e": 8519, "s": 8467, "text": "SELECT * FROM Customers\nWHERE FirstName LIKE '%A%'\n" }, { "code": null, "e": 8695, "s": 8519, "text": "The above query is inefficient as it uses the wildcard character % at the beginning of the pattern. A much more efficient version of the query that avoids this is given below:" }, { "code": null, "e": 8746, "s": 8695, "text": "SELECT * FROM Customers\nWHERE FirstName LIKE 'A%'\n" }, { "code": null, "e": 8756, "s": 8746, "text": "Marketing" }, { "code": null, "e": 8760, "s": 8756, "text": "SQL" }, { "code": null, "e": 8764, "s": 8760, "text": "SQL" }, { "code": null, "e": 8862, "s": 8764, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8928, "s": 8862, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 8952, "s": 8928, "text": "SQL Interview Questions" }, { "code": null, "e": 8964, "s": 8952, "text": "SQL | Views" }, { "code": null, "e": 9009, "s": 8964, "text": "Difference between DELETE, DROP and TRUNCATE" }, { "code": null, "e": 9041, "s": 9009, "text": "MySQL | Group_CONCAT() Function" }, { "code": null, "e": 9065, "s": 9041, "text": "Window functions in SQL" }, { "code": null, "e": 9080, "s": 9065, "text": "SQL | GROUP BY" }, { "code": null, "e": 9119, "s": 9080, "text": "Difference between DDL and DML in DBMS" }, { "code": null, "e": 9158, "s": 9119, "text": "Difference between DELETE and TRUNCATE" } ]
Sum of squares of all Subsets of given Array
13 Mar, 2022 Given an array arr[]. The value of a subset of array A is defined as the sum of squares of all the numbers in that subset. The task is to calculate the sum of values of all possible non-empty subsets of the given array. Since, the answer can be large print the val mod 1000000007.Examples: Input: arr[] = {3, 7} Output: 116 val({3}) = 32 = 9 val({7}) = 72 = 49 val({3, 7}) = 32 + 72 = 9 + 49 = 58 9 + 49 + 58 = 116Input: arr[] = {1, 1, 1} Output: 12 Naive approach: A simple approach is to find all the subset and then square each element in that subset and add it to the result. The time complexity of this approach will be O(2N)Efficient approach: It can be observed that in all the possible subsets of the given array, every element will occur 2N – 1 times where N is the size of the array. So the contribution of any element X in the sum will be 2N – 1 * X2.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; const int mod = 1e9 + 7; // Function to return (2^P % mod)long long power(int p){ long long res = 1; for (int i = 1; i <= p; ++i) { res *= 2; res %= mod; } return res % mod;} // Function to return the sum of squares of subsetslong long subset_square_sum(vector<int>& A){ int n = (int)A.size(); long long ans = 0; // Sqauaring the elements // and adding it to ans for (int i : A) { ans += (1LL * i * i) % mod; ans %= mod; } return (1LL * ans * power(n - 1)) % mod;} // Driver codeint main(){ vector<int> A = { 3, 7 }; cout << subset_square_sum(A); return 0;} // Java implementation of the approachclass GFG{ static final int mod = (int)(1e9 + 7); // Function to return (2^P % mod) static long power(int p) { long res = 1; for (int i = 1; i <= p; ++i) { res *= 2; res %= mod; } return res % mod; } // Function to return the sum of squares of subsets static long subset_square_sum(int A[]) { int n = A.length; long ans = 0; // Sqauaring the elements // and adding it to ans for (int i : A) { ans += (1 * i * i) % mod; ans %= mod; } return (1 * ans * power(n - 1)) % mod; } // Driver code public static void main (String[] args) { int A[] = { 3, 7 }; System.out.println(subset_square_sum(A)); }} // This code is contributed by AnkitRai01 # Python3 implementation of the approachmod = 10**9 + 7 # Function to return (2^P % mod)def power(p): res = 1 for i in range(1, p + 1): res *= 2 res %= mod return res % mod # Function to return the sum of# squares of subsetsdef subset_square_sum(A): n = len(A) ans = 0 # Squaring the elements # and adding it to ans for i in A: ans += i * i % mod ans %= mod return ans * power(n - 1) % mod # Driver codeA = [3, 7] print(subset_square_sum(A)) # This code is contributed by Mohit Kumar // C# implementation of the approachusing System; class GFG{ static readonly int mod = (int)(1e9 + 7); // Function to return (2^P % mod) static long power(int p) { long res = 1; for (int i = 1; i <= p; ++i) { res *= 2; res %= mod; } return res % mod; } // Function to return the sum of squares of subsets static long subset_square_sum(int []A) { int n = A.Length; long ans = 0; // Sqauaring the elements // and adding it to ans foreach (int i in A) { ans += (1 * i * i) % mod; ans %= mod; } return (1 * ans * power(n - 1)) % mod; } // Driver code public static void Main (String[] args) { int []A = { 3, 7 }; Console.WriteLine(subset_square_sum(A)); }} // This code is contributed by 29AjayKumar <script>// Javascript implementation of the approach const mod = 1000000000 + 7; // Function to return (2^P % mod)function power(p){ let res = 1; for (let i = 1; i <= p; ++i) { res *= 2; res %= mod; } return res % mod;} // Function to return the sum of squares of subsetsfunction subset_square_sum(A){ let n = A.length; let ans = 0; // Sqauaring the elements // and adding it to ans for (let i = 0; i < n; i++) { ans += (A[i] * A[i]) % mod; ans %= mod; } return (ans * power(n - 1)) % mod;} // Driver code let A = [ 3, 7 ]; document.write(subset_square_sum(A));</script> 116 Time Complexity: O(N) Auxiliary Space: O(1) mohit kumar 29 ankthon 29AjayKumar subham348 subhammahato348 subset Arrays Mathematical Arrays Mathematical subset Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Multidimensional Arrays in Java Stack Data Structure (Introduction and Program) Linear Search Set in C++ Standard Template Library (STL) Write a program to print all permutations of a given string C++ Data Types Merge two sorted arrays Operators in C / C++
[ { "code": null, "e": 28, "s": 0, "text": "\n13 Mar, 2022" }, { "code": null, "e": 320, "s": 28, "text": "Given an array arr[]. The value of a subset of array A is defined as the sum of squares of all the numbers in that subset. The task is to calculate the sum of values of all possible non-empty subsets of the given array. Since, the answer can be large print the val mod 1000000007.Examples: " }, { "code": null, "e": 482, "s": 320, "text": "Input: arr[] = {3, 7} Output: 116 val({3}) = 32 = 9 val({7}) = 72 = 49 val({3, 7}) = 32 + 72 = 9 + 49 = 58 9 + 49 + 58 = 116Input: arr[] = {1, 1, 1} Output: 12 " }, { "code": null, "e": 949, "s": 484, "text": "Naive approach: A simple approach is to find all the subset and then square each element in that subset and add it to the result. The time complexity of this approach will be O(2N)Efficient approach: It can be observed that in all the possible subsets of the given array, every element will occur 2N – 1 times where N is the size of the array. So the contribution of any element X in the sum will be 2N – 1 * X2.Below is the implementation of the above approach: " }, { "code": null, "e": 953, "s": 949, "text": "C++" }, { "code": null, "e": 958, "s": 953, "text": "Java" }, { "code": null, "e": 966, "s": 958, "text": "Python3" }, { "code": null, "e": 969, "s": 966, "text": "C#" }, { "code": null, "e": 980, "s": 969, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; const int mod = 1e9 + 7; // Function to return (2^P % mod)long long power(int p){ long long res = 1; for (int i = 1; i <= p; ++i) { res *= 2; res %= mod; } return res % mod;} // Function to return the sum of squares of subsetslong long subset_square_sum(vector<int>& A){ int n = (int)A.size(); long long ans = 0; // Sqauaring the elements // and adding it to ans for (int i : A) { ans += (1LL * i * i) % mod; ans %= mod; } return (1LL * ans * power(n - 1)) % mod;} // Driver codeint main(){ vector<int> A = { 3, 7 }; cout << subset_square_sum(A); return 0;}", "e": 1696, "s": 980, "text": null }, { "code": "// Java implementation of the approachclass GFG{ static final int mod = (int)(1e9 + 7); // Function to return (2^P % mod) static long power(int p) { long res = 1; for (int i = 1; i <= p; ++i) { res *= 2; res %= mod; } return res % mod; } // Function to return the sum of squares of subsets static long subset_square_sum(int A[]) { int n = A.length; long ans = 0; // Sqauaring the elements // and adding it to ans for (int i : A) { ans += (1 * i * i) % mod; ans %= mod; } return (1 * ans * power(n - 1)) % mod; } // Driver code public static void main (String[] args) { int A[] = { 3, 7 }; System.out.println(subset_square_sum(A)); }} // This code is contributed by AnkitRai01", "e": 2590, "s": 1696, "text": null }, { "code": "# Python3 implementation of the approachmod = 10**9 + 7 # Function to return (2^P % mod)def power(p): res = 1 for i in range(1, p + 1): res *= 2 res %= mod return res % mod # Function to return the sum of# squares of subsetsdef subset_square_sum(A): n = len(A) ans = 0 # Squaring the elements # and adding it to ans for i in A: ans += i * i % mod ans %= mod return ans * power(n - 1) % mod # Driver codeA = [3, 7] print(subset_square_sum(A)) # This code is contributed by Mohit Kumar", "e": 3135, "s": 2590, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ static readonly int mod = (int)(1e9 + 7); // Function to return (2^P % mod) static long power(int p) { long res = 1; for (int i = 1; i <= p; ++i) { res *= 2; res %= mod; } return res % mod; } // Function to return the sum of squares of subsets static long subset_square_sum(int []A) { int n = A.Length; long ans = 0; // Sqauaring the elements // and adding it to ans foreach (int i in A) { ans += (1 * i * i) % mod; ans %= mod; } return (1 * ans * power(n - 1)) % mod; } // Driver code public static void Main (String[] args) { int []A = { 3, 7 }; Console.WriteLine(subset_square_sum(A)); }} // This code is contributed by 29AjayKumar", "e": 4057, "s": 3135, "text": null }, { "code": "<script>// Javascript implementation of the approach const mod = 1000000000 + 7; // Function to return (2^P % mod)function power(p){ let res = 1; for (let i = 1; i <= p; ++i) { res *= 2; res %= mod; } return res % mod;} // Function to return the sum of squares of subsetsfunction subset_square_sum(A){ let n = A.length; let ans = 0; // Sqauaring the elements // and adding it to ans for (let i = 0; i < n; i++) { ans += (A[i] * A[i]) % mod; ans %= mod; } return (ans * power(n - 1)) % mod;} // Driver code let A = [ 3, 7 ]; document.write(subset_square_sum(A));</script>", "e": 4700, "s": 4057, "text": null }, { "code": null, "e": 4704, "s": 4700, "text": "116" }, { "code": null, "e": 4728, "s": 4706, "text": "Time Complexity: O(N)" }, { "code": null, "e": 4751, "s": 4728, "text": "Auxiliary Space: O(1) " }, { "code": null, "e": 4766, "s": 4751, "text": "mohit kumar 29" }, { "code": null, "e": 4774, "s": 4766, "text": "ankthon" }, { "code": null, "e": 4786, "s": 4774, "text": "29AjayKumar" }, { "code": null, "e": 4796, "s": 4786, "text": "subham348" }, { "code": null, "e": 4812, "s": 4796, "text": "subhammahato348" }, { "code": null, "e": 4819, "s": 4812, "text": "subset" }, { "code": null, "e": 4826, "s": 4819, "text": "Arrays" }, { "code": null, "e": 4839, "s": 4826, "text": "Mathematical" }, { "code": null, "e": 4846, "s": 4839, "text": "Arrays" }, { "code": null, "e": 4859, "s": 4846, "text": "Mathematical" }, { "code": null, "e": 4866, "s": 4859, "text": "subset" }, { "code": null, "e": 4964, "s": 4866, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5032, "s": 4964, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 5076, "s": 5032, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 5108, "s": 5076, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 5156, "s": 5108, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 5170, "s": 5156, "text": "Linear Search" }, { "code": null, "e": 5213, "s": 5170, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 5273, "s": 5213, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 5288, "s": 5273, "text": "C++ Data Types" }, { "code": null, "e": 5312, "s": 5288, "text": "Merge two sorted arrays" } ]
What is a clean, Pythonic way to have multiple constructors in Python?
29 Dec, 2020 Prerequisite – Constructors, @classmethod decorators Python does not support explicit multiple constructors, yet there are some ways using which the multiple constructors can be achieved. If multiple __init__ methods are written for the same class, then the latest one overwrites all the previous constructors. Look at the example below. Python3 class example: def __init__(self): print("One") def __init__(self): print("Two") def __init__(self): print("Three") e = example() Three Multiple constructors are required when one has to perform different actions on the instantiation of a class. This is useful when the class has to perform different actions on different parameters. The class constructors can be made to exhibit polymorphism in three ways which are listed below. Overloading constructors based on arguments.Calling methods from __init__.Using @classmethod decorator. Overloading constructors based on arguments. Calling methods from __init__. Using @classmethod decorator. This article explains how to have multiple constructors in a clean and Pythonic way with examples. The constructor overloading is done by checking conditions for the arguments passed and performing required actions. For example, consider passing an argument to the class sample, If the parameter is an int, the square of the number should be the answer. If the parameter is a String, the answer should be “Hello!!”+string. If the parameter is of length greater than 1, the sum of arguments should be stored as the answer. Python3 class sample: # constructor overloading # based on args def __init__(self, *args): # if args are more than 1 # sum of args if len(args) > 1: self.ans = 0 for i in args: self.ans += i # if arg is an integer # square the arg elif isinstance(args[0], int): self.ans = args[0]*args[0] # if arg is string # Print with hello elif isinstance(args[0], str): self.ans = "Hello! "+args[0]+"." s1 = sample(1, 2, 3, 4, 5)print("Sum of list :", s1.ans) s2 = sample(5)print("Square of int :", s2.ans) s3 = sample("GeeksforGeeks")print("String :", s3.ans) Sum of list : 15 Square of int : 25 String : Hello! GeeksforGeeks. In the code above, the instance variable was ans, but its values differ based on the arguments. Since a variable number of arguments for the class, *args is used which is a tuple that contains the arguments passed and can be accessed using an index. In the case of int and string, only one argument is passed and thus accessed as args[0] (the only element in the tuple). A class can have one constructor __init__ which can perform any action when the instance of the class is created. This constructor can be made to different functions that carry out different actions based on the arguments passed. Now consider an example : If the number of arguments passed is 2, then evaluate the expression x = a2-b2 If the number of arguments passed is 3, then evaluate the expression y = a2+b2-c. If more than 3 arguments have been passed, then sum up the squares, divide it by the highest value in the arguments passed. Python3 class eval_equations: # single constructor to call other methods def __init__(self, *inp): # when 2 arguments are passed if len(inp) == 2: self.ans = self.eq2(inp) # when 3 arguments are passed elif len(inp) == 3: self.ans = self.eq1(inp) # when more than 3 arguments are passed else: self.ans = self.eq3(inp) def eq1(self, args): x = (args[0]*args[0])+(args[1]*args[1])-args[2] return x def eq2(self, args): y = (args[0]*args[0])-(args[1]*args[1]) return y def eq3(self, args): temp = 0 for i in range(0, len(args)): temp += args[i]*args[i] temp = temp/max(args) z = temp return z inp1 = eval_equations(1, 2)inp2 = eval_equations(1, 2, 3)inp3 = eval_equations(1, 2, 3, 4, 5) print("equation 2 :", inp1.ans)print("equation 1 :", inp2.ans)print("equation 3 :", inp3.ans) equation 2 : -3 equation 1 : 2 equation 3 : 11.0 In the example above, the equation to be evaluated is written on different instance methods and made to return the answer. The constructor calls the appropriate method and acts differently for different parameters. The expressions have been evaluated as follows: inputs : 1,2 —> 12-22 = 1-4 = -3 inputs : 1,2,3 —> (12 + 22) – 3 = 5-3 = 2 inputs : 1,2,3,4,5 —> (12 + 22 + 32 + 42 + 52) / 5 = 55/5 = 11.0 This decorator allows a function to be accessible without instantiating the class. The functions can be accessed both by the instance of the class and the class itself. The first parameter of the method that is declared as classmethod is cls, which is like the self of the instance methods. Here cls refer to the class itself. This proves to be very helpful to use multiple constructors in Python and is a more Pythonic approach considered to the above ones. Consider the same example used above. Evaluate different expressions based on the number of inputs. Python3 class eval_equations: # basic constructor def __init__(self, a): self.ans = a # expression 1 @classmethod def eq1(cls, args): # create an object for the class to return x = cls((args[0]*args[0])+(args[1]*args[1])-args[2]) return x # expression 2 @classmethod def eq2(cls, args): y = cls((args[0]*args[0])-(args[1]*args[1])) return y # expression 3 @classmethod def eq3(cls, args): temp = 0 # square of each element for i in range(0, len(args)): temp += args[i]*args[i] temp = temp/max(args) z = cls(temp) return z li = [[1, 2], [1, 2, 3], [1, 2, 3, 4, 5]]i = 0 # loop to get input three timeswhile i < 3: inp = li[i] # no.of.arguments = 2 if len(inp) == 2: p = eval_equations.eq2(inp) print("equation 2 :", p.ans) # no.of.arguments = 3 elif len(inp) == 3: p = eval_equations.eq1(inp) print("equation 1 :", p.ans) # More than three arguments else: p = eval_equations.eq3(inp) print("equation 3 :", p.ans) #increment loop i += 1 equation 2 : -3 equation 1 : 2 equation 3 : 11.0 In the example above, the instance of the object is not created initially. The class methods to evaluate various expression has been defined with @classmethod decorator. Now they can be called with the class name and the object is created in that class method after evaluating the expression. The instance variable holds different answers for a different number of parameters passed. Python Oops-programs Python-OOP python-oop-concepts Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Dec, 2020" }, { "code": null, "e": 81, "s": 28, "text": "Prerequisite – Constructors, @classmethod decorators" }, { "code": null, "e": 366, "s": 81, "text": "Python does not support explicit multiple constructors, yet there are some ways using which the multiple constructors can be achieved. If multiple __init__ methods are written for the same class, then the latest one overwrites all the previous constructors. Look at the example below." }, { "code": null, "e": 374, "s": 366, "text": "Python3" }, { "code": "class example: def __init__(self): print(\"One\") def __init__(self): print(\"Two\") def __init__(self): print(\"Three\") e = example()", "e": 543, "s": 374, "text": null }, { "code": null, "e": 550, "s": 543, "text": "Three\n" }, { "code": null, "e": 845, "s": 550, "text": "Multiple constructors are required when one has to perform different actions on the instantiation of a class. This is useful when the class has to perform different actions on different parameters. The class constructors can be made to exhibit polymorphism in three ways which are listed below." }, { "code": null, "e": 949, "s": 845, "text": "Overloading constructors based on arguments.Calling methods from __init__.Using @classmethod decorator." }, { "code": null, "e": 994, "s": 949, "text": "Overloading constructors based on arguments." }, { "code": null, "e": 1025, "s": 994, "text": "Calling methods from __init__." }, { "code": null, "e": 1055, "s": 1025, "text": "Using @classmethod decorator." }, { "code": null, "e": 1154, "s": 1055, "text": "This article explains how to have multiple constructors in a clean and Pythonic way with examples." }, { "code": null, "e": 1335, "s": 1154, "text": "The constructor overloading is done by checking conditions for the arguments passed and performing required actions. For example, consider passing an argument to the class sample, " }, { "code": null, "e": 1410, "s": 1335, "text": "If the parameter is an int, the square of the number should be the answer." }, { "code": null, "e": 1479, "s": 1410, "text": "If the parameter is a String, the answer should be “Hello!!”+string." }, { "code": null, "e": 1578, "s": 1479, "text": "If the parameter is of length greater than 1, the sum of arguments should be stored as the answer." }, { "code": null, "e": 1586, "s": 1578, "text": "Python3" }, { "code": "class sample: # constructor overloading # based on args def __init__(self, *args): # if args are more than 1 # sum of args if len(args) > 1: self.ans = 0 for i in args: self.ans += i # if arg is an integer # square the arg elif isinstance(args[0], int): self.ans = args[0]*args[0] # if arg is string # Print with hello elif isinstance(args[0], str): self.ans = \"Hello! \"+args[0]+\".\" s1 = sample(1, 2, 3, 4, 5)print(\"Sum of list :\", s1.ans) s2 = sample(5)print(\"Square of int :\", s2.ans) s3 = sample(\"GeeksforGeeks\")print(\"String :\", s3.ans)", "e": 2271, "s": 1586, "text": null }, { "code": null, "e": 2339, "s": 2271, "text": "Sum of list : 15\nSquare of int : 25\nString : Hello! GeeksforGeeks.\n" }, { "code": null, "e": 2710, "s": 2339, "text": "In the code above, the instance variable was ans, but its values differ based on the arguments. Since a variable number of arguments for the class, *args is used which is a tuple that contains the arguments passed and can be accessed using an index. In the case of int and string, only one argument is passed and thus accessed as args[0] (the only element in the tuple)." }, { "code": null, "e": 2967, "s": 2710, "text": "A class can have one constructor __init__ which can perform any action when the instance of the class is created. This constructor can be made to different functions that carry out different actions based on the arguments passed. Now consider an example : " }, { "code": null, "e": 3046, "s": 2967, "text": "If the number of arguments passed is 2, then evaluate the expression x = a2-b2" }, { "code": null, "e": 3128, "s": 3046, "text": "If the number of arguments passed is 3, then evaluate the expression y = a2+b2-c." }, { "code": null, "e": 3252, "s": 3128, "text": "If more than 3 arguments have been passed, then sum up the squares, divide it by the highest value in the arguments passed." }, { "code": null, "e": 3260, "s": 3252, "text": "Python3" }, { "code": "class eval_equations: # single constructor to call other methods def __init__(self, *inp): # when 2 arguments are passed if len(inp) == 2: self.ans = self.eq2(inp) # when 3 arguments are passed elif len(inp) == 3: self.ans = self.eq1(inp) # when more than 3 arguments are passed else: self.ans = self.eq3(inp) def eq1(self, args): x = (args[0]*args[0])+(args[1]*args[1])-args[2] return x def eq2(self, args): y = (args[0]*args[0])-(args[1]*args[1]) return y def eq3(self, args): temp = 0 for i in range(0, len(args)): temp += args[i]*args[i] temp = temp/max(args) z = temp return z inp1 = eval_equations(1, 2)inp2 = eval_equations(1, 2, 3)inp3 = eval_equations(1, 2, 3, 4, 5) print(\"equation 2 :\", inp1.ans)print(\"equation 1 :\", inp2.ans)print(\"equation 3 :\", inp3.ans)", "e": 4220, "s": 3260, "text": null }, { "code": null, "e": 4270, "s": 4220, "text": "equation 2 : -3\nequation 1 : 2\nequation 3 : 11.0\n" }, { "code": null, "e": 4486, "s": 4270, "text": " In the example above, the equation to be evaluated is written on different instance methods and made to return the answer. The constructor calls the appropriate method and acts differently for different parameters." }, { "code": null, "e": 4534, "s": 4486, "text": "The expressions have been evaluated as follows:" }, { "code": null, "e": 4567, "s": 4534, "text": "inputs : 1,2 —> 12-22 = 1-4 = -3" }, { "code": null, "e": 4610, "s": 4567, "text": "inputs : 1,2,3 —> (12 + 22) – 3 = 5-3 = 2" }, { "code": null, "e": 4675, "s": 4610, "text": "inputs : 1,2,3,4,5 —> (12 + 22 + 32 + 42 + 52) / 5 = 55/5 = 11.0" }, { "code": null, "e": 5234, "s": 4675, "text": "This decorator allows a function to be accessible without instantiating the class. The functions can be accessed both by the instance of the class and the class itself. The first parameter of the method that is declared as classmethod is cls, which is like the self of the instance methods. Here cls refer to the class itself. This proves to be very helpful to use multiple constructors in Python and is a more Pythonic approach considered to the above ones. Consider the same example used above. Evaluate different expressions based on the number of inputs." }, { "code": null, "e": 5242, "s": 5234, "text": "Python3" }, { "code": "class eval_equations: # basic constructor def __init__(self, a): self.ans = a # expression 1 @classmethod def eq1(cls, args): # create an object for the class to return x = cls((args[0]*args[0])+(args[1]*args[1])-args[2]) return x # expression 2 @classmethod def eq2(cls, args): y = cls((args[0]*args[0])-(args[1]*args[1])) return y # expression 3 @classmethod def eq3(cls, args): temp = 0 # square of each element for i in range(0, len(args)): temp += args[i]*args[i] temp = temp/max(args) z = cls(temp) return z li = [[1, 2], [1, 2, 3], [1, 2, 3, 4, 5]]i = 0 # loop to get input three timeswhile i < 3: inp = li[i] # no.of.arguments = 2 if len(inp) == 2: p = eval_equations.eq2(inp) print(\"equation 2 :\", p.ans) # no.of.arguments = 3 elif len(inp) == 3: p = eval_equations.eq1(inp) print(\"equation 1 :\", p.ans) # More than three arguments else: p = eval_equations.eq3(inp) print(\"equation 3 :\", p.ans) #increment loop i += 1", "e": 6406, "s": 5242, "text": null }, { "code": null, "e": 6456, "s": 6406, "text": "equation 2 : -3\nequation 1 : 2\nequation 3 : 11.0\n" }, { "code": null, "e": 6840, "s": 6456, "text": "In the example above, the instance of the object is not created initially. The class methods to evaluate various expression has been defined with @classmethod decorator. Now they can be called with the class name and the object is created in that class method after evaluating the expression. The instance variable holds different answers for a different number of parameters passed." }, { "code": null, "e": 6861, "s": 6840, "text": "Python Oops-programs" }, { "code": null, "e": 6872, "s": 6861, "text": "Python-OOP" }, { "code": null, "e": 6892, "s": 6872, "text": "python-oop-concepts" }, { "code": null, "e": 6899, "s": 6892, "text": "Python" } ]
Breaking an Integer to get Maximum Product
23 Jun, 2022 Given a number n, the task is to break n in such a way that multiplication of its parts is maximized. Input : n = 10 Output : 36 10 = 4 + 3 + 3 and 4 * 3 * 3 = 36 is maximum possible product. Input : n = 8 Output : 18 8 = 2 + 3 + 3 and 2 * 3 * 3 = 18 is maximum possible product. Mathematically, we are given n and we need to maximize a1 * a2 * a3 .... * aK such that n = a1 + a2 + a3 ... + aK and a1, a2, ... ak > 0.Note that we need to break given Integer in at least two parts in this problem for maximizing the product. Method 1 – Now we know from maxima-minima concept that, If an integer need to break in two parts, then to maximize their product those part should be equal. Using this concept lets break n into (n/x) x’s then their product will be x(n/x), now if we take derivative of this product and make that equal to 0 for maxima, we will get to know that value of x should be e (base of the natural logarithm) for maximum product. As we know that 2 < e < 3, so we should break every Integer into 2 or 3 only for maximum product. Next thing is 6 = 3 + 3 = 2 + 2 + 2, but 3 * 3 > 2 * 2 * 2, that is every triplet of 2 can be replaced with tuple of 3 for maximum product, so we will keep breaking the number in terms of 3 only, until number remains as 4 or 2, which we will be broken into 2*2 (2*2 > 3*1) and 2 respectively and we will get our maximum product. In short, procedure to get maximum product is as follows – Try to break integer in power of 3 only and when integer remains small (<5) then use brute force. The complexity of below program is O(log N), because of repeated squaring power method. Below is the implementation of above approach: C++ Java Python3 C# PHP Javascript // C/C++ program to find maximum product by breaking// the Integer#include <bits/stdc++.h>using namespace std; // method return x^a in log(a) timeint power(int x, int a){ int res = 1; while (a) { if (a & 1) res = res * x; x = x * x; a >>= 1; } return res;} // Method returns maximum product obtained by// breaking Nint breakInteger(int N){ // base case 2 = 1 + 1 if (N == 2) return 1; // base case 3 = 2 + 1 if (N == 3) return 2; int maxProduct; // breaking based on mod with 3 switch (N % 3) { // If divides evenly, then break into all 3 case 0: maxProduct = power(3, N / 3); break; // If division gives mod as 1, then break as // 4 + power of 3 for remaining part case 1: maxProduct = 2 * 2 * power(3, (N / 3) - 1); break; // If division gives mod as 2, then break as // 2 + power of 3 for remaining part case 2: maxProduct = 2 * power(3, N / 3); break; } return maxProduct;} // Driver code to test above methodsint main(){ int maxProduct = breakInteger(10); cout << maxProduct << endl; return 0;} // Java program to find maximum product by breaking// the Integer class GFG { // method return x^a in log(a) time static int power(int x, int a) { int res = 1; while (a > 0) { if ((a & 1) > 0) res = res * x; x = x * x; a >>= 1; } return res; } // Method returns maximum product obtained by // breaking N static int breakInteger(int N) { // base case 2 = 1 + 1 if (N == 2) return 1; // base case 3 = 2 + 1 if (N == 3) return 2; int maxProduct = -1; // breaking based on mod with 3 switch (N % 3) { // If divides evenly, then break into all 3 case 0: maxProduct = power(3, N / 3); break; // If division gives mod as 1, then break as // 4 + power of 3 for remaining part case 1: maxProduct = 2 * 2 * power(3, (N / 3) - 1); break; // If division gives mod as 2, then break as // 2 + power of 3 for remaining part case 2: maxProduct = 2 * power(3, N / 3); break; } return maxProduct; } // Driver code to test above methods public static void main(String[] args) { int maxProduct = breakInteger(10); System.out.println(maxProduct); }}// This code is contributed by mits # Python3 program to find maximum product by breaking# the Integer # method return x^a in log(a) time def power(x, a): res = 1 while (a): if (a & 1): res = res * x x = x * x a >>= 1 return res # Method returns maximum product obtained by# breaking N def breakInteger(N): # base case 2 = 1 + 1 if (N == 2): return 1 # base case 3 = 2 + 1 if (N == 3): return 2 maxProduct = 0 # breaking based on mod with 3 if(N % 3 == 0): # If divides evenly, then break into all 3 maxProduct = power(3, int(N/3)) return maxProduct else if(N % 3 == 1): # If division gives mod as 1, then break as # 4 + power of 3 for remaining part maxProduct = 2 * 2 * power(3, int(N/3) - 1) return maxProduct else if(N % 3 == 2): # If division gives mod as 2, then break as # 2 + power of 3 for remaining part maxProduct = 2 * power(3, int(N/3)) return maxProduct # Driver code to test above methods maxProduct = breakInteger(10)print(maxProduct) # This code is contributed by mits // C# program to find maximum product by breaking// the Integer class GFG { // method return x^a in log(a) time static int power(int x, int a) { int res = 1; while (a > 0) { if ((a & 1) > 0) res = res * x; x = x * x; a >>= 1; } return res; } // Method returns maximum product obtained by // breaking N static int breakInteger(int N) { // base case 2 = 1 + 1 if (N == 2) return 1; // base case 3 = 2 + 1 if (N == 3) return 2; int maxProduct = -1; // breaking based on mod with 3 switch (N % 3) { // If divides evenly, then break into all 3 case 0: maxProduct = power(3, N / 3); break; // If division gives mod as 1, then break as // 4 + power of 3 for remaining part case 1: maxProduct = 2 * 2 * power(3, (N / 3) - 1); break; // If division gives mod as 2, then break as // 2 + power of 3 for remaining part case 2: maxProduct = 2 * power(3, N / 3); break; } return maxProduct; } // Driver code to test above methods public static void Main() { int maxProduct = breakInteger(10); System.Console.WriteLine(maxProduct); }}// This code is contributed by mits <?php// PHP program to find maximum product by breaking// the Integer // method return x^a in log(a) timefunction power($x, $a){ $res = 1; while ($a) { if ($a & 1) $res = $res * $x; $x = $x * $x; $a >>= 1; } return $res;} // Method returns maximum product obtained by// breaking Nfunction breakInteger($N){ // base case 2 = 1 + 1 if ($N == 2) return 1; // base case 3 = 2 + 1 if ($N == 3) return 2; $maxProduct=0; // breaking based on mod with 3 switch ($N % 3) { // If divides evenly, then break into all 3 case 0: $maxProduct = power(3, $N/3); break; // If division gives mod as 1, then break as // 4 + power of 3 for remaining part case 1: $maxProduct = 2 * 2 * power(3, ($N/3) - 1); break; // If division gives mod as 2, then break as // 2 + power of 3 for remaining part case 2: $maxProduct = 2 * power(3, $N/3); break; } return $maxProduct;} // Driver code to test above methods $maxProduct = breakInteger(10); echo $maxProduct; // This code is contributed by mits?> <script> // Javascript program to find maximum// product by breaking the Integer // Method return x^a in log(a) timefunction power(x, a){ let res = 1; while (a > 0) { if ((a & 1) > 0) res = res * x; x = x * x; a >>= 1; } return res;} // Method returns maximum product obtained by// breaking Nfunction breakInteger(N){ // Base case 2 = 1 + 1 if (N == 2) return 1; // Base case 3 = 2 + 1 if (N == 3) return 2; let maxProduct; // Breaking based on mod with 3 switch (N % 3) { // If divides evenly, then break into all 3 case 0: maxProduct = power(3, N / 3); break; // If division gives mod as 1, then break as // 4 + power of 3 for remaining part case 1: maxProduct = 2 * 2 * power(3, (N / 3) - 1); break; // If division gives mod as 2, then break as // 2 + power of 3 for remaining part case 2: maxProduct = 2 * power(3, N / 3); break; } return maxProduct;} // Driver codelet maxProduct = breakInteger(10);document.write(maxProduct); // This code is contributed by rameshtravel07 </script> 36 Method 2 – If we see some examples of this problems, we can easily observe following pattern.The maximum product can be obtained be repeatedly cutting parts of size 3 while size is greater than 4, keeping the last part as size of 2 or 3 or 4. For example, n = 10, the maximum product is obtained by 3, 3, 4. For n = 11, the maximum product is obtained by 3, 3, 3, 2. Following is the implementation of this approach. C++ Java Python3 C# Javascript #include <iostream>using namespace std; /* The main function that returns the max possible product */int maxProd(int n){ // n equals to 2 or 3 must be handled explicitly if (n == 2 || n == 3) return (n-1); // Keep removing parts of size 3 while n is greater than 4 int res = 1; while (n > 4) { n -= 3; res *= 3; // Keep multiplying 3 to res } return (n * res); // The last part multiplied by previous parts} /* Driver program to test above functions */int main(){ cout << "Maximum Product is " << maxProd(45); return 0;} public class GFG{ /* The main function that returns the max possible product */ static int maxProd(int n) { // n equals to 2 or 3 must be handled explicitly if (n == 2 || n == 3) return (n - 1); // Keep removing parts of size 3 while n is greater than 4 int res = 1; while (n > 4) { n -= 3; res *= 3; // Keep multiplying 3 to res } return (n * res); // The last part multiplied by previous parts } // Driver code public static void main(String[] args) { System.out.println("Maximum Product is " + maxProd(45)); }} // This code is contributed by divyeshrabadiya07 ''' The main function that returns the max possible product '''def maxProd(n): # n equals to 2 or 3 must be handled explicitly if (n == 2 or n == 3): return (n - 1); # Keep removing parts of size 3 while n is greater than 4 res = 1; while (n > 4): n -= 3; res *= 3; # Keep multiplying 3 to res return (n * res); # The last part multiplied by previous parts ''' Driver program to test above functions '''if __name__=='__main__': print("Maximum Product is", maxProd(45)) # This code is contributed by rutvik_56. using System;class GFG { /* The main function that returns the max possible product */ static int maxProd(int n) { // n equals to 2 or 3 must be handled explicitly if (n == 2 || n == 3) return (n - 1); // Keep removing parts of size 3 while n is greater than 4 int res = 1; while (n > 4) { n -= 3; res *= 3; // Keep multiplying 3 to res } return (n * res); // The last part multiplied by previous parts } // Driver code static void Main() { Console.WriteLine("Maximum Product is " + maxProd(45)); }} // This code is contributed by divyesh072019. <script> /* The main function that returns the max possible product */ function maxProd(n) { // n equals to 2 or 3 must be handled explicitly if (n == 2 || n == 3) return (n - 1); // Keep removing parts of size 3 while n is greater than 4 let res = 1; while (n > 4) { n -= 3; res *= 3; // Keep multiplying 3 to res } return (n * res); // The last part multiplied by previous parts } document.write("Maximum Product is " + maxProd(45)); </script> Maximum Product is 14348907 Time Complexity: O(n) Auxiliary Space: O(1) This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Mithun Kumar ShubhamShekhaliya bhavneet2000 divyeshrabadiya07 divyesh072019 rutvik_56 mukesh07 rameshtravel07 simmytarika5 shivamanandrj9 Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n23 Jun, 2022" }, { "code": null, "e": 157, "s": 54, "text": "Given a number n, the task is to break n in such a way that multiplication of its parts is maximized. " }, { "code": null, "e": 336, "s": 157, "text": "Input : n = 10\nOutput : 36\n10 = 4 + 3 + 3 and 4 * 3 * 3 = 36\nis maximum possible product.\n\nInput : n = 8\nOutput : 18\n8 = 2 + 3 + 3 and 2 * 3 * 3 = 18\nis maximum possible product." }, { "code": null, "e": 580, "s": 336, "text": "Mathematically, we are given n and we need to maximize a1 * a2 * a3 .... * aK such that n = a1 + a2 + a3 ... + aK and a1, a2, ... ak > 0.Note that we need to break given Integer in at least two parts in this problem for maximizing the product." }, { "code": null, "e": 592, "s": 580, "text": "Method 1 – " }, { "code": null, "e": 1673, "s": 592, "text": "Now we know from maxima-minima concept that, If an integer need to break in two parts, then to maximize their product those part should be equal. Using this concept lets break n into (n/x) x’s then their product will be x(n/x), now if we take derivative of this product and make that equal to 0 for maxima, we will get to know that value of x should be e (base of the natural logarithm) for maximum product. As we know that 2 < e < 3, so we should break every Integer into 2 or 3 only for maximum product. Next thing is 6 = 3 + 3 = 2 + 2 + 2, but 3 * 3 > 2 * 2 * 2, that is every triplet of 2 can be replaced with tuple of 3 for maximum product, so we will keep breaking the number in terms of 3 only, until number remains as 4 or 2, which we will be broken into 2*2 (2*2 > 3*1) and 2 respectively and we will get our maximum product. In short, procedure to get maximum product is as follows – Try to break integer in power of 3 only and when integer remains small (<5) then use brute force. The complexity of below program is O(log N), because of repeated squaring power method. " }, { "code": null, "e": 1721, "s": 1673, "text": "Below is the implementation of above approach: " }, { "code": null, "e": 1725, "s": 1721, "text": "C++" }, { "code": null, "e": 1730, "s": 1725, "text": "Java" }, { "code": null, "e": 1738, "s": 1730, "text": "Python3" }, { "code": null, "e": 1741, "s": 1738, "text": "C#" }, { "code": null, "e": 1745, "s": 1741, "text": "PHP" }, { "code": null, "e": 1756, "s": 1745, "text": "Javascript" }, { "code": "// C/C++ program to find maximum product by breaking// the Integer#include <bits/stdc++.h>using namespace std; // method return x^a in log(a) timeint power(int x, int a){ int res = 1; while (a) { if (a & 1) res = res * x; x = x * x; a >>= 1; } return res;} // Method returns maximum product obtained by// breaking Nint breakInteger(int N){ // base case 2 = 1 + 1 if (N == 2) return 1; // base case 3 = 2 + 1 if (N == 3) return 2; int maxProduct; // breaking based on mod with 3 switch (N % 3) { // If divides evenly, then break into all 3 case 0: maxProduct = power(3, N / 3); break; // If division gives mod as 1, then break as // 4 + power of 3 for remaining part case 1: maxProduct = 2 * 2 * power(3, (N / 3) - 1); break; // If division gives mod as 2, then break as // 2 + power of 3 for remaining part case 2: maxProduct = 2 * power(3, N / 3); break; } return maxProduct;} // Driver code to test above methodsint main(){ int maxProduct = breakInteger(10); cout << maxProduct << endl; return 0;}", "e": 2925, "s": 1756, "text": null }, { "code": "// Java program to find maximum product by breaking// the Integer class GFG { // method return x^a in log(a) time static int power(int x, int a) { int res = 1; while (a > 0) { if ((a & 1) > 0) res = res * x; x = x * x; a >>= 1; } return res; } // Method returns maximum product obtained by // breaking N static int breakInteger(int N) { // base case 2 = 1 + 1 if (N == 2) return 1; // base case 3 = 2 + 1 if (N == 3) return 2; int maxProduct = -1; // breaking based on mod with 3 switch (N % 3) { // If divides evenly, then break into all 3 case 0: maxProduct = power(3, N / 3); break; // If division gives mod as 1, then break as // 4 + power of 3 for remaining part case 1: maxProduct = 2 * 2 * power(3, (N / 3) - 1); break; // If division gives mod as 2, then break as // 2 + power of 3 for remaining part case 2: maxProduct = 2 * power(3, N / 3); break; } return maxProduct; } // Driver code to test above methods public static void main(String[] args) { int maxProduct = breakInteger(10); System.out.println(maxProduct); }}// This code is contributed by mits", "e": 4332, "s": 2925, "text": null }, { "code": "# Python3 program to find maximum product by breaking# the Integer # method return x^a in log(a) time def power(x, a): res = 1 while (a): if (a & 1): res = res * x x = x * x a >>= 1 return res # Method returns maximum product obtained by# breaking N def breakInteger(N): # base case 2 = 1 + 1 if (N == 2): return 1 # base case 3 = 2 + 1 if (N == 3): return 2 maxProduct = 0 # breaking based on mod with 3 if(N % 3 == 0): # If divides evenly, then break into all 3 maxProduct = power(3, int(N/3)) return maxProduct else if(N % 3 == 1): # If division gives mod as 1, then break as # 4 + power of 3 for remaining part maxProduct = 2 * 2 * power(3, int(N/3) - 1) return maxProduct else if(N % 3 == 2): # If division gives mod as 2, then break as # 2 + power of 3 for remaining part maxProduct = 2 * power(3, int(N/3)) return maxProduct # Driver code to test above methods maxProduct = breakInteger(10)print(maxProduct) # This code is contributed by mits", "e": 5454, "s": 4332, "text": null }, { "code": "// C# program to find maximum product by breaking// the Integer class GFG { // method return x^a in log(a) time static int power(int x, int a) { int res = 1; while (a > 0) { if ((a & 1) > 0) res = res * x; x = x * x; a >>= 1; } return res; } // Method returns maximum product obtained by // breaking N static int breakInteger(int N) { // base case 2 = 1 + 1 if (N == 2) return 1; // base case 3 = 2 + 1 if (N == 3) return 2; int maxProduct = -1; // breaking based on mod with 3 switch (N % 3) { // If divides evenly, then break into all 3 case 0: maxProduct = power(3, N / 3); break; // If division gives mod as 1, then break as // 4 + power of 3 for remaining part case 1: maxProduct = 2 * 2 * power(3, (N / 3) - 1); break; // If division gives mod as 2, then break as // 2 + power of 3 for remaining part case 2: maxProduct = 2 * power(3, N / 3); break; } return maxProduct; } // Driver code to test above methods public static void Main() { int maxProduct = breakInteger(10); System.Console.WriteLine(maxProduct); }}// This code is contributed by mits", "e": 6852, "s": 5454, "text": null }, { "code": "<?php// PHP program to find maximum product by breaking// the Integer // method return x^a in log(a) timefunction power($x, $a){ $res = 1; while ($a) { if ($a & 1) $res = $res * $x; $x = $x * $x; $a >>= 1; } return $res;} // Method returns maximum product obtained by// breaking Nfunction breakInteger($N){ // base case 2 = 1 + 1 if ($N == 2) return 1; // base case 3 = 2 + 1 if ($N == 3) return 2; $maxProduct=0; // breaking based on mod with 3 switch ($N % 3) { // If divides evenly, then break into all 3 case 0: $maxProduct = power(3, $N/3); break; // If division gives mod as 1, then break as // 4 + power of 3 for remaining part case 1: $maxProduct = 2 * 2 * power(3, ($N/3) - 1); break; // If division gives mod as 2, then break as // 2 + power of 3 for remaining part case 2: $maxProduct = 2 * power(3, $N/3); break; } return $maxProduct;} // Driver code to test above methods $maxProduct = breakInteger(10); echo $maxProduct; // This code is contributed by mits?>", "e": 8076, "s": 6852, "text": null }, { "code": "<script> // Javascript program to find maximum// product by breaking the Integer // Method return x^a in log(a) timefunction power(x, a){ let res = 1; while (a > 0) { if ((a & 1) > 0) res = res * x; x = x * x; a >>= 1; } return res;} // Method returns maximum product obtained by// breaking Nfunction breakInteger(N){ // Base case 2 = 1 + 1 if (N == 2) return 1; // Base case 3 = 2 + 1 if (N == 3) return 2; let maxProduct; // Breaking based on mod with 3 switch (N % 3) { // If divides evenly, then break into all 3 case 0: maxProduct = power(3, N / 3); break; // If division gives mod as 1, then break as // 4 + power of 3 for remaining part case 1: maxProduct = 2 * 2 * power(3, (N / 3) - 1); break; // If division gives mod as 2, then break as // 2 + power of 3 for remaining part case 2: maxProduct = 2 * power(3, N / 3); break; } return maxProduct;} // Driver codelet maxProduct = breakInteger(10);document.write(maxProduct); // This code is contributed by rameshtravel07 </script>", "e": 9315, "s": 8076, "text": null }, { "code": null, "e": 9318, "s": 9315, "text": "36" }, { "code": null, "e": 9330, "s": 9318, "text": "Method 2 – " }, { "code": null, "e": 9736, "s": 9330, "text": "If we see some examples of this problems, we can easily observe following pattern.The maximum product can be obtained be repeatedly cutting parts of size 3 while size is greater than 4, keeping the last part as size of 2 or 3 or 4. For example, n = 10, the maximum product is obtained by 3, 3, 4. For n = 11, the maximum product is obtained by 3, 3, 3, 2. Following is the implementation of this approach." }, { "code": null, "e": 9740, "s": 9736, "text": "C++" }, { "code": null, "e": 9745, "s": 9740, "text": "Java" }, { "code": null, "e": 9753, "s": 9745, "text": "Python3" }, { "code": null, "e": 9756, "s": 9753, "text": "C#" }, { "code": null, "e": 9767, "s": 9756, "text": "Javascript" }, { "code": "#include <iostream>using namespace std; /* The main function that returns the max possible product */int maxProd(int n){ // n equals to 2 or 3 must be handled explicitly if (n == 2 || n == 3) return (n-1); // Keep removing parts of size 3 while n is greater than 4 int res = 1; while (n > 4) { n -= 3; res *= 3; // Keep multiplying 3 to res } return (n * res); // The last part multiplied by previous parts} /* Driver program to test above functions */int main(){ cout << \"Maximum Product is \" << maxProd(45); return 0;}", "e": 10329, "s": 9767, "text": null }, { "code": "public class GFG{ /* The main function that returns the max possible product */ static int maxProd(int n) { // n equals to 2 or 3 must be handled explicitly if (n == 2 || n == 3) return (n - 1); // Keep removing parts of size 3 while n is greater than 4 int res = 1; while (n > 4) { n -= 3; res *= 3; // Keep multiplying 3 to res } return (n * res); // The last part multiplied by previous parts } // Driver code public static void main(String[] args) { System.out.println(\"Maximum Product is \" + maxProd(45)); }} // This code is contributed by divyeshrabadiya07", "e": 10943, "s": 10329, "text": null }, { "code": " ''' The main function that returns the max possible product '''def maxProd(n): # n equals to 2 or 3 must be handled explicitly if (n == 2 or n == 3): return (n - 1); # Keep removing parts of size 3 while n is greater than 4 res = 1; while (n > 4): n -= 3; res *= 3; # Keep multiplying 3 to res return (n * res); # The last part multiplied by previous parts ''' Driver program to test above functions '''if __name__=='__main__': print(\"Maximum Product is\", maxProd(45)) # This code is contributed by rutvik_56.", "e": 11512, "s": 10943, "text": null }, { "code": "using System;class GFG { /* The main function that returns the max possible product */ static int maxProd(int n) { // n equals to 2 or 3 must be handled explicitly if (n == 2 || n == 3) return (n - 1); // Keep removing parts of size 3 while n is greater than 4 int res = 1; while (n > 4) { n -= 3; res *= 3; // Keep multiplying 3 to res } return (n * res); // The last part multiplied by previous parts } // Driver code static void Main() { Console.WriteLine(\"Maximum Product is \" + maxProd(45)); }} // This code is contributed by divyesh072019.", "e": 12119, "s": 11512, "text": null }, { "code": "<script> /* The main function that returns the max possible product */ function maxProd(n) { // n equals to 2 or 3 must be handled explicitly if (n == 2 || n == 3) return (n - 1); // Keep removing parts of size 3 while n is greater than 4 let res = 1; while (n > 4) { n -= 3; res *= 3; // Keep multiplying 3 to res } return (n * res); // The last part multiplied by previous parts } document.write(\"Maximum Product is \" + maxProd(45)); </script>", "e": 12646, "s": 12119, "text": null }, { "code": null, "e": 12674, "s": 12646, "text": "Maximum Product is 14348907" }, { "code": null, "e": 12696, "s": 12674, "text": "Time Complexity: O(n)" }, { "code": null, "e": 12718, "s": 12696, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 13142, "s": 12718, "text": "This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 13155, "s": 13142, "text": "Mithun Kumar" }, { "code": null, "e": 13173, "s": 13155, "text": "ShubhamShekhaliya" }, { "code": null, "e": 13186, "s": 13173, "text": "bhavneet2000" }, { "code": null, "e": 13204, "s": 13186, "text": "divyeshrabadiya07" }, { "code": null, "e": 13218, "s": 13204, "text": "divyesh072019" }, { "code": null, "e": 13228, "s": 13218, "text": "rutvik_56" }, { "code": null, "e": 13237, "s": 13228, "text": "mukesh07" }, { "code": null, "e": 13252, "s": 13237, "text": "rameshtravel07" }, { "code": null, "e": 13265, "s": 13252, "text": "simmytarika5" }, { "code": null, "e": 13280, "s": 13265, "text": "shivamanandrj9" }, { "code": null, "e": 13293, "s": 13280, "text": "Mathematical" }, { "code": null, "e": 13306, "s": 13293, "text": "Mathematical" } ]
How to align div vertical across full screen in Tailwind CSS ?
20 Jun, 2021 You can easily align div vertical across the full screen using flex property in Tailwind CSS. Tailwind uses justify-center and items-center property which is an alternative to the flex-property in CSS. Syntax: <div class="flex h-screen justify-center items-center"> . . . </div> flex property: h-screen: It makes an element span the entire height of the viewport because by default all containers take up their entire width, but they don’t take up their entire height. justify-center: This property aligns the flex items in the center in the horizontal direction ( main-axis ) when the flex items are row-wise stacked. items-center: This property aligns the flex items in the center in a vertical direction (cross-axis) when the flex items are stacked row-wise. Note: When flex items are stacked column-wise then, the justify-content property aligns the flex items in the center in the vertical direction and the items-center property aligns the flex items in the center in the horizontal direction. Important Concept: Whenever you flip the direction of your flex, then you are also flipping both horizontal alignments ( justify-{alignment} ) and vertical alignment ( items-{alignment} ). So justify-{alignment} is in horizontal direction if flex is in the row direction. When the flex is in the column direction then justify-{alignment} is in the vertical direction. It’s inverse for items-{alignment} i.e it is vertical direction as long as the flex is in row-direction otherwise it is horizontal in the column-direction. Example 1: HTML <!DOCTYPE html> <head> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"></head> <body> <div class="flex h-screen justify-center items-center bg-green-300"> <div class="text-center h-40 w-40 bg-pink-400"> <h2 style="color:green"> GeeksforGeeks </h2> <b>Align div vertically</b> </div> </div></body> </html> Output: From this example you can observe that the pink color box is aligned vertically across the full screen. Example 2: Using m-auto to center the element. The m-auto is used to center the item both horizontally and vertically. The following example will align the div vertically and horizontally across the full screen. HTML <!DOCTYPE html> <head> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"></head> <body> <div class="flex h-screen bg-pink-200"> <div class="m-auto bg-green-300 "> <h2 style="color:green "> GeeksforGeeks </h2> <b> LEFT BOX</b> </div> <div class="m-auto bg-green-300 "> <h2 style="color:green "> GeeksforGeeks </h2> <b> RIGHT BOX</b> </div> </div></body> </html> Output: Picked Tailwind CSS-Questions CSS Web Technologies 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 Design a web page using HTML and CSS Form validation using jQuery Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array
[ { "code": null, "e": 28, "s": 0, "text": "\n20 Jun, 2021" }, { "code": null, "e": 230, "s": 28, "text": "You can easily align div vertical across the full screen using flex property in Tailwind CSS. Tailwind uses justify-center and items-center property which is an alternative to the flex-property in CSS." }, { "code": null, "e": 238, "s": 230, "text": "Syntax:" }, { "code": null, "e": 314, "s": 238, "text": "<div class=\"flex h-screen justify-center items-center\">\n . . . \n</div>" }, { "code": null, "e": 329, "s": 314, "text": "flex property:" }, { "code": null, "e": 504, "s": 329, "text": "h-screen: It makes an element span the entire height of the viewport because by default all containers take up their entire width, but they don’t take up their entire height." }, { "code": null, "e": 654, "s": 504, "text": "justify-center: This property aligns the flex items in the center in the horizontal direction ( main-axis ) when the flex items are row-wise stacked." }, { "code": null, "e": 798, "s": 654, "text": "items-center: This property aligns the flex items in the center in a vertical direction (cross-axis) when the flex items are stacked row-wise." }, { "code": null, "e": 1036, "s": 798, "text": "Note: When flex items are stacked column-wise then, the justify-content property aligns the flex items in the center in the vertical direction and the items-center property aligns the flex items in the center in the horizontal direction." }, { "code": null, "e": 1404, "s": 1036, "text": "Important Concept: Whenever you flip the direction of your flex, then you are also flipping both horizontal alignments ( justify-{alignment} ) and vertical alignment ( items-{alignment} ). So justify-{alignment} is in horizontal direction if flex is in the row direction. When the flex is in the column direction then justify-{alignment} is in the vertical direction." }, { "code": null, "e": 1560, "s": 1404, "text": "It’s inverse for items-{alignment} i.e it is vertical direction as long as the flex is in row-direction otherwise it is horizontal in the column-direction." }, { "code": null, "e": 1571, "s": 1560, "text": "Example 1:" }, { "code": null, "e": 1576, "s": 1571, "text": "HTML" }, { "code": "<!DOCTYPE html> <head> <link href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"></head> <body> <div class=\"flex h-screen justify-center items-center bg-green-300\"> <div class=\"text-center h-40 w-40 bg-pink-400\"> <h2 style=\"color:green\"> GeeksforGeeks </h2> <b>Align div vertically</b> </div> </div></body> </html>", "e": 2047, "s": 1576, "text": null }, { "code": null, "e": 2159, "s": 2047, "text": "Output: From this example you can observe that the pink color box is aligned vertically across the full screen." }, { "code": null, "e": 2371, "s": 2159, "text": "Example 2: Using m-auto to center the element. The m-auto is used to center the item both horizontally and vertically. The following example will align the div vertically and horizontally across the full screen." }, { "code": null, "e": 2376, "s": 2371, "text": "HTML" }, { "code": "<!DOCTYPE html> <head> <link href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"></head> <body> <div class=\"flex h-screen bg-pink-200\"> <div class=\"m-auto bg-green-300 \"> <h2 style=\"color:green \"> GeeksforGeeks </h2> <b> LEFT BOX</b> </div> <div class=\"m-auto bg-green-300 \"> <h2 style=\"color:green \"> GeeksforGeeks </h2> <b> RIGHT BOX</b> </div> </div></body> </html>", "e": 2927, "s": 2376, "text": null }, { "code": null, "e": 2935, "s": 2927, "text": "Output:" }, { "code": null, "e": 2942, "s": 2935, "text": "Picked" }, { "code": null, "e": 2965, "s": 2942, "text": "Tailwind CSS-Questions" }, { "code": null, "e": 2969, "s": 2965, "text": "CSS" }, { "code": null, "e": 2986, "s": 2969, "text": "Web Technologies" }, { "code": null, "e": 3084, "s": 2986, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3123, "s": 3084, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 3162, "s": 3123, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 3201, "s": 3162, "text": "Build a Survey Form using HTML and CSS" }, { "code": null, "e": 3238, "s": 3201, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 3267, "s": 3238, "text": "Form validation using jQuery" }, { "code": null, "e": 3300, "s": 3267, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 3361, "s": 3300, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3404, "s": 3361, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 3476, "s": 3404, "text": "Differences between Functional Components and Class Components in React" } ]
Ruby | Types of Iterators
29 May, 2021 The word iterate means doing one thing multiple times and that is what iterators do. Sometimes iterators are termed as the custom loops. “Iterators” is the object-oriented concept in Ruby. In more simple words, iterators are the methods which are supported by collections(Arrays, Hashes etc.). Collections are the objects which store a group of data members. Ruby iterators return all the elements of a collection one after another. Ruby iterators are “chainable” i.e adding functionality on top of each other. There are many iterators in Ruby as follows: Each IteratorCollect IteratorTimes IteratorUpto IteratorDownto IteratorStep IteratorEach_Line IteratorEach Iterator: This iterator returns all the elements of an array or a hash. Each iterator returns each value one by one. Syntax: Each Iterator Collect Iterator Times Iterator Upto Iterator Downto Iterator Step Iterator Each_Line IteratorEach Iterator: This iterator returns all the elements of an array or a hash. Each iterator returns each value one by one. Syntax: Each Iterator: This iterator returns all the elements of an array or a hash. Each iterator returns each value one by one. Syntax: Each Iterator: This iterator returns all the elements of an array or a hash. Each iterator returns each value one by one. Syntax: collection.each do |variable_name| # code to be iterate end In the above syntax, the collection can be the range, array or hash. Example: In the above syntax, the collection can be the range, array or hash. Example: Ruby # Ruby program to illustrate each iterator #!/usr/bin/ruby # using each iterator# here collection is range# variable name is i(0..9).each do |i| # statement to be executed puts i end a = ['G', 'e', 'e', 'k', 's'] puts "\n" # using each iterator# here collection is an arraya.each do|arr| # statement to be executed puts arr end Output: Output: 0 1 2 3 4 5 6 7 8 9 G e e k s Collect Iterator: This iterator returns all the elements of a collection. The collect iterator returns an entire collection, regardless of whether it is an array or hash.Syntax: Collect Iterator: This iterator returns all the elements of a collection. The collect iterator returns an entire collection, regardless of whether it is an array or hash.Syntax: Collection = collection.collect The collect method need not always be associated with a block. The collect method returns the entire collection, regardless of whether it is an array or a hash.Example: The collect method need not always be associated with a block. The collect method returns the entire collection, regardless of whether it is an array or a hash.Example: Ruby # Ruby program to illustrate the collect iterator #!/usr/bin/ruby a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # using collect iterator# printing table of 5b = a.collect{ |y| (5 * y) }puts b Output: Output: 5 10 15 20 25 30 35 40 45 50 Times Iterator: In this iterator, a loop is implanted with the specific number of time. The loop is initially started from zero and runs until the one less than the specified number.This can be used with no iteration variable.. We can add an iteration variable by using the vertical bars around the identifier. Syntax: Times Iterator: In this iterator, a loop is implanted with the specific number of time. The loop is initially started from zero and runs until the one less than the specified number.This can be used with no iteration variable.. We can add an iteration variable by using the vertical bars around the identifier. Syntax: t.times do |variable_name| # code to be execute end Here t is the specified number which is used to define the number of iteration.Example: Here t is the specified number which is used to define the number of iteration.Example: Ruby # Ruby program to illustrate time iterator #!/usr/bin/ruby # using times iterator by providing# 7 as the iterate value7.times do |i| puts iend Output: Output: 0 1 2 3 4 5 6 Upto Iterator: This iterator follows top to bottom approach. It includes both the top and bottom variable in the iteration. Syntax: Upto Iterator: This iterator follows top to bottom approach. It includes both the top and bottom variable in the iteration. Syntax: top.upto(bottom) do |variable_name| # code to execute end Here iteration starts from top and ends on bottom. The important point to remember that the value of bottom variable is always greater than the top variable and if it is not, then it will return nothing.Example: Here iteration starts from top and ends on bottom. The important point to remember that the value of bottom variable is always greater than the top variable and if it is not, then it will return nothing.Example: Ruby # Ruby program to illustrate the upto iterator #!/usr/bin/ruby # using upto iterator# here top value is 4# bottom value is 74.upto(7) do |n| puts n end # here top > bottom# so no output7.upto(4) do |n| puts n end Output: Output: 4 5 6 7 Downto Iterator: This iterator follows bottom to top approach. It includes both the top and bottom variable in the iteration. Syntax: Downto Iterator: This iterator follows bottom to top approach. It includes both the top and bottom variable in the iteration. Syntax: top.downto(bottom) do |variable_name| # code to execute end Here iteration starts from bottom and ends on top. The important point to remember that the value of bottom variable is always smaller than the top variable and if it is not, then it will return nothing.Example: Here iteration starts from bottom and ends on top. The important point to remember that the value of bottom variable is always smaller than the top variable and if it is not, then it will return nothing.Example: Ruby # Ruby program to illustrate the downto iterator #!/usr/bin/ruby # using downto iterator# here top value is 7# bottom value is 47.downto(4) do |n| puts n end # here top < bottom# so no output4.downto(7) do |n| puts n end Output: Output: 7 6 5 4 Step Iterator: Ruby step iterator is used to iterate where the user has to skip a specified range. Syntax: Step Iterator: Ruby step iterator is used to iterate where the user has to skip a specified range. Syntax: Collection.step(rng) do |variable_name| # code to be executed end Here rng is the range which will be skipped throughout the iterate operation. Example: Here rng is the range which will be skipped throughout the iterate operation. Example: Ruby # Ruby program to illustrate step iterator #!/usr/bin/ruby # using step iterator# skipping value is 10# (0..60 ) is the range(0..60).step(10) do|i| puts iend Output: Output: Output: 0 10 20 30 40 50 60 Each_line Iterator: Ruby each_line iterator is used to iterate over a new line in the string. Syntax: Each_line Iterator: Ruby each_line iterator is used to iterate over a new line in the string. Syntax: string.each_line do |variable_name| # code to be executed end Example: Example: Ruby # Ruby program to illustrate Each_line iterator #!/usr/bin/ruby # using each_line iterator"Welcome\nto\nGeeksForGeeks\nPortal".each_line do|i|puts iend Output: Output: Welcome to GeeksForGeeks Portal Code_Mech Ruby Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Make a Custom Array of Hashes in Ruby? Ruby | Enumerator each_with_index function Ruby | unless Statement and unless Modifier Ruby | Array class find_index() operation Ruby For Beginners Ruby | String concat Method Ruby | Array shift() function Ruby on Rails Introduction Ruby | Types of Variables
[ { "code": null, "e": 54, "s": 26, "text": "\n29 May, 2021" }, { "code": null, "e": 192, "s": 54, "text": "The word iterate means doing one thing multiple times and that is what iterators do. Sometimes iterators are termed as the custom loops. " }, { "code": null, "e": 244, "s": 192, "text": "“Iterators” is the object-oriented concept in Ruby." }, { "code": null, "e": 414, "s": 244, "text": "In more simple words, iterators are the methods which are supported by collections(Arrays, Hashes etc.). Collections are the objects which store a group of data members." }, { "code": null, "e": 488, "s": 414, "text": "Ruby iterators return all the elements of a collection one after another." }, { "code": null, "e": 566, "s": 488, "text": "Ruby iterators are “chainable” i.e adding functionality on top of each other." }, { "code": null, "e": 613, "s": 566, "text": "There are many iterators in Ruby as follows: " }, { "code": null, "e": 847, "s": 613, "text": "Each IteratorCollect IteratorTimes IteratorUpto IteratorDownto IteratorStep IteratorEach_Line IteratorEach Iterator: This iterator returns all the elements of an array or a hash. Each iterator returns each value one by one. Syntax: " }, { "code": null, "e": 861, "s": 847, "text": "Each Iterator" }, { "code": null, "e": 878, "s": 861, "text": "Collect Iterator" }, { "code": null, "e": 893, "s": 878, "text": "Times Iterator" }, { "code": null, "e": 907, "s": 893, "text": "Upto Iterator" }, { "code": null, "e": 923, "s": 907, "text": "Downto Iterator" }, { "code": null, "e": 937, "s": 923, "text": "Step Iterator" }, { "code": null, "e": 1087, "s": 937, "text": "Each_Line IteratorEach Iterator: This iterator returns all the elements of an array or a hash. Each iterator returns each value one by one. Syntax: " }, { "code": null, "e": 1219, "s": 1087, "text": "Each Iterator: This iterator returns all the elements of an array or a hash. Each iterator returns each value one by one. Syntax: " }, { "code": null, "e": 1351, "s": 1219, "text": "Each Iterator: This iterator returns all the elements of an array or a hash. Each iterator returns each value one by one. Syntax: " }, { "code": null, "e": 1414, "s": 1351, "text": "collection.each do |variable_name|\n # code to be iterate\nend" }, { "code": null, "e": 1494, "s": 1414, "text": "In the above syntax, the collection can be the range, array or hash. Example: " }, { "code": null, "e": 1574, "s": 1494, "text": "In the above syntax, the collection can be the range, array or hash. Example: " }, { "code": null, "e": 1579, "s": 1574, "text": "Ruby" }, { "code": "# Ruby program to illustrate each iterator #!/usr/bin/ruby # using each iterator# here collection is range# variable name is i(0..9).each do |i| # statement to be executed puts i end a = ['G', 'e', 'e', 'k', 's'] puts \"\\n\" # using each iterator# here collection is an arraya.each do|arr| # statement to be executed puts arr end", "e": 1937, "s": 1579, "text": null }, { "code": null, "e": 1947, "s": 1937, "text": "Output: " }, { "code": null, "e": 1957, "s": 1947, "text": "Output: " }, { "code": null, "e": 1988, "s": 1957, "text": "0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n\nG\ne\ne\nk\ns" }, { "code": null, "e": 2169, "s": 1988, "text": " Collect Iterator: This iterator returns all the elements of a collection. The collect iterator returns an entire collection, regardless of whether it is an array or hash.Syntax: " }, { "code": null, "e": 2351, "s": 2171, "text": "Collect Iterator: This iterator returns all the elements of a collection. The collect iterator returns an entire collection, regardless of whether it is an array or hash.Syntax: " }, { "code": null, "e": 2383, "s": 2351, "text": "Collection = collection.collect" }, { "code": null, "e": 2554, "s": 2383, "text": "The collect method need not always be associated with a block. The collect method returns the entire collection, regardless of whether it is an array or a hash.Example: " }, { "code": null, "e": 2725, "s": 2554, "text": "The collect method need not always be associated with a block. The collect method returns the entire collection, regardless of whether it is an array or a hash.Example: " }, { "code": null, "e": 2730, "s": 2725, "text": "Ruby" }, { "code": "# Ruby program to illustrate the collect iterator #!/usr/bin/ruby a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # using collect iterator# printing table of 5b = a.collect{ |y| (5 * y) }puts b", "e": 2912, "s": 2730, "text": null }, { "code": null, "e": 2922, "s": 2912, "text": "Output: " }, { "code": null, "e": 2932, "s": 2922, "text": "Output: " }, { "code": null, "e": 2961, "s": 2932, "text": "5\n10\n15\n20\n25\n30\n35\n40\n45\n50" }, { "code": null, "e": 3281, "s": 2961, "text": "Times Iterator: In this iterator, a loop is implanted with the specific number of time. The loop is initially started from zero and runs until the one less than the specified number.This can be used with no iteration variable.. We can add an iteration variable by using the vertical bars around the identifier. Syntax: " }, { "code": null, "e": 3601, "s": 3281, "text": "Times Iterator: In this iterator, a loop is implanted with the specific number of time. The loop is initially started from zero and runs until the one less than the specified number.This can be used with no iteration variable.. We can add an iteration variable by using the vertical bars around the identifier. Syntax: " }, { "code": null, "e": 3655, "s": 3601, "text": "t.times do |variable_name|\n\n# code to be execute\n\nend" }, { "code": null, "e": 3744, "s": 3655, "text": "Here t is the specified number which is used to define the number of iteration.Example: " }, { "code": null, "e": 3833, "s": 3744, "text": "Here t is the specified number which is used to define the number of iteration.Example: " }, { "code": null, "e": 3838, "s": 3833, "text": "Ruby" }, { "code": "# Ruby program to illustrate time iterator #!/usr/bin/ruby # using times iterator by providing# 7 as the iterate value7.times do |i| puts iend", "e": 3984, "s": 3838, "text": null }, { "code": null, "e": 3994, "s": 3984, "text": "Output: " }, { "code": null, "e": 4004, "s": 3994, "text": "Output: " }, { "code": null, "e": 4018, "s": 4004, "text": "0\n1\n2\n3\n4\n5\n6" }, { "code": null, "e": 4152, "s": 4018, "text": "Upto Iterator: This iterator follows top to bottom approach. It includes both the top and bottom variable in the iteration. Syntax: " }, { "code": null, "e": 4286, "s": 4152, "text": "Upto Iterator: This iterator follows top to bottom approach. It includes both the top and bottom variable in the iteration. Syntax: " }, { "code": null, "e": 4346, "s": 4286, "text": "top.upto(bottom) do |variable_name|\n\n# code to execute\n\nend" }, { "code": null, "e": 4560, "s": 4346, "text": "Here iteration starts from top and ends on bottom. The important point to remember that the value of bottom variable is always greater than the top variable and if it is not, then it will return nothing.Example: " }, { "code": null, "e": 4774, "s": 4560, "text": "Here iteration starts from top and ends on bottom. The important point to remember that the value of bottom variable is always greater than the top variable and if it is not, then it will return nothing.Example: " }, { "code": null, "e": 4779, "s": 4774, "text": "Ruby" }, { "code": "# Ruby program to illustrate the upto iterator #!/usr/bin/ruby # using upto iterator# here top value is 4# bottom value is 74.upto(7) do |n| puts n end # here top > bottom# so no output7.upto(4) do |n| puts n end ", "e": 5002, "s": 4779, "text": null }, { "code": null, "e": 5012, "s": 5002, "text": "Output: " }, { "code": null, "e": 5022, "s": 5012, "text": "Output: " }, { "code": null, "e": 5030, "s": 5022, "text": "4\n5\n6\n7" }, { "code": null, "e": 5167, "s": 5030, "text": " Downto Iterator: This iterator follows bottom to top approach. It includes both the top and bottom variable in the iteration. Syntax: " }, { "code": null, "e": 5305, "s": 5169, "text": "Downto Iterator: This iterator follows bottom to top approach. It includes both the top and bottom variable in the iteration. Syntax: " }, { "code": null, "e": 5367, "s": 5305, "text": "top.downto(bottom) do |variable_name|\n\n# code to execute\n\nend" }, { "code": null, "e": 5581, "s": 5367, "text": "Here iteration starts from bottom and ends on top. The important point to remember that the value of bottom variable is always smaller than the top variable and if it is not, then it will return nothing.Example: " }, { "code": null, "e": 5795, "s": 5581, "text": "Here iteration starts from bottom and ends on top. The important point to remember that the value of bottom variable is always smaller than the top variable and if it is not, then it will return nothing.Example: " }, { "code": null, "e": 5800, "s": 5795, "text": "Ruby" }, { "code": "# Ruby program to illustrate the downto iterator #!/usr/bin/ruby # using downto iterator# here top value is 7# bottom value is 47.downto(4) do |n| puts n end # here top < bottom# so no output4.downto(7) do |n| puts n end ", "e": 6031, "s": 5800, "text": null }, { "code": null, "e": 6041, "s": 6031, "text": "Output: " }, { "code": null, "e": 6051, "s": 6041, "text": "Output: " }, { "code": null, "e": 6059, "s": 6051, "text": "7\n6\n5\n4" }, { "code": null, "e": 6169, "s": 6059, "text": " Step Iterator: Ruby step iterator is used to iterate where the user has to skip a specified range. Syntax: " }, { "code": null, "e": 6280, "s": 6171, "text": "Step Iterator: Ruby step iterator is used to iterate where the user has to skip a specified range. Syntax: " }, { "code": null, "e": 6349, "s": 6280, "text": "Collection.step(rng) do |variable_name|\n\n# code to be executed\n\nend " }, { "code": null, "e": 6437, "s": 6349, "text": "Here rng is the range which will be skipped throughout the iterate operation. Example: " }, { "code": null, "e": 6525, "s": 6437, "text": "Here rng is the range which will be skipped throughout the iterate operation. Example: " }, { "code": null, "e": 6530, "s": 6525, "text": "Ruby" }, { "code": "# Ruby program to illustrate step iterator #!/usr/bin/ruby # using step iterator# skipping value is 10# (0..60 ) is the range(0..60).step(10) do|i| puts iend", "e": 6691, "s": 6530, "text": null }, { "code": null, "e": 6701, "s": 6691, "text": "Output: " }, { "code": null, "e": 6711, "s": 6701, "text": "Output: " }, { "code": null, "e": 6721, "s": 6711, "text": "Output: " }, { "code": null, "e": 6741, "s": 6721, "text": "0\n10\n20\n30\n40\n50\n60" }, { "code": null, "e": 6845, "s": 6741, "text": " Each_line Iterator: Ruby each_line iterator is used to iterate over a new line in the string. Syntax: " }, { "code": null, "e": 6950, "s": 6847, "text": "Each_line Iterator: Ruby each_line iterator is used to iterate over a new line in the string. Syntax: " }, { "code": null, "e": 7014, "s": 6950, "text": "string.each_line do |variable_name|\n\n# code to be executed\n\nend" }, { "code": null, "e": 7024, "s": 7014, "text": "Example: " }, { "code": null, "e": 7034, "s": 7024, "text": "Example: " }, { "code": null, "e": 7039, "s": 7034, "text": "Ruby" }, { "code": "# Ruby program to illustrate Each_line iterator #!/usr/bin/ruby # using each_line iterator\"Welcome\\nto\\nGeeksForGeeks\\nPortal\".each_line do|i|puts iend", "e": 7192, "s": 7039, "text": null }, { "code": null, "e": 7202, "s": 7192, "text": "Output: " }, { "code": null, "e": 7212, "s": 7202, "text": "Output: " }, { "code": null, "e": 7244, "s": 7212, "text": "Welcome\nto\nGeeksForGeeks\nPortal" }, { "code": null, "e": 7258, "s": 7248, "text": "Code_Mech" }, { "code": null, "e": 7263, "s": 7258, "text": "Ruby" }, { "code": null, "e": 7361, "s": 7263, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7407, "s": 7361, "text": "How to Make a Custom Array of Hashes in Ruby?" }, { "code": null, "e": 7450, "s": 7407, "text": "Ruby | Enumerator each_with_index function" }, { "code": null, "e": 7494, "s": 7450, "text": "Ruby | unless Statement and unless Modifier" }, { "code": null, "e": 7536, "s": 7494, "text": "Ruby | Array class find_index() operation" }, { "code": null, "e": 7555, "s": 7536, "text": "Ruby For Beginners" }, { "code": null, "e": 7583, "s": 7555, "text": "Ruby | String concat Method" }, { "code": null, "e": 7613, "s": 7583, "text": "Ruby | Array shift() function" }, { "code": null, "e": 7640, "s": 7613, "text": "Ruby on Rails Introduction" } ]
Socket.IO - Broadcasting
Broadcasting means sending a message to all connected clients. Broadcasting can be done at multiple levels. We can send the message to all the connected clients, to clients on a namespace and clients in a particular room. To broadcast an event to all the clients, we can use the io.sockets.emit method. Note − This will emit the event to ALL the connected clients (event the socket that might have fired this event). In this example, we will broadcast the number of connected clients to all the users. Update the app.js file to incorporate the following − var app = require('express')(); var http = require('http').Server(app); var io = require('socket.io')(http); app.get('/', function(req, res){ res.sendFile('E:/test/index.html'); }); var clients = 0; io.on('connection', function(socket){ clients++; io.sockets.emit('broadcast',{ description: clients + ' clients connected!'}); socket.on('disconnect', function () { clients--; io.sockets.emit('broadcast',{ description: clients + ' clients connected!'}); }); }); http.listen(3000, function(){ console.log('listening on localhost:3000'); }); On the client side, we just need to handle the broadcast event − <!DOCTYPE html> <html> <head><title>Hello world</title></head> <script src="/socket.io/socket.io.js"></script> <script> var socket = io(); socket.on('broadcast',function(data){ document.body.innerHTML = ''; document.write(data.description); }); </script> <body>Hello world</body> </html> If you connect four clients, you will get the following result − This was to send an event to everyone. Now, if we want to send an event to everyone, but the client that caused it (in the previous example, it was caused by new clients on connecting), we can use the socket.broadcast.emit. Let us send the new user a welcome message and update the other clients about him/her joining. So, in your app.js file, on connection of client send him a welcome message and broadcast connected client number to all others. var app = require('express')(); var http = require('http').Server(app); var io = require('socket.io')(http); app.get('/', function(req, res){ res.sendFile('E:/test/index.html'); }); var clients = 0; io.on('connection', function(socket){ clients++; socket.emit('newclientconnect',{ description: 'Hey, welcome!'}); socket.broadcast.emit('newclientconnect',{ description: clients + ' clients connected!'}) socket.on('disconnect', function () { clients--; socket.broadcast.emit('newclientconnect',{ description: clients + ' clients connected!'}) }); }); http.listen(3000, function(){ console.log('listening on localhost:3000'); }); And your html to handle this event − <!DOCTYPE html> <html> <head><title>Hello world</title></head> <script src="/socket.io/socket.io.js"></script> <script> var socket = io(); socket.on('newclientconnect',function(data){ document.body.innerHTML = ''; document.write(data.description); }); </script> <body>Hello world</body> </html> Now, the newest client gets a welcome message and others get how many clients are connected currently to the server.
[ { "code": null, "e": 2302, "s": 1999, "text": "Broadcasting means sending a message to all connected clients. Broadcasting can be done at multiple levels. We can send the message to all the connected clients, to clients on a namespace and clients in a particular room. To broadcast an event to all the clients, we can use the io.sockets.emit method." }, { "code": null, "e": 2416, "s": 2302, "text": "Note − This will emit the event to ALL the connected clients (event the socket that might have fired this event)." }, { "code": null, "e": 2555, "s": 2416, "text": "In this example, we will broadcast the number of connected clients to all the users. Update the app.js file to incorporate the following −" }, { "code": null, "e": 3131, "s": 2555, "text": "var app = require('express')();\nvar http = require('http').Server(app);\nvar io = require('socket.io')(http);\n\napp.get('/', function(req, res){\n res.sendFile('E:/test/index.html');\n});\n \nvar clients = 0;\n\nio.on('connection', function(socket){\n clients++;\n io.sockets.emit('broadcast',{ description: clients + ' clients connected!'});\n socket.on('disconnect', function () {\n clients--;\n io.sockets.emit('broadcast',{ description: clients + ' clients connected!'});\n });\n});\n\nhttp.listen(3000, function(){\n console.log('listening on localhost:3000');\n});" }, { "code": null, "e": 3196, "s": 3131, "text": "On the client side, we just need to handle the broadcast event −" }, { "code": null, "e": 3535, "s": 3196, "text": "<!DOCTYPE html>\n<html>\n <head><title>Hello world</title></head>\n <script src=\"/socket.io/socket.io.js\"></script>\n <script>\n var socket = io();\n socket.on('broadcast',function(data){\n document.body.innerHTML = '';\n document.write(data.description);\n });\n </script>\n <body>Hello world</body>\n</html>" }, { "code": null, "e": 3600, "s": 3535, "text": "If you connect four clients, you will get the following result −" }, { "code": null, "e": 3824, "s": 3600, "text": "This was to send an event to everyone. Now, if we want to send an event to everyone, but the client that caused it (in the previous example, it was caused by new clients on connecting), we can use the socket.broadcast.emit." }, { "code": null, "e": 4048, "s": 3824, "text": "Let us send the new user a welcome message and update the other clients about him/her joining. So, in your app.js file, on connection of client send him a welcome message and broadcast connected client number to all others." }, { "code": null, "e": 4711, "s": 4048, "text": "var app = require('express')();\nvar http = require('http').Server(app);\nvar io = require('socket.io')(http);\n\napp.get('/', function(req, res){\n res.sendFile('E:/test/index.html');\n});\nvar clients = 0;\n\nio.on('connection', function(socket){\n clients++;\n socket.emit('newclientconnect',{ description: 'Hey, welcome!'});\n socket.broadcast.emit('newclientconnect',{ description: clients + ' clients connected!'})\n socket.on('disconnect', function () {\n clients--;\n socket.broadcast.emit('newclientconnect',{ description: clients + ' clients connected!'})\n });\n});\nhttp.listen(3000, function(){\n console.log('listening on localhost:3000');\n});" }, { "code": null, "e": 4748, "s": 4711, "text": "And your html to handle this event −" }, { "code": null, "e": 5106, "s": 4748, "text": "<!DOCTYPE html>\n<html>\n <head><title>Hello world</title></head>\n <script src=\"/socket.io/socket.io.js\"></script>\n <script>\n var socket = io();\n socket.on('newclientconnect',function(data){\n document.body.innerHTML = '';\n document.write(data.description);\n });\n </script>\n <body>Hello world</body>\n</html>" } ]
Shell Sort Program in C
Shell sort is a highly efficient sorting algorithm and is based on insertion sort algorithm. This algorithm avoids large shifts as in case of insertion sort, if the smaller value is to the far right and has to be moved to the far left. #include <stdio.h> #include <stdbool.h> #define MAX 7 int intArray[MAX] = {4,6,3,2,1,9,7}; void printline(int count) { int i; for(i = 0;i < count-1;i++) { printf("="); } printf("=\n"); } void display() { int i; printf("["); // navigate through all items for(i = 0;i < MAX;i++) { printf("%d ",intArray[i]); } printf("]\n"); } void shellSort() { int inner, outer; int valueToInsert; int interval = 1; int elements = MAX; int i = 0; while(interval <= elements/3) { interval = interval*3 +1; } while(interval > 0) { printf("iteration %d#:",i); display(); for(outer = interval; outer < elements; outer++) { valueToInsert = intArray[outer]; inner = outer; while(inner > interval -1 && intArray[inner - interval] >= valueToInsert) { intArray[inner] = intArray[inner - interval]; inner -=interval; printf(" item moved :%d\n",intArray[inner]); } intArray[inner] = valueToInsert; printf(" item inserted :%d, at position :%d\n",valueToInsert,inner); } interval = (interval -1) /3; i++; } } int main() { printf("Input Array: "); display(); printline(50); shellSort(); printf("Output Array: "); display(); printline(50); return 1; } If we compile and run the above program, it will produce the following result − Input Array: [4 6 3 2 1 9 7 ] ================================================== iteration 0#:[4 6 3 2 1 9 7 ] item moved :4 item inserted :1, at position :0 item inserted :9, at position :5 item inserted :7, at position :6 iteration 1#:[1 6 3 2 4 9 7 ] item inserted :6, at position :1 item moved :6 item inserted :3, at position :1 item moved :6 item moved :3 item inserted :2, at position :1 item moved :6 item inserted :4, at position :3 item inserted :9, at position :5 item moved :9 item inserted :7, at position :5 Output Array: [1 2 3 4 6 7 9 ]
[ { "code": null, "e": 2950, "s": 2714, "text": "Shell sort is a highly efficient sorting algorithm and is based on insertion sort algorithm. This algorithm avoids large shifts as in case of insertion sort, if the smaller value is to the far right and has to be moved to the far left." }, { "code": null, "e": 4366, "s": 2950, "text": "#include <stdio.h>\n#include <stdbool.h>\n\n#define MAX 7\n\nint intArray[MAX] = {4,6,3,2,1,9,7};\n\nvoid printline(int count) {\n int i;\n\t\n for(i = 0;i < count-1;i++) {\n printf(\"=\");\n }\n\t\n printf(\"=\\n\");\n}\n\nvoid display() {\n int i;\n printf(\"[\");\n\t\n // navigate through all items \n for(i = 0;i < MAX;i++) {\n printf(\"%d \",intArray[i]);\n }\n\t\n printf(\"]\\n\");\n}\n\nvoid shellSort() {\n int inner, outer;\n int valueToInsert;\n int interval = 1; \n int elements = MAX;\n int i = 0;\n \n while(interval <= elements/3) {\n interval = interval*3 +1;\n }\n\n while(interval > 0) {\n printf(\"iteration %d#:\",i); \n display();\n \n for(outer = interval; outer < elements; outer++) {\n valueToInsert = intArray[outer];\n inner = outer;\n\t\t\t\n while(inner > interval -1 && intArray[inner - interval] \n >= valueToInsert) {\n intArray[inner] = intArray[inner - interval];\n inner -=interval;\n printf(\" item moved :%d\\n\",intArray[inner]);\n }\n \n intArray[inner] = valueToInsert;\n printf(\" item inserted :%d, at position :%d\\n\",valueToInsert,inner);\n }\n\t\t\n interval = (interval -1) /3;\n i++;\n } \n}\n\nint main() {\n printf(\"Input Array: \");\n display();\n printline(50);\n shellSort();\n printf(\"Output Array: \");\n display();\n printline(50);\n return 1;\n}" }, { "code": null, "e": 4446, "s": 4366, "text": "If we compile and run the above program, it will produce the following result −" } ]
Snake Game in C
10 Feb, 2021 In this article, the task is to implement a basic Snake Game. Below given some functionalities of this game: The snake is represented with a 0(zero) symbol. The fruit is represented with an *(asterisk) symbol. The snake can move in any direction according to the user with the help of the keyboard (W, A, S, D keys). When the snake eats a fruit the score will increase by 10 points. The fruit will generate automatically within the boundaries. Whenever the snake will touch the boundary the game is over. Steps to create this game: There will be four user-defined functions. Build a boundary within which the game will be played. The fruits are generated randomly. Then increase the score whenever the snake eats a fruit. The user-defined functions created in this program are given below: Draw(): This function creates the boundary in which the game will be played. Setup(): This function will set the position of the fruit within the boundary. Input(): This function will take the input from the keyboard. Logic(): This function will set the movement of the snake. Built-in functions used: kbhit(): This function in C is used to determine if a key has been pressed or not. To use this function in a program include the header file conio.h. If a key has been pressed, then it returns a non-zero value otherwise it returns zero. rand(): The rand() function is declared in stdlib.h. It returns a random integer value every time it is called. Header files and variables: The header files and variables used in this program are: Here include the <unistd.h> header file for the sleep() function. Draw(): This function is responsible to build the boundary within which the game will be played. Below is the C program to build the outline boundary using draw(): C // C program to build the outline// boundary using draw()#include <stdio.h>#include <stdlib.h>int i, j, height = 30;int width = 30, gameover, score; // Function to draw a boundaryvoid draw(){ // system("cls"); for (i = 0; i < height; i++) { for (j = 0; j < width; j++) { if (i == 0 || i == width - 1 || j == 0 || j == height - 1) { printf("#"); } else { printf(" "); } } printf("\n"); }} // Driver Codeint main(){ // Function Call draw(); return 0;} ############################## # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ############################## setup():nThisbfunction is used to write the code to generate the fruit within the boundary using rand() function. Using rand()%20 because the size of the boundary is length = 20 and width = 20 so the fruit will generate within the boundary. Input(): In this function, the programmer writes the code to take the input from the keyboard (W, A, S, D, X keys). logic(): Here, write all the logic for this program like for the movement of the snake, for increasing the score, when the snake will touch the boundary the game will be over, to exit the game and the random generation of the fruit once the snake will eat the fruit. sleep(): This function in C is a function that delays the program execution for the given number of seconds. In this code sleep() is used to slow down the movement of the snake so it will be easy for the user to play. main(): From the main() function the execution of the program starts. It calls all the functions. Below is the C program to build the complete snake game: C // C program to build the complete// snake game#include <conio.h>#include <stdio.h>#include <stdlib.h>#include <unistd.h> int i, j, height = 20, width = 20;int gameover, score;int x, y, fruitx, fruity, flag; // Function to generate the fruit// within the boundaryvoid setup(){ gameover = 0; // Stores height and width x = height / 2; y = width / 2;label1: fruitx = rand() % 20; if (fruitx == 0) goto label1;label2: fruity = rand() % 20; if (fruity == 0) goto label2; score = 0;} // Function to draw the boundariesvoid draw(){ system("cls"); for (i = 0; i < height; i++) { for (j = 0; j < width; j++) { if (i == 0 || i == width - 1 || j == 0 || j == height - 1) { printf("#"); } else { if (i == x && j == y) printf("0"); else if (i == fruitx && j == fruity) printf("*"); else printf(" "); } } printf("\n"); } // Print the score after the // game ends printf("score = %d", score); printf("\n"); printf("press X to quit the game");} // Function to take the inputvoid input(){ if (kbhit()) { switch (getch()) { case 'a': flag = 1; break; case 's': flag = 2; break; case 'd': flag = 3; break; case 'w': flag = 4; break; case 'x': gameover = 1; break; } }} // Function for the logic behind// each movementvoid logic(){ sleep(0.01); switch (flag) { case 1: y--; break; case 2: x++; break; case 3: y++; break; case 4: x--; break; default: break; } // If the game is over if (x < 0 || x > height || y < 0 || y > width) gameover = 1; // If snake reaches the fruit // then update the score if (x == fruitx && y == fruity) { label3: fruitx = rand() % 20; if (fruitx == 0) goto label3; // After eating the above fruit // generate new fruit label4: fruity = rand() % 20; if (fruity == 0) goto label4; score += 10; }} // Driver Codevoid main(){ int m, n; // Generate boundary setup(); // Until the game is over while (!gameover) { // Function Call draw(); input(); logic(); }} Output: Demonstration: Technical Scripter 2020 C++ C++ Programs Project Technical Scripter CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n10 Feb, 2021" }, { "code": null, "e": 163, "s": 54, "text": "In this article, the task is to implement a basic Snake Game. Below given some functionalities of this game:" }, { "code": null, "e": 211, "s": 163, "text": "The snake is represented with a 0(zero) symbol." }, { "code": null, "e": 264, "s": 211, "text": "The fruit is represented with an *(asterisk) symbol." }, { "code": null, "e": 371, "s": 264, "text": "The snake can move in any direction according to the user with the help of the keyboard (W, A, S, D keys)." }, { "code": null, "e": 437, "s": 371, "text": "When the snake eats a fruit the score will increase by 10 points." }, { "code": null, "e": 498, "s": 437, "text": "The fruit will generate automatically within the boundaries." }, { "code": null, "e": 559, "s": 498, "text": "Whenever the snake will touch the boundary the game is over." }, { "code": null, "e": 586, "s": 559, "text": "Steps to create this game:" }, { "code": null, "e": 629, "s": 586, "text": "There will be four user-defined functions." }, { "code": null, "e": 684, "s": 629, "text": "Build a boundary within which the game will be played." }, { "code": null, "e": 719, "s": 684, "text": "The fruits are generated randomly." }, { "code": null, "e": 776, "s": 719, "text": "Then increase the score whenever the snake eats a fruit." }, { "code": null, "e": 844, "s": 776, "text": "The user-defined functions created in this program are given below:" }, { "code": null, "e": 921, "s": 844, "text": "Draw(): This function creates the boundary in which the game will be played." }, { "code": null, "e": 1000, "s": 921, "text": "Setup(): This function will set the position of the fruit within the boundary." }, { "code": null, "e": 1062, "s": 1000, "text": "Input(): This function will take the input from the keyboard." }, { "code": null, "e": 1121, "s": 1062, "text": "Logic(): This function will set the movement of the snake." }, { "code": null, "e": 1146, "s": 1121, "text": "Built-in functions used:" }, { "code": null, "e": 1383, "s": 1146, "text": "kbhit(): This function in C is used to determine if a key has been pressed or not. To use this function in a program include the header file conio.h. If a key has been pressed, then it returns a non-zero value otherwise it returns zero." }, { "code": null, "e": 1495, "s": 1383, "text": "rand(): The rand() function is declared in stdlib.h. It returns a random integer value every time it is called." }, { "code": null, "e": 1523, "s": 1495, "text": "Header files and variables:" }, { "code": null, "e": 1580, "s": 1523, "text": "The header files and variables used in this program are:" }, { "code": null, "e": 1646, "s": 1580, "text": "Here include the <unistd.h> header file for the sleep() function." }, { "code": null, "e": 1743, "s": 1646, "text": "Draw(): This function is responsible to build the boundary within which the game will be played." }, { "code": null, "e": 1810, "s": 1743, "text": "Below is the C program to build the outline boundary using draw():" }, { "code": null, "e": 1812, "s": 1810, "text": "C" }, { "code": "// C program to build the outline// boundary using draw()#include <stdio.h>#include <stdlib.h>int i, j, height = 30;int width = 30, gameover, score; // Function to draw a boundaryvoid draw(){ // system(\"cls\"); for (i = 0; i < height; i++) { for (j = 0; j < width; j++) { if (i == 0 || i == width - 1 || j == 0 || j == height - 1) { printf(\"#\"); } else { printf(\" \"); } } printf(\"\\n\"); }} // Driver Codeint main(){ // Function Call draw(); return 0;}", "e": 2394, "s": 1812, "text": null }, { "code": null, "e": 3325, "s": 2394, "text": "##############################\n# #\n# #\n# #\n# #\n# #\n# #\n# #\n# #\n# #\n# #\n# #\n# #\n# #\n# #\n# #\n# #\n# #\n# #\n# #\n# #\n# #\n# #\n# #\n# #\n# #\n# #\n# #\n# #\n##############################\n" }, { "code": null, "e": 3439, "s": 3325, "text": "setup():nThisbfunction is used to write the code to generate the fruit within the boundary using rand() function." }, { "code": null, "e": 3566, "s": 3439, "text": "Using rand()%20 because the size of the boundary is length = 20 and width = 20 so the fruit will generate within the boundary." }, { "code": null, "e": 3682, "s": 3566, "text": "Input(): In this function, the programmer writes the code to take the input from the keyboard (W, A, S, D, X keys)." }, { "code": null, "e": 3949, "s": 3682, "text": "logic(): Here, write all the logic for this program like for the movement of the snake, for increasing the score, when the snake will touch the boundary the game will be over, to exit the game and the random generation of the fruit once the snake will eat the fruit." }, { "code": null, "e": 4167, "s": 3949, "text": "sleep(): This function in C is a function that delays the program execution for the given number of seconds. In this code sleep() is used to slow down the movement of the snake so it will be easy for the user to play." }, { "code": null, "e": 4265, "s": 4167, "text": "main(): From the main() function the execution of the program starts. It calls all the functions." }, { "code": null, "e": 4322, "s": 4265, "text": "Below is the C program to build the complete snake game:" }, { "code": null, "e": 4324, "s": 4322, "text": "C" }, { "code": "// C program to build the complete// snake game#include <conio.h>#include <stdio.h>#include <stdlib.h>#include <unistd.h> int i, j, height = 20, width = 20;int gameover, score;int x, y, fruitx, fruity, flag; // Function to generate the fruit// within the boundaryvoid setup(){ gameover = 0; // Stores height and width x = height / 2; y = width / 2;label1: fruitx = rand() % 20; if (fruitx == 0) goto label1;label2: fruity = rand() % 20; if (fruity == 0) goto label2; score = 0;} // Function to draw the boundariesvoid draw(){ system(\"cls\"); for (i = 0; i < height; i++) { for (j = 0; j < width; j++) { if (i == 0 || i == width - 1 || j == 0 || j == height - 1) { printf(\"#\"); } else { if (i == x && j == y) printf(\"0\"); else if (i == fruitx && j == fruity) printf(\"*\"); else printf(\" \"); } } printf(\"\\n\"); } // Print the score after the // game ends printf(\"score = %d\", score); printf(\"\\n\"); printf(\"press X to quit the game\");} // Function to take the inputvoid input(){ if (kbhit()) { switch (getch()) { case 'a': flag = 1; break; case 's': flag = 2; break; case 'd': flag = 3; break; case 'w': flag = 4; break; case 'x': gameover = 1; break; } }} // Function for the logic behind// each movementvoid logic(){ sleep(0.01); switch (flag) { case 1: y--; break; case 2: x++; break; case 3: y++; break; case 4: x--; break; default: break; } // If the game is over if (x < 0 || x > height || y < 0 || y > width) gameover = 1; // If snake reaches the fruit // then update the score if (x == fruitx && y == fruity) { label3: fruitx = rand() % 20; if (fruitx == 0) goto label3; // After eating the above fruit // generate new fruit label4: fruity = rand() % 20; if (fruity == 0) goto label4; score += 10; }} // Driver Codevoid main(){ int m, n; // Generate boundary setup(); // Until the game is over while (!gameover) { // Function Call draw(); input(); logic(); }}", "e": 6908, "s": 4324, "text": null }, { "code": null, "e": 6916, "s": 6908, "text": "Output:" }, { "code": null, "e": 6931, "s": 6916, "text": "Demonstration:" }, { "code": null, "e": 6955, "s": 6931, "text": "Technical Scripter 2020" }, { "code": null, "e": 6959, "s": 6955, "text": "C++" }, { "code": null, "e": 6972, "s": 6959, "text": "C++ Programs" }, { "code": null, "e": 6980, "s": 6972, "text": "Project" }, { "code": null, "e": 6999, "s": 6980, "text": "Technical Scripter" }, { "code": null, "e": 7003, "s": 6999, "text": "CPP" } ]
Java Interview Questions on Constructors
28 Jun, 2021 What is a Constructor?Constructors are used to initialize the object’s state. Like methods, a constructor also contains collection of statements(i.e. instructions) that are executed at time of Object creation.Do we have Copy Constructor in Java?Like C++, Java also supports copy constructor. But, unlike C++, Java doesn’t create a default copy constructor if you don’t write your own.To copy the values of one object into another in java, you can use:ConstructorAssigning the values of one object into anotherclone() method of Object classWhat is Constructor Chaining ?Constructor Chaining is a technique of calling another constructor from one constructor. this() is used to call same class constructor where as super() is used to call super class constructor.// Java program to illustrate Constructor Chaining// within same class Using this() keywordclass Temp{ // default constructor 1 // default constructor will call another constructor // using this keyword from same class Temp() { // calls constructor 2 this(5); System.out.println("The Default constructor"); } // parameterized constructor 2 Temp(int x) { // calls constructor 3 this(5, 15); System.out.println(x); } // parameterized constructor 3 Temp(int x, int y) { System.out.println(x * y); } public static void main(String args[]) { // invokes default constructor first new Temp(); }}Can we call sub class constructor from super class constructor?No. There is no way in java to call sub class constructor from a super class constructor.What happens if you keep a return type for a constructor?Ideally, Constructor must not have a return type. By definition, if a method has a return type, it’s not a constructor.(JLS8.8 Declaration) It will be treated as a normal method. But compiler gives a warning saying that method has a constructor name.Example:class GfG { int GfG() { return 0; // Warning for the return type } }What is No-arg constructor?Constructor without arguments is called no-arg constructor. Default constructor in java is always a no-arg constructor. class GfG { public GfG() { //No-arg constructor } }How a no – argument constructor is different from default Constructor?If a class contains no constructor declarations, then a default constructor with no formal parameters and no throws clause is implicitly declared.If the class being declared is the primordial class Object, then the default constructor has an empty body. Otherwise, the default constructor simply invokes the superclass constructor with no arguments.What are private constructors and where are they used?Like any method we can provide access specifier to the constructor. If it’s made private, then it can only be accessed inside the class.The major scenarios where we use private constructor:Internal Constructor chainingSingleton class design patternWhen do we need Constructor Overloading?Sometimes there is a need of initializing an object in different ways. This can be done using constructor overloading. Different constructors can do different work by implementing different line of codes and are called based on the type and no of parameters passed.According to the situation , a constructor is called with specific number of parameters among overloaded constructors.Do we have destructors in Java?No, Because Java is a garbage collected language you cannot predict when (or even if) an object will be destroyed. Hence there is no direct equivalent of a destructor. What is a Constructor?Constructors are used to initialize the object’s state. Like methods, a constructor also contains collection of statements(i.e. instructions) that are executed at time of Object creation. Do we have Copy Constructor in Java?Like C++, Java also supports copy constructor. But, unlike C++, Java doesn’t create a default copy constructor if you don’t write your own.To copy the values of one object into another in java, you can use:ConstructorAssigning the values of one object into anotherclone() method of Object class Constructor Assigning the values of one object into another clone() method of Object class What is Constructor Chaining ?Constructor Chaining is a technique of calling another constructor from one constructor. this() is used to call same class constructor where as super() is used to call super class constructor.// Java program to illustrate Constructor Chaining// within same class Using this() keywordclass Temp{ // default constructor 1 // default constructor will call another constructor // using this keyword from same class Temp() { // calls constructor 2 this(5); System.out.println("The Default constructor"); } // parameterized constructor 2 Temp(int x) { // calls constructor 3 this(5, 15); System.out.println(x); } // parameterized constructor 3 Temp(int x, int y) { System.out.println(x * y); } public static void main(String args[]) { // invokes default constructor first new Temp(); }} // Java program to illustrate Constructor Chaining// within same class Using this() keywordclass Temp{ // default constructor 1 // default constructor will call another constructor // using this keyword from same class Temp() { // calls constructor 2 this(5); System.out.println("The Default constructor"); } // parameterized constructor 2 Temp(int x) { // calls constructor 3 this(5, 15); System.out.println(x); } // parameterized constructor 3 Temp(int x, int y) { System.out.println(x * y); } public static void main(String args[]) { // invokes default constructor first new Temp(); }} Can we call sub class constructor from super class constructor?No. There is no way in java to call sub class constructor from a super class constructor. What happens if you keep a return type for a constructor?Ideally, Constructor must not have a return type. By definition, if a method has a return type, it’s not a constructor.(JLS8.8 Declaration) It will be treated as a normal method. But compiler gives a warning saying that method has a constructor name.Example:class GfG { int GfG() { return 0; // Warning for the return type } } class GfG { int GfG() { return 0; // Warning for the return type } } What is No-arg constructor?Constructor without arguments is called no-arg constructor. Default constructor in java is always a no-arg constructor. class GfG { public GfG() { //No-arg constructor } } class GfG { public GfG() { //No-arg constructor } } How a no – argument constructor is different from default Constructor?If a class contains no constructor declarations, then a default constructor with no formal parameters and no throws clause is implicitly declared.If the class being declared is the primordial class Object, then the default constructor has an empty body. Otherwise, the default constructor simply invokes the superclass constructor with no arguments. If the class being declared is the primordial class Object, then the default constructor has an empty body. Otherwise, the default constructor simply invokes the superclass constructor with no arguments. What are private constructors and where are they used?Like any method we can provide access specifier to the constructor. If it’s made private, then it can only be accessed inside the class.The major scenarios where we use private constructor:Internal Constructor chainingSingleton class design pattern Internal Constructor chaining Singleton class design pattern When do we need Constructor Overloading?Sometimes there is a need of initializing an object in different ways. This can be done using constructor overloading. Different constructors can do different work by implementing different line of codes and are called based on the type and no of parameters passed.According to the situation , a constructor is called with specific number of parameters among overloaded constructors. Do we have destructors in Java?No, Because Java is a garbage collected language you cannot predict when (or even if) an object will be destroyed. Hence there is no direct equivalent of a destructor. Quiz on Constructors This article is contributed by Kiana Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above interview-preparation placement preparation Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Arrays in Java Arrays.sort() in Java with examples Split() String method in Java with examples Reverse a string in Java Object Oriented Programming (OOPs) Concept in Java For-each loop in Java How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples ArrayList in Java
[ { "code": null, "e": 52, "s": 24, "text": "\n28 Jun, 2021" }, { "code": null, "e": 3640, "s": 52, "text": "What is a Constructor?Constructors are used to initialize the object’s state. Like methods, a constructor also contains collection of statements(i.e. instructions) that are executed at time of Object creation.Do we have Copy Constructor in Java?Like C++, Java also supports copy constructor. But, unlike C++, Java doesn’t create a default copy constructor if you don’t write your own.To copy the values of one object into another in java, you can use:ConstructorAssigning the values of one object into anotherclone() method of Object classWhat is Constructor Chaining ?Constructor Chaining is a technique of calling another constructor from one constructor. this() is used to call same class constructor where as super() is used to call super class constructor.// Java program to illustrate Constructor Chaining// within same class Using this() keywordclass Temp{ // default constructor 1 // default constructor will call another constructor // using this keyword from same class Temp() { // calls constructor 2 this(5); System.out.println(\"The Default constructor\"); } // parameterized constructor 2 Temp(int x) { // calls constructor 3 this(5, 15); System.out.println(x); } // parameterized constructor 3 Temp(int x, int y) { System.out.println(x * y); } public static void main(String args[]) { // invokes default constructor first new Temp(); }}Can we call sub class constructor from super class constructor?No. There is no way in java to call sub class constructor from a super class constructor.What happens if you keep a return type for a constructor?Ideally, Constructor must not have a return type. By definition, if a method has a return type, it’s not a constructor.(JLS8.8 Declaration) It will be treated as a normal method. But compiler gives a warning saying that method has a constructor name.Example:class GfG\n{\n int GfG()\n {\n return 0; // Warning for the return type\n }\n}What is No-arg constructor?Constructor without arguments is called no-arg constructor. Default constructor in java is always a no-arg constructor.\nclass GfG\n{\n public GfG()\n {\n //No-arg constructor\n }\n}How a no – argument constructor is different from default Constructor?If a class contains no constructor declarations, then a default constructor with no formal parameters and no throws clause is implicitly declared.If the class being declared is the primordial class Object, then the default constructor has an empty body. Otherwise, the default constructor simply invokes the superclass constructor with no arguments.What are private constructors and where are they used?Like any method we can provide access specifier to the constructor. If it’s made private, then it can only be accessed inside the class.The major scenarios where we use private constructor:Internal Constructor chainingSingleton class design patternWhen do we need Constructor Overloading?Sometimes there is a need of initializing an object in different ways. This can be done using constructor overloading. Different constructors can do different work by implementing different line of codes and are called based on the type and no of parameters passed.According to the situation , a constructor is called with specific number of parameters among overloaded constructors.Do we have destructors in Java?No, Because Java is a garbage collected language you cannot predict when (or even if) an object will be destroyed. Hence there is no direct equivalent of a destructor." }, { "code": null, "e": 3850, "s": 3640, "text": "What is a Constructor?Constructors are used to initialize the object’s state. Like methods, a constructor also contains collection of statements(i.e. instructions) that are executed at time of Object creation." }, { "code": null, "e": 4181, "s": 3850, "text": "Do we have Copy Constructor in Java?Like C++, Java also supports copy constructor. But, unlike C++, Java doesn’t create a default copy constructor if you don’t write your own.To copy the values of one object into another in java, you can use:ConstructorAssigning the values of one object into anotherclone() method of Object class" }, { "code": null, "e": 4193, "s": 4181, "text": "Constructor" }, { "code": null, "e": 4241, "s": 4193, "text": "Assigning the values of one object into another" }, { "code": null, "e": 4272, "s": 4241, "text": "clone() method of Object class" }, { "code": null, "e": 5203, "s": 4272, "text": "What is Constructor Chaining ?Constructor Chaining is a technique of calling another constructor from one constructor. this() is used to call same class constructor where as super() is used to call super class constructor.// Java program to illustrate Constructor Chaining// within same class Using this() keywordclass Temp{ // default constructor 1 // default constructor will call another constructor // using this keyword from same class Temp() { // calls constructor 2 this(5); System.out.println(\"The Default constructor\"); } // parameterized constructor 2 Temp(int x) { // calls constructor 3 this(5, 15); System.out.println(x); } // parameterized constructor 3 Temp(int x, int y) { System.out.println(x * y); } public static void main(String args[]) { // invokes default constructor first new Temp(); }}" }, { "code": "// Java program to illustrate Constructor Chaining// within same class Using this() keywordclass Temp{ // default constructor 1 // default constructor will call another constructor // using this keyword from same class Temp() { // calls constructor 2 this(5); System.out.println(\"The Default constructor\"); } // parameterized constructor 2 Temp(int x) { // calls constructor 3 this(5, 15); System.out.println(x); } // parameterized constructor 3 Temp(int x, int y) { System.out.println(x * y); } public static void main(String args[]) { // invokes default constructor first new Temp(); }}", "e": 5912, "s": 5203, "text": null }, { "code": null, "e": 6065, "s": 5912, "text": "Can we call sub class constructor from super class constructor?No. There is no way in java to call sub class constructor from a super class constructor." }, { "code": null, "e": 6472, "s": 6065, "text": "What happens if you keep a return type for a constructor?Ideally, Constructor must not have a return type. By definition, if a method has a return type, it’s not a constructor.(JLS8.8 Declaration) It will be treated as a normal method. But compiler gives a warning saying that method has a constructor name.Example:class GfG\n{\n int GfG()\n {\n return 0; // Warning for the return type\n }\n}" }, { "code": null, "e": 6564, "s": 6472, "text": "class GfG\n{\n int GfG()\n {\n return 0; // Warning for the return type\n }\n}" }, { "code": null, "e": 6783, "s": 6564, "text": "What is No-arg constructor?Constructor without arguments is called no-arg constructor. Default constructor in java is always a no-arg constructor.\nclass GfG\n{\n public GfG()\n {\n //No-arg constructor\n }\n}" }, { "code": null, "e": 6856, "s": 6783, "text": "\nclass GfG\n{\n public GfG()\n {\n //No-arg constructor\n }\n}" }, { "code": null, "e": 7276, "s": 6856, "text": "How a no – argument constructor is different from default Constructor?If a class contains no constructor declarations, then a default constructor with no formal parameters and no throws clause is implicitly declared.If the class being declared is the primordial class Object, then the default constructor has an empty body. Otherwise, the default constructor simply invokes the superclass constructor with no arguments." }, { "code": null, "e": 7480, "s": 7276, "text": "If the class being declared is the primordial class Object, then the default constructor has an empty body. Otherwise, the default constructor simply invokes the superclass constructor with no arguments." }, { "code": null, "e": 7783, "s": 7480, "text": "What are private constructors and where are they used?Like any method we can provide access specifier to the constructor. If it’s made private, then it can only be accessed inside the class.The major scenarios where we use private constructor:Internal Constructor chainingSingleton class design pattern" }, { "code": null, "e": 7813, "s": 7783, "text": "Internal Constructor chaining" }, { "code": null, "e": 7844, "s": 7813, "text": "Singleton class design pattern" }, { "code": null, "e": 8268, "s": 7844, "text": "When do we need Constructor Overloading?Sometimes there is a need of initializing an object in different ways. This can be done using constructor overloading. Different constructors can do different work by implementing different line of codes and are called based on the type and no of parameters passed.According to the situation , a constructor is called with specific number of parameters among overloaded constructors." }, { "code": null, "e": 8467, "s": 8268, "text": "Do we have destructors in Java?No, Because Java is a garbage collected language you cannot predict when (or even if) an object will be destroyed. Hence there is no direct equivalent of a destructor." }, { "code": null, "e": 8488, "s": 8467, "text": "Quiz on Constructors" }, { "code": null, "e": 8754, "s": 8488, "text": "This article is contributed by Kiana Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 8878, "s": 8754, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 8900, "s": 8878, "text": "interview-preparation" }, { "code": null, "e": 8922, "s": 8900, "text": "placement preparation" }, { "code": null, "e": 8927, "s": 8922, "text": "Java" }, { "code": null, "e": 8932, "s": 8927, "text": "Java" }, { "code": null, "e": 9030, "s": 8932, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9045, "s": 9030, "text": "Arrays in Java" }, { "code": null, "e": 9081, "s": 9045, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 9125, "s": 9081, "text": "Split() String method in Java with examples" }, { "code": null, "e": 9150, "s": 9125, "text": "Reverse a string in Java" }, { "code": null, "e": 9201, "s": 9150, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 9223, "s": 9201, "text": "For-each loop in Java" }, { "code": null, "e": 9254, "s": 9223, "text": "How to iterate any Map in Java" }, { "code": null, "e": 9273, "s": 9254, "text": "Interfaces in Java" }, { "code": null, "e": 9303, "s": 9273, "text": "HashMap in Java with Examples" } ]
Deletion in a Binary Tree
23 Jun, 2022 Given a binary tree, delete a node from it by making sure that the tree shrinks from the bottom (i.e. the deleted node is replaced by the bottom-most and rightmost node). This is different from BST deletion. Here we do not have any order among elements, so we replace them with the last element.Examples : Delete 10 in below tree 10 / \ 20 30Output: 30 / 20 Delete 20 in below tree 10 / \ 20 30 \ 40Output: 10 \ 30 \ 40 Algorithm 1. Starting at the root, find the deepest and rightmost node in the binary tree and the node which we want to delete. 2. Replace the deepest rightmost node’s data with the node to be deleted. 3. Then delete the deepest rightmost node. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to delete element in binary tree#include <bits/stdc++.h>using namespace std; /* A binary tree node has key, pointer to leftchild and a pointer to right child */struct Node { int key; struct Node *left, *right;}; /* function to create a new node of tree andreturn pointer */struct Node* newNode(int key){ struct Node* temp = new Node; temp->key = key; temp->left = temp->right = NULL; return temp;}; /* Inorder traversal of a binary tree*/void inorder(struct Node* temp){ if (!temp) return; inorder(temp->left); cout << temp->key << " "; inorder(temp->right);} /* function to delete the given deepest node(d_node) in binary tree */void deletDeepest(struct Node* root, struct Node* d_node){ queue<struct Node*> q; q.push(root); // Do level order traversal until last node struct Node* temp; while (!q.empty()) { temp = q.front(); q.pop(); if (temp == d_node) { temp = NULL; delete (d_node); return; } if (temp->right) { if (temp->right == d_node) { temp->right = NULL; delete (d_node); return; } else q.push(temp->right); } if (temp->left) { if (temp->left == d_node) { temp->left = NULL; delete (d_node); return; } else q.push(temp->left); } }} /* function to delete element in binary tree */Node* deletion(struct Node* root, int key){ if (root == NULL) return NULL; if (root->left == NULL && root->right == NULL) { if (root->key == key) return NULL; else return root; } queue<struct Node*> q; q.push(root); struct Node* temp; struct Node* key_node = NULL; // Do level order traversal to find deepest // node(temp) and node to be deleted (key_node) while (!q.empty()) { temp = q.front(); q.pop(); if (temp->key == key) key_node = temp; if (temp->left) q.push(temp->left); if (temp->right) q.push(temp->right); } if (key_node != NULL) { int x = temp->key; deletDeepest(root, temp); key_node->key = x; } return root;} // Driver codeint main(){ struct Node* root = newNode(10); root->left = newNode(11); root->left->left = newNode(7); root->left->right = newNode(12); root->right = newNode(9); root->right->left = newNode(15); root->right->right = newNode(8); cout << "Inorder traversal before deletion : "; inorder(root); int key = 11; root = deletion(root, key); cout << endl; cout << "Inorder traversal after deletion : "; inorder(root); return 0;} // Java program to delete element// in binary treeimport java.util.LinkedList;import java.util.Queue; class GFG{ // A binary tree node has key, pointer to// left child and a pointer to right childstatic class Node{ int key; Node left, right; // Constructor Node(int key) { this.key = key; left = null; right = null; }} static Node root;static Node temp = root; // Inorder traversal of a binary treestatic void inorder(Node temp){ if (temp == null) return; inorder(temp.left); System.out.print(temp.key + " "); inorder(temp.right);} // Function to delete deepest// element in binary treestatic void deleteDeepest(Node root, Node delNode){ Queue<Node> q = new LinkedList<Node>(); q.add(root); Node temp = null; // Do level order traversal until last node while (!q.isEmpty()) { temp = q.peek(); q.remove(); if (temp == delNode) { temp = null; return; } if (temp.right!=null) { if (temp.right == delNode) { temp.right = null; return; } else q.add(temp.right); } if (temp.left != null) { if (temp.left == delNode) { temp.left = null; return; } else q.add(temp.left); }}} // Function to delete given element// in binary treestatic void delete(Node root, int key){ if (root == null) return; if (root.left == null && root.right == null) { if (root.key == key) { root=null; return; } else return; } Queue<Node> q = new LinkedList<Node>(); q.add(root); Node temp = null, keyNode = null; // Do level order traversal until // we find key and last node. while (!q.isEmpty()) { temp = q.peek(); q.remove(); if (temp.key == key) keyNode = temp; if (temp.left != null) q.add(temp.left); if (temp.right != null) q.add(temp.right); } if (keyNode != null) { int x = temp.key; deleteDeepest(root, temp); keyNode.key = x; }} // Driver codepublic static void main(String args[]){ root = new Node(10); root.left = new Node(11); root.left.left = new Node(7); root.left.right = new Node(12); root.right = new Node(9); root.right.left = new Node(15); root.right.right = new Node(8); System.out.print("Inorder traversal " + "before deletion:"); inorder(root); int key = 11; delete(root, key); System.out.print("\nInorder traversal " + "after deletion:"); inorder(root);}} // This code is contributed by Ravi Kant Verma # Python3 program to illustrate deletion in a Binary Tree # class to create a node with data, left child and right child.class Node: def __init__(self,data): self.data = data self.left = None self.right = None # Inorder traversal of a binary treedef inorder(temp): if(not temp): return inorder(temp.left) print(temp.data, end = " ") inorder(temp.right) # function to delete the given deepest node (d_node) in binary treedef deleteDeepest(root,d_node): q = [] q.append(root) while(len(q)): temp = q.pop(0) if temp is d_node: temp = None return if temp.right: if temp.right is d_node: temp.right = None return else: q.append(temp.right) if temp.left: if temp.left is d_node: temp.left = None return else: q.append(temp.left) # function to delete element in binary treedef deletion(root, key): if root == None : return None if root.left == None and root.right == None: if root.key == key : return None else : return root key_node = None q = [] q.append(root) temp = None while(len(q)): temp = q.pop(0) if temp.data == key: key_node = temp if temp.left: q.append(temp.left) if temp.right: q.append(temp.right) if key_node : x = temp.data deleteDeepest(root,temp) key_node.data = x return root # Driver codeif __name__=='__main__': root = Node(10) root.left = Node(11) root.left.left = Node(7) root.left.right = Node(12) root.right = Node(9) root.right.left = Node(15) root.right.right = Node(8) print("The tree before the deletion:") inorder(root) key = 11 root = deletion(root, key) print() print("The tree after the deletion;") inorder(root) # This code is contributed by Monika Anandan // C# program to delete element// in binary tree using System;using System.Collections.Generic; class GFG { // A binary tree node has key, pointer to // left child and a pointer to right child public class Node { public int key; public Node left, right; // Constructor public Node(int key) { this.key = key; left = null; right = null; } } static Node root; // Inorder traversal of a binary tree static void inorder(Node temp) { if (temp == null) return; inorder(temp.left); Console.Write(temp.key + " "); inorder(temp.right); } // Function to delete deepest // element in binary tree static void deleteDeepest(Node root, Node delNode) { Queue<Node> q = new Queue<Node>(); q.Enqueue(root); Node temp = null; // Do level order traversal until last node while (q.Count != 0) { temp = q.Peek(); q.Dequeue(); if (temp == delNode) { temp = null; return; } if (temp.right != null) { if (temp.right == delNode) { temp.right = null; return; } else q.Enqueue(temp.right); } if (temp.left != null) { if (temp.left == delNode) { temp.left = null; return; } else q.Enqueue(temp.left); } } } // Function to delete given element // in binary tree static void delete(Node root, int key) { if (root == null) return; if (root.left == null && root.right == null) { if (root.key == key) { root = null; return; } else return; } Queue<Node> q = new Queue<Node>(); q.Enqueue(root); Node temp = null, keyNode = null; // Do level order traversal until // we find key and last node. while (q.Count != 0) { temp = q.Peek(); q.Dequeue(); if (temp.key == key) keyNode = temp; if (temp.left != null) q.Enqueue(temp.left); if (temp.right != null) q.Enqueue(temp.right); } if (keyNode != null) { int x = temp.key; deleteDeepest(root, temp); keyNode.key = x; } } // Driver code public static void Main(String[] args) { root = new Node(10); root.left = new Node(11); root.left.left = new Node(7); root.left.right = new Node(12); root.right = new Node(9); root.right.left = new Node(15); root.right.right = new Node(8); Console.Write("Inorder traversal " + "before deletion: "); inorder(root); int key = 11; delete(root, key); Console.Write("\nInorder traversal " + "after deletion: "); inorder(root); }} // This code is contributed by Abhijeet Kumar(abhijeet19403) <script> // Javascript program to delete element in binary tree class Node { constructor(key) { this.left = null; this.right = null; this.key = key; } } let root; let temp = root; // Inorder traversal of a binary tree function inorder(temp) { if (temp == null) return; inorder(temp.left); document.write(temp.key + " "); inorder(temp.right); } // Function to delete deepest // element in binary tree function deleteDeepest(root, delNode) { let q = []; q.push(root); let temp = null; // Do level order traversal until last node while (q.length > 0) { temp = q[0]; q.shift(); if (temp == delNode) { temp = null; return; } if (temp.right!=null) { if (temp.right == delNode) { temp.right = null; return; } else q.push(temp.right); } if (temp.left != null) { if (temp.left == delNode) { temp.left = null; return; } else q.push(temp.left); } } } // Function to delete given element // in binary tree function Delete(root, key) { if (root == null) return; if (root.left == null && root.right == null) { if (root.key == key) { root=null; return; } else return; } let q = []; q.push(root); let temp = null, keyNode = null; // Do level order traversal until // we find key and last node. while (q.length > 0) { temp = q[0]; q.shift(); if (temp.key == key) keyNode = temp; if (temp.left != null) q.push(temp.left); if (temp.right != null) q.push(temp.right); } if (keyNode != null) { let x = temp.key; deleteDeepest(root, temp); keyNode.key = x; } } root = new Node(10); root.left = new Node(11); root.left.left = new Node(7); root.left.right = new Node(12); root.right = new Node(9); root.right.left = new Node(15); root.right.right = new Node(8); document.write("Inorder traversal " + "before deletion : "); inorder(root); let key = 11; Delete(root, key); document.write("</br>" + "Inorder traversal " + "after deletion : "); inorder(root); </script> Inorder traversal before deletion : 7 11 12 10 15 9 8 Inorder traversal after deletion : 7 8 12 10 15 9 Time complexity: O(n) where n is no number of nodes Auxiliary Space: O(n) size of queue Note: We can also replace the node’s data that is to be deleted with any node whose left and right child points to NULL but we only use deepest node in order to maintain the Balance of a binary tree. Important Note: The above code will not work if the node to be deleted is the deepest node itself because after the function deletDeepest(root, temp) completes execution, the key_node gets deleted(as here key_node is equal to temp)and after which replacing key_node‘s data with the deepest node’s data(temp‘s data) throws a runtime error. Output To avoid the above error and also to avoid doing BFS twice (1st iteration while searching the rightmost deepest node, and 2nd while deleting the rightmost deepest node), we can store the parent node while first traversal and after setting the rightmost deepest node’s data to the node needed deletion, easily delete the rightmost deepest node. C++ C# // C++ program to delete element in binary tree#include <bits/stdc++.h>using namespace std; /* A binary tree node has key, pointer to leftchild and a pointer to right child */struct Node { int data; struct Node *left, *right;}; /* function to create a new node of tree andreturn pointer */struct Node* newNode(int key){ struct Node* temp = new Node; temp->data = key; temp->left = temp->right = NULL; return temp;}; /* Inorder traversal of a binary tree*/void inorder(struct Node* temp){ if (!temp) return; inorder(temp->left); cout << temp->data << " "; inorder(temp->right);} struct Node* deletion(struct Node* root, int key){ if(root==NULL) return NULL; if(root->left==NULL && root->right==NULL) { if(root->data==key) return NULL; else return root; } Node* key_node=NULL; Node* temp; Node* last; queue<Node*> q; q.push(root); // Do level order traversal to find deepest // node(temp), node to be deleted (key_node) // and parent of deepest node(last) while(!q.empty()) { temp=q.front(); q.pop(); if(temp->data==key) key_node=temp; if(temp->left) { last=temp;//storing the parent node q.push(temp->left); } if(temp->right) { last=temp;// storing the parent node q.push(temp->right); } } if(key_node!=NULL) { key_node->data=temp->data;//replacing key_node's data to deepest node's data if(last->right==temp) last->right=NULL; else last->left=NULL; delete(temp); } return root;} // Driver codeint main(){ struct Node* root = newNode(9); root->left = newNode(2); root->left->left = newNode(4); root->left->right = newNode(7); root->right = newNode(8); cout << "Inorder traversal before deletion : "; inorder(root); int key = 7; root = deletion(root, key); cout << endl; cout << "Inorder traversal after deletion : "; inorder(root); return 0;} // This code is designed to delete a node in a Binary Tree using System; namespace BinaryTreeDeletion { public class TreeNode { public int Data; public TreeNode leftNode; public TreeNode rightNode;}public class BinaryTreeOperations { TreeNode rootNode; TreeNode parentNode; int NodeToDelete; int NodeToBeReplaceWith; bool NodeValueReplaced = false; // Driver code public static void Main() { BinaryTreeOperations obj = new BinaryTreeOperations(); obj.AddNode(7); obj.AddNode(2); obj.AddNode(3); obj.AddNode(1); obj.AddNode(10); obj.AddNode(5); obj.AddNode(8); Console.WriteLine( "Inorder Traversal before Deletion : "); obj.PrintInorderTraversalData(obj.rootNode); obj.DeleteNode(5); Console.WriteLine(""); Console.WriteLine( "Inorder Traversal after Deletion : "); obj.PrintInorderTraversalData(obj.rootNode); } void PrintInorderTraversalData(TreeNode Node) { if (Node != null) { PrintInorderTraversalData(Node.leftNode); Console.Write(Node.Data + " "); PrintInorderTraversalData(Node.rightNode); } } public void AddNode(int Value) { TreeNode beforeNode = null; TreeNode afterNode = this.rootNode; while (afterNode != null) { beforeNode = afterNode; if (Value < afterNode.Data) afterNode = afterNode.leftNode; else if (Value > afterNode.Data) afterNode = afterNode.rightNode; else return; } TreeNode newNode = new TreeNode(); newNode.Data = Value; if (this.rootNode == null) rootNode = newNode; else { if (Value < beforeNode.Data) { beforeNode.leftNode = newNode; } else { beforeNode.rightNode = newNode; } } } void DeleteNode(int Value) { if (rootNode == null) { return; } NodeToBeReplaceWith = FindDeepestNode(rootNode); NodeToDelete = Value; Search(rootNode); } int FindDeepestNode(TreeNode rootnode) { if (rootnode.leftNode == null && rootnode.rightNode == null) { int deepestVal = rootnode.Data; parentNode.leftNode = null; parentNode.rightNode = null; return deepestVal; } parentNode = rootnode; return FindDeepestNode(rootnode.rightNode != null ? rootnode.rightNode : rootnode.leftNode); } void Search(TreeNode node) { if (!NodeValueReplaced) { SearchAndReplace(node.leftNode); } if (!NodeValueReplaced) { SearchAndReplace(node.rightNode); } } void SearchAndReplace(TreeNode rootnode) { if (rootnode == null) { return; } if (rootnode.Data == NodeToDelete) { rootnode.Data = NodeToBeReplaceWith; NodeValueReplaced = true; return; } if (!NodeValueReplaced) { SearchAndReplace(rootnode.leftNode); } if (!NodeValueReplaced) { SearchAndReplace(rootnode.rightNode); } }}} // This code is contributed by Prakher Mehrotra Inorder traversal before deletion : 4 2 7 9 8 Inorder traversal after deletion : 4 2 9 8 Time complexity: O(n) where n is no number of nodes Auxiliary Space: O(n) size of queue This article is contributed by Yash Singla and Peehoo Jain. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Kumar Shubham 10 MonikaAnandan Vidhayak_Chacha Punpun AakashYadav4 The_Error divyesh072019 snehaspatil6327 peehoojain2 harendrakumar123 prakhermehrotra noviced3vq6 abhijeet19403 cpp-queu tree-level-order Tree Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. AVL Tree | Set 1 (Insertion) Introduction to Data Structures What is Data Structure: Types, Classifications and Applications A program to check if a binary tree is BST or not Decision Tree Top 50 Tree Coding Problems for Interviews Segment Tree | Set 1 (Sum of given range) Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash) Complexity of different operations in Binary tree, Binary Search Tree and AVL tree Sorted Array to Balanced BST
[ { "code": null, "e": 54, "s": 26, "text": "\n23 Jun, 2022" }, { "code": null, "e": 360, "s": 54, "text": "Given a binary tree, delete a node from it by making sure that the tree shrinks from the bottom (i.e. the deleted node is replaced by the bottom-most and rightmost node). This is different from BST deletion. Here we do not have any order among elements, so we replace them with the last element.Examples :" }, { "code": null, "e": 384, "s": 360, "text": "Delete 10 in below tree" }, { "code": null, "e": 472, "s": 384, "text": " 10 / \\ 20 30Output: 30 / 20 " }, { "code": null, "e": 645, "s": 472, "text": "Delete 20 in below tree 10 / \\ 20 30 \\ 40Output: 10 \\ 30 \\ 40 " }, { "code": null, "e": 890, "s": 645, "text": "Algorithm 1. Starting at the root, find the deepest and rightmost node in the binary tree and the node which we want to delete. 2. Replace the deepest rightmost node’s data with the node to be deleted. 3. Then delete the deepest rightmost node." }, { "code": null, "e": 941, "s": 890, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 945, "s": 941, "text": "C++" }, { "code": null, "e": 950, "s": 945, "text": "Java" }, { "code": null, "e": 958, "s": 950, "text": "Python3" }, { "code": null, "e": 961, "s": 958, "text": "C#" }, { "code": null, "e": 972, "s": 961, "text": "Javascript" }, { "code": "// C++ program to delete element in binary tree#include <bits/stdc++.h>using namespace std; /* A binary tree node has key, pointer to leftchild and a pointer to right child */struct Node { int key; struct Node *left, *right;}; /* function to create a new node of tree andreturn pointer */struct Node* newNode(int key){ struct Node* temp = new Node; temp->key = key; temp->left = temp->right = NULL; return temp;}; /* Inorder traversal of a binary tree*/void inorder(struct Node* temp){ if (!temp) return; inorder(temp->left); cout << temp->key << \" \"; inorder(temp->right);} /* function to delete the given deepest node(d_node) in binary tree */void deletDeepest(struct Node* root, struct Node* d_node){ queue<struct Node*> q; q.push(root); // Do level order traversal until last node struct Node* temp; while (!q.empty()) { temp = q.front(); q.pop(); if (temp == d_node) { temp = NULL; delete (d_node); return; } if (temp->right) { if (temp->right == d_node) { temp->right = NULL; delete (d_node); return; } else q.push(temp->right); } if (temp->left) { if (temp->left == d_node) { temp->left = NULL; delete (d_node); return; } else q.push(temp->left); } }} /* function to delete element in binary tree */Node* deletion(struct Node* root, int key){ if (root == NULL) return NULL; if (root->left == NULL && root->right == NULL) { if (root->key == key) return NULL; else return root; } queue<struct Node*> q; q.push(root); struct Node* temp; struct Node* key_node = NULL; // Do level order traversal to find deepest // node(temp) and node to be deleted (key_node) while (!q.empty()) { temp = q.front(); q.pop(); if (temp->key == key) key_node = temp; if (temp->left) q.push(temp->left); if (temp->right) q.push(temp->right); } if (key_node != NULL) { int x = temp->key; deletDeepest(root, temp); key_node->key = x; } return root;} // Driver codeint main(){ struct Node* root = newNode(10); root->left = newNode(11); root->left->left = newNode(7); root->left->right = newNode(12); root->right = newNode(9); root->right->left = newNode(15); root->right->right = newNode(8); cout << \"Inorder traversal before deletion : \"; inorder(root); int key = 11; root = deletion(root, key); cout << endl; cout << \"Inorder traversal after deletion : \"; inorder(root); return 0;}", "e": 3815, "s": 972, "text": null }, { "code": "// Java program to delete element// in binary treeimport java.util.LinkedList;import java.util.Queue; class GFG{ // A binary tree node has key, pointer to// left child and a pointer to right childstatic class Node{ int key; Node left, right; // Constructor Node(int key) { this.key = key; left = null; right = null; }} static Node root;static Node temp = root; // Inorder traversal of a binary treestatic void inorder(Node temp){ if (temp == null) return; inorder(temp.left); System.out.print(temp.key + \" \"); inorder(temp.right);} // Function to delete deepest// element in binary treestatic void deleteDeepest(Node root, Node delNode){ Queue<Node> q = new LinkedList<Node>(); q.add(root); Node temp = null; // Do level order traversal until last node while (!q.isEmpty()) { temp = q.peek(); q.remove(); if (temp == delNode) { temp = null; return; } if (temp.right!=null) { if (temp.right == delNode) { temp.right = null; return; } else q.add(temp.right); } if (temp.left != null) { if (temp.left == delNode) { temp.left = null; return; } else q.add(temp.left); }}} // Function to delete given element// in binary treestatic void delete(Node root, int key){ if (root == null) return; if (root.left == null && root.right == null) { if (root.key == key) { root=null; return; } else return; } Queue<Node> q = new LinkedList<Node>(); q.add(root); Node temp = null, keyNode = null; // Do level order traversal until // we find key and last node. while (!q.isEmpty()) { temp = q.peek(); q.remove(); if (temp.key == key) keyNode = temp; if (temp.left != null) q.add(temp.left); if (temp.right != null) q.add(temp.right); } if (keyNode != null) { int x = temp.key; deleteDeepest(root, temp); keyNode.key = x; }} // Driver codepublic static void main(String args[]){ root = new Node(10); root.left = new Node(11); root.left.left = new Node(7); root.left.right = new Node(12); root.right = new Node(9); root.right.left = new Node(15); root.right.right = new Node(8); System.out.print(\"Inorder traversal \" + \"before deletion:\"); inorder(root); int key = 11; delete(root, key); System.out.print(\"\\nInorder traversal \" + \"after deletion:\"); inorder(root);}} // This code is contributed by Ravi Kant Verma", "e": 6698, "s": 3815, "text": null }, { "code": "# Python3 program to illustrate deletion in a Binary Tree # class to create a node with data, left child and right child.class Node: def __init__(self,data): self.data = data self.left = None self.right = None # Inorder traversal of a binary treedef inorder(temp): if(not temp): return inorder(temp.left) print(temp.data, end = \" \") inorder(temp.right) # function to delete the given deepest node (d_node) in binary treedef deleteDeepest(root,d_node): q = [] q.append(root) while(len(q)): temp = q.pop(0) if temp is d_node: temp = None return if temp.right: if temp.right is d_node: temp.right = None return else: q.append(temp.right) if temp.left: if temp.left is d_node: temp.left = None return else: q.append(temp.left) # function to delete element in binary treedef deletion(root, key): if root == None : return None if root.left == None and root.right == None: if root.key == key : return None else : return root key_node = None q = [] q.append(root) temp = None while(len(q)): temp = q.pop(0) if temp.data == key: key_node = temp if temp.left: q.append(temp.left) if temp.right: q.append(temp.right) if key_node : x = temp.data deleteDeepest(root,temp) key_node.data = x return root # Driver codeif __name__=='__main__': root = Node(10) root.left = Node(11) root.left.left = Node(7) root.left.right = Node(12) root.right = Node(9) root.right.left = Node(15) root.right.right = Node(8) print(\"The tree before the deletion:\") inorder(root) key = 11 root = deletion(root, key) print() print(\"The tree after the deletion;\") inorder(root) # This code is contributed by Monika Anandan", "e": 8723, "s": 6698, "text": null }, { "code": "// C# program to delete element// in binary tree using System;using System.Collections.Generic; class GFG { // A binary tree node has key, pointer to // left child and a pointer to right child public class Node { public int key; public Node left, right; // Constructor public Node(int key) { this.key = key; left = null; right = null; } } static Node root; // Inorder traversal of a binary tree static void inorder(Node temp) { if (temp == null) return; inorder(temp.left); Console.Write(temp.key + \" \"); inorder(temp.right); } // Function to delete deepest // element in binary tree static void deleteDeepest(Node root, Node delNode) { Queue<Node> q = new Queue<Node>(); q.Enqueue(root); Node temp = null; // Do level order traversal until last node while (q.Count != 0) { temp = q.Peek(); q.Dequeue(); if (temp == delNode) { temp = null; return; } if (temp.right != null) { if (temp.right == delNode) { temp.right = null; return; } else q.Enqueue(temp.right); } if (temp.left != null) { if (temp.left == delNode) { temp.left = null; return; } else q.Enqueue(temp.left); } } } // Function to delete given element // in binary tree static void delete(Node root, int key) { if (root == null) return; if (root.left == null && root.right == null) { if (root.key == key) { root = null; return; } else return; } Queue<Node> q = new Queue<Node>(); q.Enqueue(root); Node temp = null, keyNode = null; // Do level order traversal until // we find key and last node. while (q.Count != 0) { temp = q.Peek(); q.Dequeue(); if (temp.key == key) keyNode = temp; if (temp.left != null) q.Enqueue(temp.left); if (temp.right != null) q.Enqueue(temp.right); } if (keyNode != null) { int x = temp.key; deleteDeepest(root, temp); keyNode.key = x; } } // Driver code public static void Main(String[] args) { root = new Node(10); root.left = new Node(11); root.left.left = new Node(7); root.left.right = new Node(12); root.right = new Node(9); root.right.left = new Node(15); root.right.right = new Node(8); Console.Write(\"Inorder traversal \" + \"before deletion: \"); inorder(root); int key = 11; delete(root, key); Console.Write(\"\\nInorder traversal \" + \"after deletion: \"); inorder(root); }} // This code is contributed by Abhijeet Kumar(abhijeet19403)", "e": 11964, "s": 8723, "text": null }, { "code": "<script> // Javascript program to delete element in binary tree class Node { constructor(key) { this.left = null; this.right = null; this.key = key; } } let root; let temp = root; // Inorder traversal of a binary tree function inorder(temp) { if (temp == null) return; inorder(temp.left); document.write(temp.key + \" \"); inorder(temp.right); } // Function to delete deepest // element in binary tree function deleteDeepest(root, delNode) { let q = []; q.push(root); let temp = null; // Do level order traversal until last node while (q.length > 0) { temp = q[0]; q.shift(); if (temp == delNode) { temp = null; return; } if (temp.right!=null) { if (temp.right == delNode) { temp.right = null; return; } else q.push(temp.right); } if (temp.left != null) { if (temp.left == delNode) { temp.left = null; return; } else q.push(temp.left); } } } // Function to delete given element // in binary tree function Delete(root, key) { if (root == null) return; if (root.left == null && root.right == null) { if (root.key == key) { root=null; return; } else return; } let q = []; q.push(root); let temp = null, keyNode = null; // Do level order traversal until // we find key and last node. while (q.length > 0) { temp = q[0]; q.shift(); if (temp.key == key) keyNode = temp; if (temp.left != null) q.push(temp.left); if (temp.right != null) q.push(temp.right); } if (keyNode != null) { let x = temp.key; deleteDeepest(root, temp); keyNode.key = x; } } root = new Node(10); root.left = new Node(11); root.left.left = new Node(7); root.left.right = new Node(12); root.right = new Node(9); root.right.left = new Node(15); root.right.right = new Node(8); document.write(\"Inorder traversal \" + \"before deletion : \"); inorder(root); let key = 11; Delete(root, key); document.write(\"</br>\" + \"Inorder traversal \" + \"after deletion : \"); inorder(root); </script>", "e": 14791, "s": 11964, "text": null }, { "code": null, "e": 14897, "s": 14791, "text": "Inorder traversal before deletion : 7 11 12 10 15 9 8 \nInorder traversal after deletion : 7 8 12 10 15 9 " }, { "code": null, "e": 14949, "s": 14897, "text": "Time complexity: O(n) where n is no number of nodes" }, { "code": null, "e": 14985, "s": 14949, "text": "Auxiliary Space: O(n) size of queue" }, { "code": null, "e": 15185, "s": 14985, "text": "Note: We can also replace the node’s data that is to be deleted with any node whose left and right child points to NULL but we only use deepest node in order to maintain the Balance of a binary tree." }, { "code": null, "e": 15524, "s": 15185, "text": "Important Note: The above code will not work if the node to be deleted is the deepest node itself because after the function deletDeepest(root, temp) completes execution, the key_node gets deleted(as here key_node is equal to temp)and after which replacing key_node‘s data with the deepest node’s data(temp‘s data) throws a runtime error." }, { "code": null, "e": 15531, "s": 15524, "text": "Output" }, { "code": null, "e": 15875, "s": 15531, "text": "To avoid the above error and also to avoid doing BFS twice (1st iteration while searching the rightmost deepest node, and 2nd while deleting the rightmost deepest node), we can store the parent node while first traversal and after setting the rightmost deepest node’s data to the node needed deletion, easily delete the rightmost deepest node." }, { "code": null, "e": 15879, "s": 15875, "text": "C++" }, { "code": null, "e": 15882, "s": 15879, "text": "C#" }, { "code": "// C++ program to delete element in binary tree#include <bits/stdc++.h>using namespace std; /* A binary tree node has key, pointer to leftchild and a pointer to right child */struct Node { int data; struct Node *left, *right;}; /* function to create a new node of tree andreturn pointer */struct Node* newNode(int key){ struct Node* temp = new Node; temp->data = key; temp->left = temp->right = NULL; return temp;}; /* Inorder traversal of a binary tree*/void inorder(struct Node* temp){ if (!temp) return; inorder(temp->left); cout << temp->data << \" \"; inorder(temp->right);} struct Node* deletion(struct Node* root, int key){ if(root==NULL) return NULL; if(root->left==NULL && root->right==NULL) { if(root->data==key) return NULL; else return root; } Node* key_node=NULL; Node* temp; Node* last; queue<Node*> q; q.push(root); // Do level order traversal to find deepest // node(temp), node to be deleted (key_node) // and parent of deepest node(last) while(!q.empty()) { temp=q.front(); q.pop(); if(temp->data==key) key_node=temp; if(temp->left) { last=temp;//storing the parent node q.push(temp->left); } if(temp->right) { last=temp;// storing the parent node q.push(temp->right); } } if(key_node!=NULL) { key_node->data=temp->data;//replacing key_node's data to deepest node's data if(last->right==temp) last->right=NULL; else last->left=NULL; delete(temp); } return root;} // Driver codeint main(){ struct Node* root = newNode(9); root->left = newNode(2); root->left->left = newNode(4); root->left->right = newNode(7); root->right = newNode(8); cout << \"Inorder traversal before deletion : \"; inorder(root); int key = 7; root = deletion(root, key); cout << endl; cout << \"Inorder traversal after deletion : \"; inorder(root); return 0;}", "e": 18013, "s": 15882, "text": null }, { "code": "// This code is designed to delete a node in a Binary Tree using System; namespace BinaryTreeDeletion { public class TreeNode { public int Data; public TreeNode leftNode; public TreeNode rightNode;}public class BinaryTreeOperations { TreeNode rootNode; TreeNode parentNode; int NodeToDelete; int NodeToBeReplaceWith; bool NodeValueReplaced = false; // Driver code public static void Main() { BinaryTreeOperations obj = new BinaryTreeOperations(); obj.AddNode(7); obj.AddNode(2); obj.AddNode(3); obj.AddNode(1); obj.AddNode(10); obj.AddNode(5); obj.AddNode(8); Console.WriteLine( \"Inorder Traversal before Deletion : \"); obj.PrintInorderTraversalData(obj.rootNode); obj.DeleteNode(5); Console.WriteLine(\"\"); Console.WriteLine( \"Inorder Traversal after Deletion : \"); obj.PrintInorderTraversalData(obj.rootNode); } void PrintInorderTraversalData(TreeNode Node) { if (Node != null) { PrintInorderTraversalData(Node.leftNode); Console.Write(Node.Data + \" \"); PrintInorderTraversalData(Node.rightNode); } } public void AddNode(int Value) { TreeNode beforeNode = null; TreeNode afterNode = this.rootNode; while (afterNode != null) { beforeNode = afterNode; if (Value < afterNode.Data) afterNode = afterNode.leftNode; else if (Value > afterNode.Data) afterNode = afterNode.rightNode; else return; } TreeNode newNode = new TreeNode(); newNode.Data = Value; if (this.rootNode == null) rootNode = newNode; else { if (Value < beforeNode.Data) { beforeNode.leftNode = newNode; } else { beforeNode.rightNode = newNode; } } } void DeleteNode(int Value) { if (rootNode == null) { return; } NodeToBeReplaceWith = FindDeepestNode(rootNode); NodeToDelete = Value; Search(rootNode); } int FindDeepestNode(TreeNode rootnode) { if (rootnode.leftNode == null && rootnode.rightNode == null) { int deepestVal = rootnode.Data; parentNode.leftNode = null; parentNode.rightNode = null; return deepestVal; } parentNode = rootnode; return FindDeepestNode(rootnode.rightNode != null ? rootnode.rightNode : rootnode.leftNode); } void Search(TreeNode node) { if (!NodeValueReplaced) { SearchAndReplace(node.leftNode); } if (!NodeValueReplaced) { SearchAndReplace(node.rightNode); } } void SearchAndReplace(TreeNode rootnode) { if (rootnode == null) { return; } if (rootnode.Data == NodeToDelete) { rootnode.Data = NodeToBeReplaceWith; NodeValueReplaced = true; return; } if (!NodeValueReplaced) { SearchAndReplace(rootnode.leftNode); } if (!NodeValueReplaced) { SearchAndReplace(rootnode.rightNode); } }}} // This code is contributed by Prakher Mehrotra", "e": 21426, "s": 18013, "text": null }, { "code": null, "e": 21517, "s": 21426, "text": "Inorder traversal before deletion : 4 2 7 9 8 \nInorder traversal after deletion : 4 2 9 8 " }, { "code": null, "e": 21569, "s": 21517, "text": "Time complexity: O(n) where n is no number of nodes" }, { "code": null, "e": 21605, "s": 21569, "text": "Auxiliary Space: O(n) size of queue" }, { "code": null, "e": 22040, "s": 21605, "text": "This article is contributed by Yash Singla and Peehoo Jain. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 22057, "s": 22040, "text": "Kumar Shubham 10" }, { "code": null, "e": 22071, "s": 22057, "text": "MonikaAnandan" }, { "code": null, "e": 22087, "s": 22071, "text": "Vidhayak_Chacha" }, { "code": null, "e": 22094, "s": 22087, "text": "Punpun" }, { "code": null, "e": 22107, "s": 22094, "text": "AakashYadav4" }, { "code": null, "e": 22117, "s": 22107, "text": "The_Error" }, { "code": null, "e": 22131, "s": 22117, "text": "divyesh072019" }, { "code": null, "e": 22147, "s": 22131, "text": "snehaspatil6327" }, { "code": null, "e": 22159, "s": 22147, "text": "peehoojain2" }, { "code": null, "e": 22176, "s": 22159, "text": "harendrakumar123" }, { "code": null, "e": 22192, "s": 22176, "text": "prakhermehrotra" }, { "code": null, "e": 22204, "s": 22192, "text": "noviced3vq6" }, { "code": null, "e": 22218, "s": 22204, "text": "abhijeet19403" }, { "code": null, "e": 22227, "s": 22218, "text": "cpp-queu" }, { "code": null, "e": 22244, "s": 22227, "text": "tree-level-order" }, { "code": null, "e": 22249, "s": 22244, "text": "Tree" }, { "code": null, "e": 22254, "s": 22249, "text": "Tree" }, { "code": null, "e": 22352, "s": 22254, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 22381, "s": 22352, "text": "AVL Tree | Set 1 (Insertion)" }, { "code": null, "e": 22413, "s": 22381, "text": "Introduction to Data Structures" }, { "code": null, "e": 22477, "s": 22413, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 22527, "s": 22477, "text": "A program to check if a binary tree is BST or not" }, { "code": null, "e": 22541, "s": 22527, "text": "Decision Tree" }, { "code": null, "e": 22584, "s": 22541, "text": "Top 50 Tree Coding Problems for Interviews" }, { "code": null, "e": 22626, "s": 22584, "text": "Segment Tree | Set 1 (Sum of given range)" }, { "code": null, "e": 22696, "s": 22626, "text": "Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash)" }, { "code": null, "e": 22779, "s": 22696, "text": "Complexity of different operations in Binary tree, Binary Search Tree and AVL tree" } ]
Java Program to Find all triplets with zero sum
06 Jan, 2022 Given an array of distinct elements. The task is to find triplets in the array whose sum is zero. Examples : Input : arr[] = {0, -1, 2, -3, 1} Output : (0 -1 1), (2 -3 1) Explanation : The triplets with zero sum are 0 + -1 + 1 = 0 and 2 + -3 + 1 = 0 Input : arr[] = {1, -2, 1, 0, 5} Output : 1 -2 1 Explanation : The triplets with zero sum is 1 + -2 + 1 = 0 Method 1: This is a simple method that takes O(n3) time to arrive at the result. Approach: The naive approach runs three loops and check one by one that sum of three elements is zero or not. If the sum of three elements is zero then print elements otherwise print not found. Algorithm: Run three nested loops with loop counter i, j, kThe first loops will run from 0 to n-3 and second loop from i+1 to n-2 and the third loop from j+1 to n-1. The loop counter represents the three elements of the triplet.Check if the sum of elements at i’th, j’th, k’th is equal to zero or not. If yes print the sum else continue. Run three nested loops with loop counter i, j, kThe first loops will run from 0 to n-3 and second loop from i+1 to n-2 and the third loop from j+1 to n-1. The loop counter represents the three elements of the triplet.Check if the sum of elements at i’th, j’th, k’th is equal to zero or not. If yes print the sum else continue. Run three nested loops with loop counter i, j, k The first loops will run from 0 to n-3 and second loop from i+1 to n-2 and the third loop from j+1 to n-1. The loop counter represents the three elements of the triplet. Check if the sum of elements at i’th, j’th, k’th is equal to zero or not. If yes print the sum else continue. Below is the implementation of the above approach: Java // A simple Java program to find three elements// whose sum is equal to zeroclass num{// Prints all triplets in arr[] with 0 sumstatic void findTriplets(int[] arr, int n){ boolean found = false; for (int i=0; i<n-2; i++) { for (int j=i+1; j<n-1; j++) { for (int k=j+1; k<n; k++) { if (arr[i]+arr[j]+arr[k] == 0) { System.out.print(arr[i]); System.out.print(" "); System.out.print(arr[j]); System.out.print(" "); System.out.print(arr[k]); System.out.print(""); found = true; } } } } // If no triplet with 0 sum found in array if (found == false) System.out.println(" not exist "); } // Driver codepublic static void main(String[] args){ int arr[] = {0, -1, 2, -3, 1}; int n =arr.length; findTriplets(arr, n); }}//This code is contributed by//Smitha Dinesh Semwal 0 -1 1 2 -3 1 Complexity Analysis: Time Complexity: O(n3). As three nested loops are required, so the time complexity is O(n3). Auxiliary Space: O(1). Since no extra space is required, so the space complexity is constant. Method 2: The second method uses the process of Hashing to arrive at the result and is solved at a lesser time of O(n2). Approach: This involves traversing through the array. For every element arr[i], find a pair with sum “-arr[i]”. This problem reduces to pair sum and can be solved in O(n) time using hashing. Algorithm: Create a hashmap to store a key-value pair.Run a nested loop with two loops, the outer loop from 0 to n-2 and the inner loop from i+1 to n-1Check if the sum of ith and jth element multiplied with -1 is present in the hashmap or notIf the element is present in the hashmap, print the triplet else insert the j’th element in the hashmap. Create a hashmap to store a key-value pair. Run a nested loop with two loops, the outer loop from 0 to n-2 and the inner loop from i+1 to n-1 Check if the sum of ith and jth element multiplied with -1 is present in the hashmap or not If the element is present in the hashmap, print the triplet else insert the j’th element in the hashmap. Below is the implementation of the above approach: Java // Java program to find triplets in a given// array whose sum is zeroimport java.util.*; class GFG { // function to print triplets with 0 sum static void findTriplets(int arr[], int n) { boolean found = false; for (int i = 0; i < n - 1; i++) { // Find all pairs with sum equals to // "-arr[i]" HashSet<Integer> s = new HashSet<Integer>(); for (int j = i + 1; j < n; j++) { int x = -(arr[i] + arr[j]); if (s.contains(x)) { System.out.printf("%d %d %d", x, arr[i], arr[j]); found = true; } else { s.add(arr[j]); } } } if (found == false) { System.out.printf(" No Triplet Found"); } } // Driver code public static void main(String[] args) { int arr[] = {0, -1, 2, -3, 1}; int n = arr.length; findTriplets(arr, n); }} // This code contributed by Rajput-Ji -1 0 1 -3 2 1 Complexity Analysis: Time Complexity: O(n2). Since two nested loops are required, so the time complexity is O(n2). Auxiliary Space: O(n). Since a hashmap is required, so the space complexity is linear. Method 3: This method uses Sorting to arrive at the correct result and is solved in O(n2) time. Approach: The above method requires extra space. The idea is based on method 2 of this post. For every element check that there is a pair whose sum is equal to the negative value of that element. Algorithm: Sort the array in ascending order.Traverse the array from start to end.For every index i, create two variables l = i + 1 and r = n – 1Run a loop until l is less than r if the sum of array[i], array[l] and array[r] is equal to zero then print the triplet and break the loopIf the sum is less than zero then increment the value of l, by increasing the value of l the sum will increase as the array is sorted, so array[l+1] > array [l]If the sum is greater than zero then decrement the value of r, by increasing the value of l the sum will decrease as the array is sorted, so array[r-1] < array [r]. Sort the array in ascending order. Traverse the array from start to end. For every index i, create two variables l = i + 1 and r = n – 1 Run a loop until l is less than r if the sum of array[i], array[l] and array[r] is equal to zero then print the triplet and break the loop If the sum is less than zero then increment the value of l, by increasing the value of l the sum will increase as the array is sorted, so array[l+1] > array [l] If the sum is greater than zero then decrement the value of r, by increasing the value of l the sum will decrease as the array is sorted, so array[r-1] < array [r]. Below is the implementation of the above approach: Java // Java program to find triplets in a given// array whose sum is zeroimport java.util.Arrays; import java.io.*; class GFG { // function to print triplets with 0 sumstatic void findTriplets(int arr[], int n){ boolean found = false; // sort array elements Arrays.sort(arr); for (int i=0; i<n-1; i++) { // initialize left and right int l = i + 1; int r = n - 1; int x = arr[i]; while (l < r) { if (x + arr[l] + arr[r] == 0) { // print elements if it's sum is zero System.out.print(x + " "); System.out.print(arr[l]+ " "); System.out.println(arr[r]+ " "); l++; r--; found = true; } // If sum of three elements is less // than zero then increment in left else if (x + arr[l] + arr[r] < 0) l++; // if sum is greater than zero than // decrement in right side else r--; } } if (found == false) System.out.println(" No Triplet Found");} // Driven source public static void main (String[] args) { int arr[] = {0, -1, 2, -3, 1}; int n =arr.length; findTriplets(arr, n); }//This code is contributed by Tushil.. } -3 1 2 -1 0 1 Complexity Analysis: Time Complexity : O(n2). Only two nested loops are required, so the time complexity is O(n2). Auxiliary Space : O(1), no extra space is required, so the time complexity is constant. Please refer complete article on Find all triplets with zero sum for more details! Facebook Google two-pointer-algorithm Arrays Hash Java Java Programs Searching Sorting Google Facebook two-pointer-algorithm Arrays Searching Hash Sorting Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Data Structures Window Sliding Technique Search, insert and delete in an unsorted array What is Data Structure: Types, Classifications and Applications Chocolate Distribution Problem What is Hashing | A Complete Tutorial Internal Working of HashMap in Java Hashing | Set 1 (Introduction) Count pairs with given sum Sort string of characters
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Jan, 2022" }, { "code": null, "e": 126, "s": 28, "text": "Given an array of distinct elements. The task is to find triplets in the array whose sum is zero." }, { "code": null, "e": 138, "s": 126, "text": "Examples : " }, { "code": null, "e": 395, "s": 138, "text": "Input : arr[] = {0, -1, 2, -3, 1}\nOutput : (0 -1 1), (2 -3 1)\n\nExplanation : The triplets with zero sum are\n0 + -1 + 1 = 0 and 2 + -3 + 1 = 0 \n\nInput : arr[] = {1, -2, 1, 0, 5}\nOutput : 1 -2 1\nExplanation : The triplets with zero sum is\n1 + -2 + 1 = 0 " }, { "code": null, "e": 476, "s": 395, "text": "Method 1: This is a simple method that takes O(n3) time to arrive at the result." }, { "code": null, "e": 670, "s": 476, "text": "Approach: The naive approach runs three loops and check one by one that sum of three elements is zero or not. If the sum of three elements is zero then print elements otherwise print not found." }, { "code": null, "e": 1008, "s": 670, "text": "Algorithm: Run three nested loops with loop counter i, j, kThe first loops will run from 0 to n-3 and second loop from i+1 to n-2 and the third loop from j+1 to n-1. The loop counter represents the three elements of the triplet.Check if the sum of elements at i’th, j’th, k’th is equal to zero or not. If yes print the sum else continue." }, { "code": null, "e": 1335, "s": 1008, "text": "Run three nested loops with loop counter i, j, kThe first loops will run from 0 to n-3 and second loop from i+1 to n-2 and the third loop from j+1 to n-1. The loop counter represents the three elements of the triplet.Check if the sum of elements at i’th, j’th, k’th is equal to zero or not. If yes print the sum else continue." }, { "code": null, "e": 1384, "s": 1335, "text": "Run three nested loops with loop counter i, j, k" }, { "code": null, "e": 1554, "s": 1384, "text": "The first loops will run from 0 to n-3 and second loop from i+1 to n-2 and the third loop from j+1 to n-1. The loop counter represents the three elements of the triplet." }, { "code": null, "e": 1664, "s": 1554, "text": "Check if the sum of elements at i’th, j’th, k’th is equal to zero or not. If yes print the sum else continue." }, { "code": null, "e": 1716, "s": 1664, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 1721, "s": 1716, "text": "Java" }, { "code": "// A simple Java program to find three elements// whose sum is equal to zeroclass num{// Prints all triplets in arr[] with 0 sumstatic void findTriplets(int[] arr, int n){ boolean found = false; for (int i=0; i<n-2; i++) { for (int j=i+1; j<n-1; j++) { for (int k=j+1; k<n; k++) { if (arr[i]+arr[j]+arr[k] == 0) { System.out.print(arr[i]); System.out.print(\" \"); System.out.print(arr[j]); System.out.print(\" \"); System.out.print(arr[k]); System.out.print(\"\"); found = true; } } } } // If no triplet with 0 sum found in array if (found == false) System.out.println(\" not exist \"); } // Driver codepublic static void main(String[] args){ int arr[] = {0, -1, 2, -3, 1}; int n =arr.length; findTriplets(arr, n); }}//This code is contributed by//Smitha Dinesh Semwal", "e": 2754, "s": 1721, "text": null }, { "code": null, "e": 2768, "s": 2754, "text": "0 -1 1\n2 -3 1" }, { "code": null, "e": 2790, "s": 2768, "text": "Complexity Analysis: " }, { "code": null, "e": 2883, "s": 2790, "text": "Time Complexity: O(n3). As three nested loops are required, so the time complexity is O(n3)." }, { "code": null, "e": 2977, "s": 2883, "text": "Auxiliary Space: O(1). Since no extra space is required, so the space complexity is constant." }, { "code": null, "e": 3100, "s": 2977, "text": " Method 2: The second method uses the process of Hashing to arrive at the result and is solved at a lesser time of O(n2). " }, { "code": null, "e": 3291, "s": 3100, "text": "Approach: This involves traversing through the array. For every element arr[i], find a pair with sum “-arr[i]”. This problem reduces to pair sum and can be solved in O(n) time using hashing." }, { "code": null, "e": 3303, "s": 3291, "text": "Algorithm: " }, { "code": null, "e": 3639, "s": 3303, "text": "Create a hashmap to store a key-value pair.Run a nested loop with two loops, the outer loop from 0 to n-2 and the inner loop from i+1 to n-1Check if the sum of ith and jth element multiplied with -1 is present in the hashmap or notIf the element is present in the hashmap, print the triplet else insert the j’th element in the hashmap." }, { "code": null, "e": 3683, "s": 3639, "text": "Create a hashmap to store a key-value pair." }, { "code": null, "e": 3781, "s": 3683, "text": "Run a nested loop with two loops, the outer loop from 0 to n-2 and the inner loop from i+1 to n-1" }, { "code": null, "e": 3873, "s": 3781, "text": "Check if the sum of ith and jth element multiplied with -1 is present in the hashmap or not" }, { "code": null, "e": 3978, "s": 3873, "text": "If the element is present in the hashmap, print the triplet else insert the j’th element in the hashmap." }, { "code": null, "e": 4030, "s": 3978, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 4035, "s": 4030, "text": "Java" }, { "code": "// Java program to find triplets in a given// array whose sum is zeroimport java.util.*; class GFG { // function to print triplets with 0 sum static void findTriplets(int arr[], int n) { boolean found = false; for (int i = 0; i < n - 1; i++) { // Find all pairs with sum equals to // \"-arr[i]\" HashSet<Integer> s = new HashSet<Integer>(); for (int j = i + 1; j < n; j++) { int x = -(arr[i] + arr[j]); if (s.contains(x)) { System.out.printf(\"%d %d %d\", x, arr[i], arr[j]); found = true; } else { s.add(arr[j]); } } } if (found == false) { System.out.printf(\" No Triplet Found\"); } } // Driver code public static void main(String[] args) { int arr[] = {0, -1, 2, -3, 1}; int n = arr.length; findTriplets(arr, n); }} // This code contributed by Rajput-Ji", "e": 5137, "s": 4035, "text": null }, { "code": null, "e": 5151, "s": 5137, "text": "-1 0 1\n-3 2 1" }, { "code": null, "e": 5173, "s": 5151, "text": "Complexity Analysis: " }, { "code": null, "e": 5267, "s": 5173, "text": "Time Complexity: O(n2). Since two nested loops are required, so the time complexity is O(n2)." }, { "code": null, "e": 5354, "s": 5267, "text": "Auxiliary Space: O(n). Since a hashmap is required, so the space complexity is linear." }, { "code": null, "e": 5453, "s": 5354, "text": " Method 3: This method uses Sorting to arrive at the correct result and is solved in O(n2) time. " }, { "code": null, "e": 5649, "s": 5453, "text": "Approach: The above method requires extra space. The idea is based on method 2 of this post. For every element check that there is a pair whose sum is equal to the negative value of that element." }, { "code": null, "e": 5661, "s": 5649, "text": "Algorithm: " }, { "code": null, "e": 6258, "s": 5661, "text": "Sort the array in ascending order.Traverse the array from start to end.For every index i, create two variables l = i + 1 and r = n – 1Run a loop until l is less than r if the sum of array[i], array[l] and array[r] is equal to zero then print the triplet and break the loopIf the sum is less than zero then increment the value of l, by increasing the value of l the sum will increase as the array is sorted, so array[l+1] > array [l]If the sum is greater than zero then decrement the value of r, by increasing the value of l the sum will decrease as the array is sorted, so array[r-1] < array [r]." }, { "code": null, "e": 6293, "s": 6258, "text": "Sort the array in ascending order." }, { "code": null, "e": 6331, "s": 6293, "text": "Traverse the array from start to end." }, { "code": null, "e": 6395, "s": 6331, "text": "For every index i, create two variables l = i + 1 and r = n – 1" }, { "code": null, "e": 6534, "s": 6395, "text": "Run a loop until l is less than r if the sum of array[i], array[l] and array[r] is equal to zero then print the triplet and break the loop" }, { "code": null, "e": 6695, "s": 6534, "text": "If the sum is less than zero then increment the value of l, by increasing the value of l the sum will increase as the array is sorted, so array[l+1] > array [l]" }, { "code": null, "e": 6860, "s": 6695, "text": "If the sum is greater than zero then decrement the value of r, by increasing the value of l the sum will decrease as the array is sorted, so array[r-1] < array [r]." }, { "code": null, "e": 6912, "s": 6860, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 6917, "s": 6912, "text": "Java" }, { "code": "// Java program to find triplets in a given// array whose sum is zeroimport java.util.Arrays; import java.io.*; class GFG { // function to print triplets with 0 sumstatic void findTriplets(int arr[], int n){ boolean found = false; // sort array elements Arrays.sort(arr); for (int i=0; i<n-1; i++) { // initialize left and right int l = i + 1; int r = n - 1; int x = arr[i]; while (l < r) { if (x + arr[l] + arr[r] == 0) { // print elements if it's sum is zero System.out.print(x + \" \"); System.out.print(arr[l]+ \" \"); System.out.println(arr[r]+ \" \"); l++; r--; found = true; } // If sum of three elements is less // than zero then increment in left else if (x + arr[l] + arr[r] < 0) l++; // if sum is greater than zero than // decrement in right side else r--; } } if (found == false) System.out.println(\" No Triplet Found\");} // Driven source public static void main (String[] args) { int arr[] = {0, -1, 2, -3, 1}; int n =arr.length; findTriplets(arr, n); }//This code is contributed by Tushil.. }", "e": 8287, "s": 6917, "text": null }, { "code": null, "e": 8301, "s": 8287, "text": "-3 1 2\n-1 0 1" }, { "code": null, "e": 8323, "s": 8301, "text": "Complexity Analysis: " }, { "code": null, "e": 8417, "s": 8323, "text": "Time Complexity : O(n2). Only two nested loops are required, so the time complexity is O(n2)." }, { "code": null, "e": 8505, "s": 8417, "text": "Auxiliary Space : O(1), no extra space is required, so the time complexity is constant." }, { "code": null, "e": 8588, "s": 8505, "text": "Please refer complete article on Find all triplets with zero sum for more details!" }, { "code": null, "e": 8597, "s": 8588, "text": "Facebook" }, { "code": null, "e": 8604, "s": 8597, "text": "Google" }, { "code": null, "e": 8626, "s": 8604, "text": "two-pointer-algorithm" }, { "code": null, "e": 8633, "s": 8626, "text": "Arrays" }, { "code": null, "e": 8638, "s": 8633, "text": "Hash" }, { "code": null, "e": 8643, "s": 8638, "text": "Java" }, { "code": null, "e": 8657, "s": 8643, "text": "Java Programs" }, { "code": null, "e": 8667, "s": 8657, "text": "Searching" }, { "code": null, "e": 8675, "s": 8667, "text": "Sorting" }, { "code": null, "e": 8682, "s": 8675, "text": "Google" }, { "code": null, "e": 8691, "s": 8682, "text": "Facebook" }, { "code": null, "e": 8713, "s": 8691, "text": "two-pointer-algorithm" }, { "code": null, "e": 8720, "s": 8713, "text": "Arrays" }, { "code": null, "e": 8730, "s": 8720, "text": "Searching" }, { "code": null, "e": 8735, "s": 8730, "text": "Hash" }, { "code": null, "e": 8743, "s": 8735, "text": "Sorting" }, { "code": null, "e": 8748, "s": 8743, "text": "Java" }, { "code": null, "e": 8846, "s": 8748, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8878, "s": 8846, "text": "Introduction to Data Structures" }, { "code": null, "e": 8903, "s": 8878, "text": "Window Sliding Technique" }, { "code": null, "e": 8950, "s": 8903, "text": "Search, insert and delete in an unsorted array" }, { "code": null, "e": 9014, "s": 8950, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 9045, "s": 9014, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 9083, "s": 9045, "text": "What is Hashing | A Complete Tutorial" }, { "code": null, "e": 9119, "s": 9083, "text": "Internal Working of HashMap in Java" }, { "code": null, "e": 9150, "s": 9119, "text": "Hashing | Set 1 (Introduction)" }, { "code": null, "e": 9177, "s": 9150, "text": "Count pairs with given sum" } ]
Python – Unpacking Values in Strings
29 Aug, 2020 Given a dictionary, unpack its values into a string. Input : test_str = “First value is {} Second is {}”, test_dict = {3 : “Gfg”, 9 : “Best”}Output : First value is Gfg Second is BestExplanation : After substitution, we get Gfg and Best as values. Input : test_str = “First value is {} Second is {}”, test_dict = {3 : “G”, 9 : “f”}Output : First value is G Second is f.Explanation : After substitution, we get G and f as values. Method : Using format() + * operator + values() The combination of above functions can be used to solve this problem. In this, we use format to map required value with braces in string. The * operator is used to unpack and assign. The values are extracted using values(). Python3 # Python3 code to demonstrate working of # Unpacking Integer Keys in Strings# Using format() + * operator + values() # initializing stringtest_str = "First value is {} Second is {} Third {}" # printing original stringprint("The original string is : " + str(test_str)) # initializing dictionary test_dict = {3 : "Gfg", 4 : "is", 9 : "Best"} # using format() for mapping required values res = test_str.format(*test_dict.values()) # printing result print("String after unpacking dictionary : " + str(res)) The original string is : First value is {} Second is {} Third {} String after unpacking dictionary : First value is Gfg Second is is Third Best Python string-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Aug, 2020" }, { "code": null, "e": 81, "s": 28, "text": "Given a dictionary, unpack its values into a string." }, { "code": null, "e": 276, "s": 81, "text": "Input : test_str = “First value is {} Second is {}”, test_dict = {3 : “Gfg”, 9 : “Best”}Output : First value is Gfg Second is BestExplanation : After substitution, we get Gfg and Best as values." }, { "code": null, "e": 457, "s": 276, "text": "Input : test_str = “First value is {} Second is {}”, test_dict = {3 : “G”, 9 : “f”}Output : First value is G Second is f.Explanation : After substitution, we get G and f as values." }, { "code": null, "e": 506, "s": 457, "text": "Method : Using format() + * operator + values()" }, { "code": null, "e": 730, "s": 506, "text": "The combination of above functions can be used to solve this problem. In this, we use format to map required value with braces in string. The * operator is used to unpack and assign. The values are extracted using values()." }, { "code": null, "e": 738, "s": 730, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of # Unpacking Integer Keys in Strings# Using format() + * operator + values() # initializing stringtest_str = \"First value is {} Second is {} Third {}\" # printing original stringprint(\"The original string is : \" + str(test_str)) # initializing dictionary test_dict = {3 : \"Gfg\", 4 : \"is\", 9 : \"Best\"} # using format() for mapping required values res = test_str.format(*test_dict.values()) # printing result print(\"String after unpacking dictionary : \" + str(res)) ", "e": 1251, "s": 738, "text": null }, { "code": null, "e": 1397, "s": 1251, "text": "The original string is : First value is {} Second is {} Third {}\nString after unpacking dictionary : First value is Gfg Second is is Third Best\n\n" }, { "code": null, "e": 1420, "s": 1397, "text": "Python string-programs" }, { "code": null, "e": 1427, "s": 1420, "text": "Python" }, { "code": null, "e": 1443, "s": 1427, "text": "Python Programs" } ]
Stack and Queues in Python
09 May, 2022 Prerequisites : list and Deque in Python. Unlike C++ STL and Java Collections, Python does have specific classes/interfaces for Stack and Queue. Following are different ways to implement in Python 1) Using listStack works on the principle of “Last-in, first-out”. Also, the inbuilt functions in Python make the code short and simple. To add an item to the top of the list, i.e., to push an item, we use append() function and to pop out an element we use pop() function. These functions work quiet efficiently and fast in end operations. Let’s look at an example and try to understand the working of push() and pop() function:Example: # Python code to demonstrate Implementing # stack using liststack = ["Amar", "Akbar", "Anthony"]stack.append("Ram")stack.append("Iqbal")print(stack) # Removes the last itemprint(stack.pop()) print(stack) # Removes the last itemprint(stack.pop()) print(stack) ['Amar', 'Akbar', 'Anthony', 'Ram', 'Iqbal'] Iqbal ['Amar', 'Akbar', 'Anthony', 'Ram'] Ram ['Amar', 'Akbar', 'Anthony'] Queue works on the principle of “First-in, first-out”. Below is list implementation of queue. We use pop(0) to remove the first item from a list. # Python code to demonstrate Implementing # Queue using listqueue = ["Amar", "Akbar", "Anthony"]queue.append("Ram")queue.append("Iqbal")print(queue) # Removes the first itemprint(queue.pop(0)) print(queue) # Removes the first itemprint(queue.pop(0)) print(queue) ['Amar', 'Akbar', 'Anthony', 'Ram', 'Iqbal'] Amar ['Akbar', 'Anthony', 'Ram', 'Iqbal'] Akbar ['Anthony', 'Ram', 'Iqbal'] 2) Using DequeIn case of stack, list implementation works fine and provides both append() and pop() in O(1) time. When we use deque implementation, we get same time complexity. # Python code to demonstrate Implementing # Stack using dequefrom collections import dequequeue = deque(["Ram", "Tarun", "Asif", "John"])print(queue)queue.append("Akbar")print(queue)queue.append("Birbal")print(queue)print(queue.pop()) print(queue.pop()) print(queue) deque(['Ram', 'Tarun', 'Asif', 'John']) deque(['Ram', 'Tarun', 'Asif', 'John', 'Akbar']) deque(['Ram', 'Tarun', 'Asif', 'John', 'Akbar', 'Birbal']) Birbal Akbar deque(['Ram', 'Tarun', 'Asif', 'John']) But when it comes to queue, the above list implementation is not efficient. In queue when pop() is made from the beginning of the list which is slow. This occurs due to the properties of list, which is fast at the end operations but slow at the beginning operations, as all other elements have to be shifted one by one.So, we prefer the use of dequeue over list, which was specially designed to have fast appends and pops from both the front and back end. Let’s look at an example and try to understand queue using collections.deque: # Python code to demonstrate Implementing # Queue using dequefrom collections import dequequeue = deque(["Ram", "Tarun", "Asif", "John"])print(queue)queue.append("Akbar")print(queue)queue.append("Birbal")print(queue)print(queue.popleft()) print(queue.popleft()) print(queue) deque(['Ram', 'Tarun', 'Asif', 'John']) deque(['Ram', 'Tarun', 'Asif', 'John', 'Akbar']) deque(['Ram', 'Tarun', 'Asif', 'John', 'Akbar', 'Birbal']) Ram Tarun deque(['Asif', 'John', 'Akbar', 'Birbal']) This article is contributed by Chinmoy Lenka. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. radaboy679 Python-Data-Structures python-list Python python-list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n09 May, 2022" }, { "code": null, "e": 95, "s": 53, "text": "Prerequisites : list and Deque in Python." }, { "code": null, "e": 250, "s": 95, "text": "Unlike C++ STL and Java Collections, Python does have specific classes/interfaces for Stack and Queue. Following are different ways to implement in Python" }, { "code": null, "e": 590, "s": 250, "text": "1) Using listStack works on the principle of “Last-in, first-out”. Also, the inbuilt functions in Python make the code short and simple. To add an item to the top of the list, i.e., to push an item, we use append() function and to pop out an element we use pop() function. These functions work quiet efficiently and fast in end operations." }, { "code": null, "e": 687, "s": 590, "text": "Let’s look at an example and try to understand the working of push() and pop() function:Example:" }, { "code": "# Python code to demonstrate Implementing # stack using liststack = [\"Amar\", \"Akbar\", \"Anthony\"]stack.append(\"Ram\")stack.append(\"Iqbal\")print(stack) # Removes the last itemprint(stack.pop()) print(stack) # Removes the last itemprint(stack.pop()) print(stack)", "e": 950, "s": 687, "text": null }, { "code": null, "e": 1071, "s": 950, "text": "['Amar', 'Akbar', 'Anthony', 'Ram', 'Iqbal']\nIqbal\n['Amar', 'Akbar', 'Anthony', 'Ram']\nRam\n['Amar', 'Akbar', 'Anthony']\n" }, { "code": null, "e": 1217, "s": 1071, "text": "Queue works on the principle of “First-in, first-out”. Below is list implementation of queue. We use pop(0) to remove the first item from a list." }, { "code": "# Python code to demonstrate Implementing # Queue using listqueue = [\"Amar\", \"Akbar\", \"Anthony\"]queue.append(\"Ram\")queue.append(\"Iqbal\")print(queue) # Removes the first itemprint(queue.pop(0)) print(queue) # Removes the first itemprint(queue.pop(0)) print(queue)", "e": 1484, "s": 1217, "text": null }, { "code": null, "e": 1606, "s": 1484, "text": "['Amar', 'Akbar', 'Anthony', 'Ram', 'Iqbal']\nAmar\n['Akbar', 'Anthony', 'Ram', 'Iqbal']\nAkbar\n['Anthony', 'Ram', 'Iqbal']\n" }, { "code": null, "e": 1783, "s": 1606, "text": "2) Using DequeIn case of stack, list implementation works fine and provides both append() and pop() in O(1) time. When we use deque implementation, we get same time complexity." }, { "code": "# Python code to demonstrate Implementing # Stack using dequefrom collections import dequequeue = deque([\"Ram\", \"Tarun\", \"Asif\", \"John\"])print(queue)queue.append(\"Akbar\")print(queue)queue.append(\"Birbal\")print(queue)print(queue.pop()) print(queue.pop()) print(queue)", "e": 2082, "s": 1783, "text": null }, { "code": null, "e": 2284, "s": 2082, "text": "deque(['Ram', 'Tarun', 'Asif', 'John'])\ndeque(['Ram', 'Tarun', 'Asif', 'John', 'Akbar'])\ndeque(['Ram', 'Tarun', 'Asif', 'John', 'Akbar', 'Birbal'])\nBirbal\nAkbar\ndeque(['Ram', 'Tarun', 'Asif', 'John'])\n" }, { "code": null, "e": 2740, "s": 2284, "text": "But when it comes to queue, the above list implementation is not efficient. In queue when pop() is made from the beginning of the list which is slow. This occurs due to the properties of list, which is fast at the end operations but slow at the beginning operations, as all other elements have to be shifted one by one.So, we prefer the use of dequeue over list, which was specially designed to have fast appends and pops from both the front and back end." }, { "code": null, "e": 2818, "s": 2740, "text": "Let’s look at an example and try to understand queue using collections.deque:" }, { "code": "# Python code to demonstrate Implementing # Queue using dequefrom collections import dequequeue = deque([\"Ram\", \"Tarun\", \"Asif\", \"John\"])print(queue)queue.append(\"Akbar\")print(queue)queue.append(\"Birbal\")print(queue)print(queue.popleft()) print(queue.popleft()) print(queue)", "e": 3125, "s": 2818, "text": null }, { "code": null, "e": 3327, "s": 3125, "text": "deque(['Ram', 'Tarun', 'Asif', 'John'])\ndeque(['Ram', 'Tarun', 'Asif', 'John', 'Akbar'])\ndeque(['Ram', 'Tarun', 'Asif', 'John', 'Akbar', 'Birbal'])\nRam\nTarun\ndeque(['Asif', 'John', 'Akbar', 'Birbal'])\n" }, { "code": null, "e": 3624, "s": 3327, "text": "This article is contributed by Chinmoy Lenka. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 3749, "s": 3624, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 3760, "s": 3749, "text": "radaboy679" }, { "code": null, "e": 3783, "s": 3760, "text": "Python-Data-Structures" }, { "code": null, "e": 3795, "s": 3783, "text": "python-list" }, { "code": null, "e": 3802, "s": 3795, "text": "Python" }, { "code": null, "e": 3814, "s": 3802, "text": "python-list" } ]
Lodash _.uniqueId() Method
09 Sep, 2020 The Lodash _.uniqueId() method is used to create an unique id for some element each time. This method will work for the purpose of assigning a unique id for most use cases, but not with complex projects that require a unique id always even if the project restarts. Syntax: _.uniqueId(prefix) Parameters: This method accepts a single parameter as mentioned above and described below: prefix: The value to prefix the ID with. Return Value: This method returns the string unique ID. Example 1: Javascript // Requiring the lodash library const _ = require("lodash"); // Use of _.uniqueId() // Method without the prefixlet gfg = _.uniqueId(); // Printing the output console.log(gfg); Output: 1 Example 2: Javascript // Requiring the lodash library const _ = require("lodash"); // Use of _.uniqueId() // Method with prefixlet ans = _.uniqueId("gfg_"); // Printing the output console.log(ans); let ans1 = _.uniqueId("gfg_"); // Printing the output console.log(ans1); Output: gfg_1 gfg_2 JavaScript-Lodash JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n09 Sep, 2020" }, { "code": null, "e": 294, "s": 28, "text": "The Lodash _.uniqueId() method is used to create an unique id for some element each time. This method will work for the purpose of assigning a unique id for most use cases, but not with complex projects that require a unique id always even if the project restarts. " }, { "code": null, "e": 302, "s": 294, "text": "Syntax:" }, { "code": null, "e": 321, "s": 302, "text": "_.uniqueId(prefix)" }, { "code": null, "e": 412, "s": 321, "text": "Parameters: This method accepts a single parameter as mentioned above and described below:" }, { "code": null, "e": 453, "s": 412, "text": "prefix: The value to prefix the ID with." }, { "code": null, "e": 509, "s": 453, "text": "Return Value: This method returns the string unique ID." }, { "code": null, "e": 520, "s": 509, "text": "Example 1:" }, { "code": null, "e": 531, "s": 520, "text": "Javascript" }, { "code": "// Requiring the lodash library const _ = require(\"lodash\"); // Use of _.uniqueId() // Method without the prefixlet gfg = _.uniqueId(); // Printing the output console.log(gfg);", "e": 732, "s": 531, "text": null }, { "code": null, "e": 740, "s": 732, "text": "Output:" }, { "code": null, "e": 743, "s": 740, "text": "1\n" }, { "code": null, "e": 754, "s": 743, "text": "Example 2:" }, { "code": null, "e": 765, "s": 754, "text": "Javascript" }, { "code": "// Requiring the lodash library const _ = require(\"lodash\"); // Use of _.uniqueId() // Method with prefixlet ans = _.uniqueId(\"gfg_\"); // Printing the output console.log(ans); let ans1 = _.uniqueId(\"gfg_\"); // Printing the output console.log(ans1);", "e": 1029, "s": 765, "text": null }, { "code": null, "e": 1037, "s": 1029, "text": "Output:" }, { "code": null, "e": 1050, "s": 1037, "text": "gfg_1\ngfg_2\n" }, { "code": null, "e": 1068, "s": 1050, "text": "JavaScript-Lodash" }, { "code": null, "e": 1079, "s": 1068, "text": "JavaScript" }, { "code": null, "e": 1096, "s": 1079, "text": "Web Technologies" } ]
How to Finally Install TensorFlow 2 GPU on Windows 10 in 2021 | Towards Data Science
I think Windows users, including me, have suffered enough. You are probably stumbling on this after trying hours or even days to make this work. So, as a kindness, I will just cut to the chase and show you the steps you need to install TensorFlow GPU on Windows 10 without giving the usual blog intro. The first, very important step is to go to this link and decide which TF version you want to install. Based on this, the CUDA driver versions and other software versions change. As of writing this guide, TF 2.6.0 is the latest, and we will be installing that one. We are only interested in the TF version, cuDNN, and CUDA versions. We keep this tab open and move on to the next step. Next, we install Microsoft Visual Studio. Note that this one is different than Visual Studio Code, which is a lightweight IDE so many people love. Go to this link and press download: Run the downloaded executable and it will take a minute to download the requirements. Then, it will ask you to choose what workloads to install. We don’t want any, so just click install without workloads and click continue. After the installation is done, it will ask you to sign in but you don’t have to. NVIDIA CUDA toolkit contains the drivers for your NVIDIA GPU. Depending on your Windows, they may or may not be already installed. If installed, we should check their version and see if they are compatible with the TensorFlow version we want to install. Go to your Settings on Windows and choose “Apps & Features”. Then, search for NVIDIA: We want to install TF 2.6.0 which requires NVIDIA CUDA Toolkit version 11.2 (see the first link to double-check). If your drivers are any other version, delete all the ones that have “NVIDIA CUDA” in their title (leave the others). Then, go to Local Disk (C:) > Program Files > NVIDIA GPU Computing Toolkit > CUDA. There, you will see a folder with the CUDA version as a name. Delete that folder. If you search for NVIDIA and no CUDA toolkit is found, go to this page. Here is what it looks like: Here, we see three 11.2 versions, which are what we need (we got the version from the first TF version link I provided). Click on any of them and choose Windows 10, and download the network installer: Follow the on-screen prompts and install the drivers with default parameters. Then, restart your computer and come back. For TensorFlow 2.6.0, cuDNN 8.1 is required. Go to this page and press download: It will ask you for an NVIDIA Developer account: If you don’t have an account already, click “Join now” and enter your email. Fill up the form — the standard stuff. Then, go back to the cuDNN download page: At the top, it will ask you to fill out a survey. Fill it out and you will be presented with the above page. Click on the first one since it is the one compatible with CUDA Toolkit v. 11.*. There, you will see a Windows version, which you should download. Extract the downloaded ZIP folder: Open the cuda folder and copy the three folders at the top (bin, include, lib). Then, go to C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.2 and paste them there. Explorer tells you that these folders already exist, which you should press Replace the files in the destination. That’s it, we are done with the software requirements! Restart your computer once again. Now, it is time to add a few folders to the environment variables. In the last destination, C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.2, there is a bin and folder: Open it and copy the file path. Then, press the “Start” (Windows) button and type “Environment variables”: Open it and go to “Environment variables”. This will open this pop-up window: Choose the “Path” from the top and press edit. Press “New” and paste the copied link there. Then, go back to the GPU toolkit folder and open the libnvvp folder: Copy its path and paste it to Environment variables just like you did with the bin folder. Then, close all pop-ups, saving the changes. Finally, we are ready to install TensorFlow. Create a virtual environment with your preferred package manager. I use conda, so I create a conda environment named tf with Python version 3.8. conda create -n tf python==3.8conda activate tfpip install --upgrade tensorflowpip install jupyterlab ipykernel It is important that both TensorFlow and JupyterLab are installed with either pip or conda. You will get a ModelNotFoundError in JupyterLab if they are installed from different channels. Next, we should add the conda environment to Jupyterlab so that it is listed as a valid kernel when we launch a session: ipython kernel install --user --name=<name of the kernel, `tf` for our case> If you launch JupyterLab, you should be able to see the environment as a kernel. Create a new notebook and run this snippet to check if TF can detect your GPU: import tensorflow as tffrom tensorflow.python.client import device_libprint("Num GPUs Available: ", len(tf.config.list_physical_devices('GPU')))device_lib.list_local_devices() As the output says, I have a single GPU and at the end, it shows its name. If you have a similar output, then my job here is done! Instructions were taken from this live-saver YouTube video.
[ { "code": null, "e": 474, "s": 172, "text": "I think Windows users, including me, have suffered enough. You are probably stumbling on this after trying hours or even days to make this work. So, as a kindness, I will just cut to the chase and show you the steps you need to install TensorFlow GPU on Windows 10 without giving the usual blog intro." }, { "code": null, "e": 652, "s": 474, "text": "The first, very important step is to go to this link and decide which TF version you want to install. Based on this, the CUDA driver versions and other software versions change." }, { "code": null, "e": 738, "s": 652, "text": "As of writing this guide, TF 2.6.0 is the latest, and we will be installing that one." }, { "code": null, "e": 858, "s": 738, "text": "We are only interested in the TF version, cuDNN, and CUDA versions. We keep this tab open and move on to the next step." }, { "code": null, "e": 1005, "s": 858, "text": "Next, we install Microsoft Visual Studio. Note that this one is different than Visual Studio Code, which is a lightweight IDE so many people love." }, { "code": null, "e": 1041, "s": 1005, "text": "Go to this link and press download:" }, { "code": null, "e": 1347, "s": 1041, "text": "Run the downloaded executable and it will take a minute to download the requirements. Then, it will ask you to choose what workloads to install. We don’t want any, so just click install without workloads and click continue. After the installation is done, it will ask you to sign in but you don’t have to." }, { "code": null, "e": 1601, "s": 1347, "text": "NVIDIA CUDA toolkit contains the drivers for your NVIDIA GPU. Depending on your Windows, they may or may not be already installed. If installed, we should check their version and see if they are compatible with the TensorFlow version we want to install." }, { "code": null, "e": 1687, "s": 1601, "text": "Go to your Settings on Windows and choose “Apps & Features”. Then, search for NVIDIA:" }, { "code": null, "e": 2084, "s": 1687, "text": "We want to install TF 2.6.0 which requires NVIDIA CUDA Toolkit version 11.2 (see the first link to double-check). If your drivers are any other version, delete all the ones that have “NVIDIA CUDA” in their title (leave the others). Then, go to Local Disk (C:) > Program Files > NVIDIA GPU Computing Toolkit > CUDA. There, you will see a folder with the CUDA version as a name. Delete that folder." }, { "code": null, "e": 2184, "s": 2084, "text": "If you search for NVIDIA and no CUDA toolkit is found, go to this page. Here is what it looks like:" }, { "code": null, "e": 2385, "s": 2184, "text": "Here, we see three 11.2 versions, which are what we need (we got the version from the first TF version link I provided). Click on any of them and choose Windows 10, and download the network installer:" }, { "code": null, "e": 2506, "s": 2385, "text": "Follow the on-screen prompts and install the drivers with default parameters. Then, restart your computer and come back." }, { "code": null, "e": 2587, "s": 2506, "text": "For TensorFlow 2.6.0, cuDNN 8.1 is required. Go to this page and press download:" }, { "code": null, "e": 2636, "s": 2587, "text": "It will ask you for an NVIDIA Developer account:" }, { "code": null, "e": 2794, "s": 2636, "text": "If you don’t have an account already, click “Join now” and enter your email. Fill up the form — the standard stuff. Then, go back to the cuDNN download page:" }, { "code": null, "e": 3050, "s": 2794, "text": "At the top, it will ask you to fill out a survey. Fill it out and you will be presented with the above page. Click on the first one since it is the one compatible with CUDA Toolkit v. 11.*. There, you will see a Windows version, which you should download." }, { "code": null, "e": 3085, "s": 3050, "text": "Extract the downloaded ZIP folder:" }, { "code": null, "e": 3256, "s": 3085, "text": "Open the cuda folder and copy the three folders at the top (bin, include, lib). Then, go to C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v11.2 and paste them there." }, { "code": null, "e": 3459, "s": 3256, "text": "Explorer tells you that these folders already exist, which you should press Replace the files in the destination. That’s it, we are done with the software requirements! Restart your computer once again." }, { "code": null, "e": 3636, "s": 3459, "text": "Now, it is time to add a few folders to the environment variables. In the last destination, C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v11.2, there is a bin and folder:" }, { "code": null, "e": 3743, "s": 3636, "text": "Open it and copy the file path. Then, press the “Start” (Windows) button and type “Environment variables”:" }, { "code": null, "e": 3821, "s": 3743, "text": "Open it and go to “Environment variables”. This will open this pop-up window:" }, { "code": null, "e": 3913, "s": 3821, "text": "Choose the “Path” from the top and press edit. Press “New” and paste the copied link there." }, { "code": null, "e": 3982, "s": 3913, "text": "Then, go back to the GPU toolkit folder and open the libnvvp folder:" }, { "code": null, "e": 4118, "s": 3982, "text": "Copy its path and paste it to Environment variables just like you did with the bin folder. Then, close all pop-ups, saving the changes." }, { "code": null, "e": 4308, "s": 4118, "text": "Finally, we are ready to install TensorFlow. Create a virtual environment with your preferred package manager. I use conda, so I create a conda environment named tf with Python version 3.8." }, { "code": null, "e": 4420, "s": 4308, "text": "conda create -n tf python==3.8conda activate tfpip install --upgrade tensorflowpip install jupyterlab ipykernel" }, { "code": null, "e": 4607, "s": 4420, "text": "It is important that both TensorFlow and JupyterLab are installed with either pip or conda. You will get a ModelNotFoundError in JupyterLab if they are installed from different channels." }, { "code": null, "e": 4728, "s": 4607, "text": "Next, we should add the conda environment to Jupyterlab so that it is listed as a valid kernel when we launch a session:" }, { "code": null, "e": 4805, "s": 4728, "text": "ipython kernel install --user --name=<name of the kernel, `tf` for our case>" }, { "code": null, "e": 4965, "s": 4805, "text": "If you launch JupyterLab, you should be able to see the environment as a kernel. Create a new notebook and run this snippet to check if TF can detect your GPU:" }, { "code": null, "e": 5141, "s": 4965, "text": "import tensorflow as tffrom tensorflow.python.client import device_libprint(\"Num GPUs Available: \", len(tf.config.list_physical_devices('GPU')))device_lib.list_local_devices()" }, { "code": null, "e": 5272, "s": 5141, "text": "As the output says, I have a single GPU and at the end, it shows its name. If you have a similar output, then my job here is done!" } ]
JavaScript Date setDate() Method
Javascript date setDate() method sets the day of the month for a specified date according to local time. Its syntax is as follows − Date.setDate( dayValue ) dayValue − An integer from 1 to 31, representing the day of the month. Try the following example. <html> <head> <title>JavaScript setDate Method</title> </head> <body> <script type = "text/javascript"> var dt = new Date( "Aug 28, 2008 23:30:00" ); dt.setDate( 24 ); document.write( dt ); </script> </body> </html> Sun Aug 24 2008 23:30:00 GMT+0530 (India Standard Time) 25 Lectures 2.5 hours Anadi Sharma 74 Lectures 10 hours Lets Kode It 72 Lectures 4.5 hours Frahaan Hussain 70 Lectures 4.5 hours Frahaan Hussain 46 Lectures 6 hours Eduonix Learning Solutions 88 Lectures 14 hours Eduonix Learning Solutions Print Add Notes Bookmark this page
[ { "code": null, "e": 2571, "s": 2466, "text": "Javascript date setDate() method sets the day of the month for a specified date according to local time." }, { "code": null, "e": 2598, "s": 2571, "text": "Its syntax is as follows −" }, { "code": null, "e": 2624, "s": 2598, "text": "Date.setDate( dayValue )\n" }, { "code": null, "e": 2696, "s": 2624, "text": "dayValue − An integer from 1 to 31, representing the day of the month." }, { "code": null, "e": 2723, "s": 2696, "text": "Try the following example." }, { "code": null, "e": 3006, "s": 2723, "text": "<html>\n <head>\n <title>JavaScript setDate Method</title>\n </head>\n \n <body> \n <script type = \"text/javascript\">\n var dt = new Date( \"Aug 28, 2008 23:30:00\" );\n dt.setDate( 24 );\n document.write( dt );\n </script> \n </body>\n</html>" }, { "code": null, "e": 3064, "s": 3006, "text": "Sun Aug 24 2008 23:30:00 GMT+0530 (India Standard Time) \n" }, { "code": null, "e": 3099, "s": 3064, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3113, "s": 3099, "text": " Anadi Sharma" }, { "code": null, "e": 3147, "s": 3113, "text": "\n 74 Lectures \n 10 hours \n" }, { "code": null, "e": 3161, "s": 3147, "text": " Lets Kode It" }, { "code": null, "e": 3196, "s": 3161, "text": "\n 72 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3213, "s": 3196, "text": " Frahaan Hussain" }, { "code": null, "e": 3248, "s": 3213, "text": "\n 70 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3265, "s": 3248, "text": " Frahaan Hussain" }, { "code": null, "e": 3298, "s": 3265, "text": "\n 46 Lectures \n 6 hours \n" }, { "code": null, "e": 3326, "s": 3298, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3360, "s": 3326, "text": "\n 88 Lectures \n 14 hours \n" }, { "code": null, "e": 3388, "s": 3360, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3395, "s": 3388, "text": " Print" }, { "code": null, "e": 3406, "s": 3395, "text": " Add Notes" } ]
Go-Back-N ARQ
Go-Back-N Automatic Repeat reQuest (Go-Back-N ARQ), is a data link layer protocol that uses a sliding window method for reliable and sequential delivery of data frames. It is a case of sliding window protocol having to send window size of N and receiving window size of 1. Go – Back – N ARQ uses the concept of protocol pipelining, i.e. sending multiple frames before receiving the acknowledgment for the first frame. The frames are sequentially numbered and a finite number of frames. The maximum number of frames that can be sent depends upon the size of the sending window. If the acknowledgment of a frame is not received within an agreed upon time period, all frames starting from that frame are retransmitted. The size of the sending window determines the sequence number of the outbound frames. If the sequence number of the frames is an n-bit field, then the range of sequence numbers that can be assigned is 0 to 2n−1. Consequently, the size of the sending window is 2n−1. Thus in order to accommodate a sending window size of 2n−1, an n-bit sequence number is chosen. The sequence numbers are numbered as modulo-n. For example, if the sending window size is 4, then the sequence numbers will be 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, and so on. The number of bits in the sequence number is 2 to generate the binary sequence 00, 01, 10, 11. The size of the receiving window is 1. begin frame s; //s denotes frame to be sent frame t; //t is temporary frame S_window = power(2,m) – 1; //Assign maximum window size SeqFirst = 0; // Sequence number of first frame in window SeqN = 0; // Sequence number of Nth frame window while (true) //check repeatedly do Wait_For_Event(); //wait for availability of packet if ( Event(Request_For_Transfer)) then //check if window is full if (SeqN–SeqFirst >= S_window) then doNothing(); end if; Get_Data_From_Network_Layer(); s = Make_Frame(); s.seq = SeqN; Store_Copy_Frame(s); Send_Frame(s); Start_Timer(s); SeqN = SeqN + 1; end if; if ( Event(Frame_Arrival) then r = Receive_Acknowledgement(); if ( AckNo > SeqFirst && AckNo < SeqN ) then while ( SeqFirst <= AckNo ) Remove_copy_frame(s.seq(SeqFirst)); SeqFirst = SeqFirst + 1; end while Stop_Timer(s); end if end if // Resend all frames if acknowledgement havn’t been received if ( Event(Time_Out)) then TempSeq = SeqFirst; while ( TempSeq < SeqN ) t = Retrieve_Copy_Frame(s.seq(SeqFirst)); Send_Frame(t); Start_Timer(t); TempSeq = TempSeq + 1; end while end if end Begin frame f; RSeqNo = 0; // Initialise sequence number of expected frame while (true) //check repeatedly do Wait_For_Event(); //wait for arrival of frame if ( Event(Frame_Arrival) then Receive_Frame_From_Physical_Layer(); if ( Corrupted ( f.SeqNo ) doNothing(); else if ( f.SeqNo = RSeqNo ) then Extract_Data(); Deliver_Data_To_Network_Layer(); RSeqNo = RSeqNo + 1; Send_ACK(RSeqNo); end if end if end while end
[ { "code": null, "e": 1335, "s": 1062, "text": "Go-Back-N Automatic Repeat reQuest (Go-Back-N ARQ), is a data link layer protocol that uses a sliding window method for reliable and sequential delivery of data frames. It is a case of sliding window protocol having to send window size of N and receiving window size of 1." }, { "code": null, "e": 1778, "s": 1335, "text": "Go – Back – N ARQ uses the concept of protocol pipelining, i.e. sending multiple frames before receiving the acknowledgment for the first frame. The frames are sequentially numbered and a finite number of frames. The maximum number of frames that can be sent depends upon the size of the sending window. If the acknowledgment of a frame is not received within an agreed upon time period, all frames starting from that frame are retransmitted." }, { "code": null, "e": 2140, "s": 1778, "text": "The size of the sending window determines the sequence number of the outbound frames. If the sequence number of the frames is an n-bit field, then the range of sequence numbers that can be assigned is 0 to 2n−1. Consequently, the size of the sending window is 2n−1. Thus in order to accommodate a sending window size of 2n−1, an n-bit sequence number is chosen." }, { "code": null, "e": 2403, "s": 2140, "text": "The sequence numbers are numbered as modulo-n. For example, if the sending window size is 4, then the sequence numbers will be 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, and so on. The number of bits in the sequence number is 2 to generate the binary sequence 00, 01, 10, 11." }, { "code": null, "e": 2442, "s": 2403, "text": "The size of the receiving window is 1." }, { "code": null, "e": 3812, "s": 2442, "text": "begin\n frame s; //s denotes frame to be sent\n frame t; //t is temporary frame\n S_window = power(2,m) – 1; //Assign maximum window size\n SeqFirst = 0; // Sequence number of first frame in window\n SeqN = 0; // Sequence number of Nth frame window\n while (true) //check repeatedly\n do\n Wait_For_Event(); //wait for availability of packet\n if ( Event(Request_For_Transfer)) then\n //check if window is full\n if (SeqN–SeqFirst >= S_window) then\n doNothing();\n end if;\n Get_Data_From_Network_Layer();\n s = Make_Frame();\n s.seq = SeqN;\n Store_Copy_Frame(s);\n Send_Frame(s);\n Start_Timer(s);\n SeqN = SeqN + 1;\n end if;\n if ( Event(Frame_Arrival) then\n r = Receive_Acknowledgement();\n if ( AckNo > SeqFirst && AckNo < SeqN ) then\n while ( SeqFirst <= AckNo )\n Remove_copy_frame(s.seq(SeqFirst));\n SeqFirst = SeqFirst + 1;\n end while\n Stop_Timer(s);\n end if\n end if\n // Resend all frames if acknowledgement havn’t been received\n if ( Event(Time_Out)) then\n TempSeq = SeqFirst;\n while ( TempSeq < SeqN )\n t = Retrieve_Copy_Frame(s.seq(SeqFirst));\n Send_Frame(t);\n Start_Timer(t);\n TempSeq = TempSeq + 1;\n end while\n end if\nend" }, { "code": null, "e": 4355, "s": 3812, "text": "Begin\n frame f;\n RSeqNo = 0; // Initialise sequence number of expected frame\n while (true) //check repeatedly\n do\n Wait_For_Event(); //wait for arrival of frame\n if ( Event(Frame_Arrival) then\n Receive_Frame_From_Physical_Layer();\n if ( Corrupted ( f.SeqNo )\n doNothing();\n else if ( f.SeqNo = RSeqNo ) then\n Extract_Data();\n Deliver_Data_To_Network_Layer();\n RSeqNo = RSeqNo + 1;\n Send_ACK(RSeqNo);\n end if\n end if\n end while\nend" } ]
Choosing the right Encoding method-Label vs OneHot Encoder | by Rahil Shaikh | Towards Data Science
In ML models we are often required to convert the categorical i.e text features to its numeric representation. The two most common ways to do this is to use Label Encoder or OneHot Encoder. However, most of the ML newbies are not familiar with the impact of the choice of encoding has on their model, the accuracy of the model may shift by large numbers by using the right encoding at the right scenario. Understanding Label and OneHot Encoding.Practical Example with Python on the impact of using Label and One hot encoding on prediction accuracy. Understanding Label and OneHot Encoding. Practical Example with Python on the impact of using Label and One hot encoding on prediction accuracy. Let us understand the working of Label and One hot encoder and further, we will see how to use these encoders in python and see their impact on predictions Label Encoding in Python can be achieved using Sklearn Library. Sklearn provides a very efficient tool for encoding the levels of categorical features into numeric values. LabelEncoder encode labels with a value between 0 and n_classes-1 where n is the number of distinct labels. If a label repeats it assigns the same value to as assigned earlier. Consider below example: If we have to pass this data to the model we need to encode the Country column to its numeric representation by using Label Encoder. After applying Label Encoder we will get a result as seen below That’s all label encoding is about. But depending on the data, label encoding introduces a new problem. For example, we have encoded a set of country names into numerical data. This is actually categorical data and there is no relation, of any kind, between the rows. The problem here is since there are different numbers in the same column, the model will misunderstand the data to be in some kind of order, 0 < 1 <2. The model may derive a correlation like as the country number increases the population increases but this clearly may not be the scenario in some other data or the prediction set. To overcome this problem, we use One Hot Encoder. Now, as we already discussed, depending on the data we have, we might run into situations where, after label encoding, we might confuse our model into thinking that a column has data with some kind of order or hierarchy when we clearly don’t have it. To avoid this, we ‘OneHotEncode’ that column. What one hot encoding does is, it takes a column which has categorical data, which has been label encoded and then splits the column into multiple columns. The numbers are replaced by 1s and 0s, depending on which column has what value. In our example, we’ll get four new columns, one for each country — Japan, U.S, India, and China. For rows which have the first column value as Japan, the ‘Japan’ column will have a ‘1’ and the other three columns will have ‘0’s. Similarly, for rows which have the first column value as the U.S, the ‘U.s’ column will have a ‘1’ and the other three columns will have ‘0’s and so on. We will be using Medical Cost Personal Datasets to predict the automobile medical charges based on various features you can download the dataset from here. The data used for this blog is just a sample data, but the difference in the prediction results is clearly seen by evaluating the prediction results by the root mean square error, closer the rmse to 0 better the model predictions are. We will run the xgboost regression algorithm model (you can use any regression algorithm of your choice) and predict the price using Label encoder and then by using One Hot encoder and compare the results. I have taken out last 37 records from the insurance.csv file and made a new file insuranceTest.csv to predict the charge on unseen data. Code Snippet: import pandas as pdimport numpy as npimport xgboostfrom sklearn.model_selection import train_test_splitfrom sklearn.preprocessing import LabelEncoderfrom math import sqrtfrom sklearn.metrics import mean_squared_errordata = pd.read_csv('D://Blogs//insurance.csv')testdata = pd.read_csv('D://Blogs//insuranceTest.csv')mergedata = data.append(testdata)testcount = len(testdata)count = len(mergedata)-testcountX_cat = mergedata.copy()X_cat = mergedata.select_dtypes(include=['object'])X_enc = X_cat.copy()#ONEHOT ENCODING BLOCK#X_enc = pd.get_dummies(X_enc, columns=['sex','region','smoker'])#mergedata = mergedata.drop(['sex','region','smoker'],axis=1)#END ENCODING BLOCK# =============================================================================# #LABEL ENCODING BLOCK# X_enc = X_enc.apply(LabelEncoder().fit_transform) #mergedata = mergedata.drop(X_cat.columns, axis=1)# #END LABEL ENCODING BLOCK# # =============================================================================FinalData = pd.concat([mergedata,X_enc], axis=1)train = FinalData[:count]test = FinalData[count:]trainy = train['charges'].astype('int')trainx = train.drop(['charges'], axis=1)test = test.drop(['charges'], axis=1)X_train,X_test, y_train,y_test = train_test_split(trainx, trainy, test_size=0.3)clf = xgboost.XGBRegressor()clf.fit(X_train,y_train)y_testpred= clf.predict(X_test)y_pred = clf.predict(test)dftestpred = pd.DataFrame(y_testpred)dfpred = pd.DataFrame(y_pred)rms = sqrt(mean_squared_error(y_test, y_testpred))print("RMSE:", rms) RMSE output: RMSE: 4931.632574106283 Now let's uncomment the One Hot encoder block from our snippet and comment Label Encoder block see the RMSE import pandas as pdimport numpy as npimport xgboostfrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import accuracy_score, confusion_matrixfrom sklearn.preprocessing import LabelEncoderfrom math import sqrtfrom sklearn.metrics import mean_squared_errordata = pd.read_csv('D://Blogs//insurance.csv')testdata = pd.read_csv('D://Blogs//insuranceTest.csv')mergedata = data.append(testdata)testcount = len(testdata)count = len(mergedata)-testcountX_cat = mergedata.copy()X_cat = mergedata.select_dtypes(include=['object'])X_enc = X_cat.copy()#ONEHOT ENCODING BLOCKX_enc = pd.get_dummies(X_enc, columns=['sex','region','smoker'])mergedata = mergedata.drop(['sex','region','smoker'],axis=1)#END ENCODING BLOCK# =============================================================================# #LABEL ENCODING BLOCK# #X_enc = X_enc.apply(LabelEncoder().fit_transform) ##mergedata = mergedata.drop(X_cat.columns, axis=1)# #END LABEL ENCODING BLOCK# # =============================================================================FinalData = pd.concat([mergedata,X_enc], axis=1)train = FinalData[:count]test = FinalData[count:]trainy = train['charges'].astype('int')trainx = train.drop(['charges'], axis=1)test = test.drop(['charges'], axis=1)X_train,X_test, y_train,y_test = train_test_split(trainx, trainy, test_size=0.3)clf = xgboost.XGBRegressor()clf.fit(X_train,y_train)y_testpred= clf.predict(X_test)y_pred = clf.predict(test)dftestpred = pd.DataFrame(y_testpred)dfpred = pd.DataFrame(y_pred)rms = sqrt(mean_squared_error(y_test, y_testpred))print("RMSE:", rms) RMSE output: RMSE: 4793.667005276121 RMSE of One Hot Encoder is less than Label Encoder which means using One Hot encoder has given better accuracy as we know closer the RMSE to 0 better the accuracy, again don't be worried for such a large RMSE as I said this is just a sample data which has helped us to understand the impact of Label and OneHot encoder on our model. If you found this article useful give it a clap and share it with your friends.
[ { "code": null, "e": 576, "s": 171, "text": "In ML models we are often required to convert the categorical i.e text features to its numeric representation. The two most common ways to do this is to use Label Encoder or OneHot Encoder. However, most of the ML newbies are not familiar with the impact of the choice of encoding has on their model, the accuracy of the model may shift by large numbers by using the right encoding at the right scenario." }, { "code": null, "e": 720, "s": 576, "text": "Understanding Label and OneHot Encoding.Practical Example with Python on the impact of using Label and One hot encoding on prediction accuracy." }, { "code": null, "e": 761, "s": 720, "text": "Understanding Label and OneHot Encoding." }, { "code": null, "e": 865, "s": 761, "text": "Practical Example with Python on the impact of using Label and One hot encoding on prediction accuracy." }, { "code": null, "e": 1021, "s": 865, "text": "Let us understand the working of Label and One hot encoder and further, we will see how to use these encoders in python and see their impact on predictions" }, { "code": null, "e": 1370, "s": 1021, "text": "Label Encoding in Python can be achieved using Sklearn Library. Sklearn provides a very efficient tool for encoding the levels of categorical features into numeric values. LabelEncoder encode labels with a value between 0 and n_classes-1 where n is the number of distinct labels. If a label repeats it assigns the same value to as assigned earlier." }, { "code": null, "e": 1394, "s": 1370, "text": "Consider below example:" }, { "code": null, "e": 1591, "s": 1394, "text": "If we have to pass this data to the model we need to encode the Country column to its numeric representation by using Label Encoder. After applying Label Encoder we will get a result as seen below" }, { "code": null, "e": 1859, "s": 1591, "text": "That’s all label encoding is about. But depending on the data, label encoding introduces a new problem. For example, we have encoded a set of country names into numerical data. This is actually categorical data and there is no relation, of any kind, between the rows." }, { "code": null, "e": 2010, "s": 1859, "text": "The problem here is since there are different numbers in the same column, the model will misunderstand the data to be in some kind of order, 0 < 1 <2." }, { "code": null, "e": 2240, "s": 2010, "text": "The model may derive a correlation like as the country number increases the population increases but this clearly may not be the scenario in some other data or the prediction set. To overcome this problem, we use One Hot Encoder." }, { "code": null, "e": 2537, "s": 2240, "text": "Now, as we already discussed, depending on the data we have, we might run into situations where, after label encoding, we might confuse our model into thinking that a column has data with some kind of order or hierarchy when we clearly don’t have it. To avoid this, we ‘OneHotEncode’ that column." }, { "code": null, "e": 2871, "s": 2537, "text": "What one hot encoding does is, it takes a column which has categorical data, which has been label encoded and then splits the column into multiple columns. The numbers are replaced by 1s and 0s, depending on which column has what value. In our example, we’ll get four new columns, one for each country — Japan, U.S, India, and China." }, { "code": null, "e": 3156, "s": 2871, "text": "For rows which have the first column value as Japan, the ‘Japan’ column will have a ‘1’ and the other three columns will have ‘0’s. Similarly, for rows which have the first column value as the U.S, the ‘U.s’ column will have a ‘1’ and the other three columns will have ‘0’s and so on." }, { "code": null, "e": 3547, "s": 3156, "text": "We will be using Medical Cost Personal Datasets to predict the automobile medical charges based on various features you can download the dataset from here. The data used for this blog is just a sample data, but the difference in the prediction results is clearly seen by evaluating the prediction results by the root mean square error, closer the rmse to 0 better the model predictions are." }, { "code": null, "e": 3753, "s": 3547, "text": "We will run the xgboost regression algorithm model (you can use any regression algorithm of your choice) and predict the price using Label encoder and then by using One Hot encoder and compare the results." }, { "code": null, "e": 3890, "s": 3753, "text": "I have taken out last 37 records from the insurance.csv file and made a new file insuranceTest.csv to predict the charge on unseen data." }, { "code": null, "e": 3904, "s": 3890, "text": "Code Snippet:" }, { "code": null, "e": 5422, "s": 3904, "text": "import pandas as pdimport numpy as npimport xgboostfrom sklearn.model_selection import train_test_splitfrom sklearn.preprocessing import LabelEncoderfrom math import sqrtfrom sklearn.metrics import mean_squared_errordata = pd.read_csv('D://Blogs//insurance.csv')testdata = pd.read_csv('D://Blogs//insuranceTest.csv')mergedata = data.append(testdata)testcount = len(testdata)count = len(mergedata)-testcountX_cat = mergedata.copy()X_cat = mergedata.select_dtypes(include=['object'])X_enc = X_cat.copy()#ONEHOT ENCODING BLOCK#X_enc = pd.get_dummies(X_enc, columns=['sex','region','smoker'])#mergedata = mergedata.drop(['sex','region','smoker'],axis=1)#END ENCODING BLOCK# =============================================================================# #LABEL ENCODING BLOCK# X_enc = X_enc.apply(LabelEncoder().fit_transform) #mergedata = mergedata.drop(X_cat.columns, axis=1)# #END LABEL ENCODING BLOCK# # =============================================================================FinalData = pd.concat([mergedata,X_enc], axis=1)train = FinalData[:count]test = FinalData[count:]trainy = train['charges'].astype('int')trainx = train.drop(['charges'], axis=1)test = test.drop(['charges'], axis=1)X_train,X_test, y_train,y_test = train_test_split(trainx, trainy, test_size=0.3)clf = xgboost.XGBRegressor()clf.fit(X_train,y_train)y_testpred= clf.predict(X_test)y_pred = clf.predict(test)dftestpred = pd.DataFrame(y_testpred)dfpred = pd.DataFrame(y_pred)rms = sqrt(mean_squared_error(y_test, y_testpred))print(\"RMSE:\", rms)" }, { "code": null, "e": 5459, "s": 5422, "text": "RMSE output: RMSE: 4931.632574106283" }, { "code": null, "e": 5567, "s": 5459, "text": "Now let's uncomment the One Hot encoder block from our snippet and comment Label Encoder block see the RMSE" }, { "code": null, "e": 7145, "s": 5567, "text": "import pandas as pdimport numpy as npimport xgboostfrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import accuracy_score, confusion_matrixfrom sklearn.preprocessing import LabelEncoderfrom math import sqrtfrom sklearn.metrics import mean_squared_errordata = pd.read_csv('D://Blogs//insurance.csv')testdata = pd.read_csv('D://Blogs//insuranceTest.csv')mergedata = data.append(testdata)testcount = len(testdata)count = len(mergedata)-testcountX_cat = mergedata.copy()X_cat = mergedata.select_dtypes(include=['object'])X_enc = X_cat.copy()#ONEHOT ENCODING BLOCKX_enc = pd.get_dummies(X_enc, columns=['sex','region','smoker'])mergedata = mergedata.drop(['sex','region','smoker'],axis=1)#END ENCODING BLOCK# =============================================================================# #LABEL ENCODING BLOCK# #X_enc = X_enc.apply(LabelEncoder().fit_transform) ##mergedata = mergedata.drop(X_cat.columns, axis=1)# #END LABEL ENCODING BLOCK# # =============================================================================FinalData = pd.concat([mergedata,X_enc], axis=1)train = FinalData[:count]test = FinalData[count:]trainy = train['charges'].astype('int')trainx = train.drop(['charges'], axis=1)test = test.drop(['charges'], axis=1)X_train,X_test, y_train,y_test = train_test_split(trainx, trainy, test_size=0.3)clf = xgboost.XGBRegressor()clf.fit(X_train,y_train)y_testpred= clf.predict(X_test)y_pred = clf.predict(test)dftestpred = pd.DataFrame(y_testpred)dfpred = pd.DataFrame(y_pred)rms = sqrt(mean_squared_error(y_test, y_testpred))print(\"RMSE:\", rms)" }, { "code": null, "e": 7182, "s": 7145, "text": "RMSE output: RMSE: 4793.667005276121" }, { "code": null, "e": 7515, "s": 7182, "text": "RMSE of One Hot Encoder is less than Label Encoder which means using One Hot encoder has given better accuracy as we know closer the RMSE to 0 better the accuracy, again don't be worried for such a large RMSE as I said this is just a sample data which has helped us to understand the impact of Label and OneHot encoder on our model." } ]
Comparator function of qsort() in C
In C, we get the qsort() function. This is used to sort some array using quicksort technique. In this function we have to pass the comparator function. This comparator function takes two arguments. Then compares them and get the relative order between them. These two arguments are pointers, and type casted to const void*. The syntax is like below − int comparator(const void* p1, const void* p2); The return values are of three types − Less than 0. The element pointed by p1 will go before the second one. Equal to 0. Two values are same. Greater than 0. The element pointed by p1 will go after the second one #include<stdio.h> #include<stdlib.h> #include<string.h> typedef struct { char title[50]; int pages; float price; } book; int compareBook(book b1, book b2){ if(b1.price < b2.price){ return 0; } return 1; } main() { int i; book book_arr[5]; strcpy(book_arr[0].title, "C Programming"); book_arr[0].pages = 260; book_arr[0].price = 450; strcpy(book_arr[1].title, "DBMS Guide"); book_arr[1].pages = 850; book_arr[1].price = 775; strcpy(book_arr[2].title, "Learn C++"); book_arr[2].pages = 350; book_arr[2].price = 520; strcpy(book_arr[3].title, "Data Structures"); book_arr[3].pages = 380; book_arr[3].price = 430; strcpy(book_arr[4].title, "Learn Python"); book_arr[4].pages = 500; book_arr[4].price = 300; qsort((void*)book_arr, 5, sizeof(book_arr[0]), compareBook); for(i = 0; i<5; i++) { printf("%s\t\t%d\t\t%f\n",book_arr[i].title, book_arr[i].pages, book_arr[i].price); } } Learn Python 500 300.000000 Data Structures 380 430.000000 C Programming 260 450.000000 Learn C++ 350 520.000000 DBMS Guide 850 775.000000
[ { "code": null, "e": 1413, "s": 1062, "text": "In C, we get the qsort() function. This is used to sort some array using quicksort technique. In this function we have to pass the comparator function. This comparator function takes two arguments. Then compares them and get the relative order between them. These two arguments are pointers, and type casted to const void*. The syntax is like below −" }, { "code": null, "e": 1461, "s": 1413, "text": "int comparator(const void* p1, const void* p2);" }, { "code": null, "e": 1500, "s": 1461, "text": "The return values are of three types −" }, { "code": null, "e": 1570, "s": 1500, "text": "Less than 0. The element pointed by p1 will go before the second one." }, { "code": null, "e": 1603, "s": 1570, "text": "Equal to 0. Two values are same." }, { "code": null, "e": 1674, "s": 1603, "text": "Greater than 0. The element pointed by p1 will go after the second one" }, { "code": null, "e": 2639, "s": 1674, "text": "#include<stdio.h>\n#include<stdlib.h>\n#include<string.h>\ntypedef struct {\n char title[50];\n int pages;\n float price;\n}\nbook;\nint compareBook(book b1, book b2){\n if(b1.price < b2.price){\n return 0;\n }\n return 1;\n}\nmain() {\n int i;\n book book_arr[5];\n strcpy(book_arr[0].title, \"C Programming\");\n book_arr[0].pages = 260;\n book_arr[0].price = 450;\n strcpy(book_arr[1].title, \"DBMS Guide\");\n book_arr[1].pages = 850;\n book_arr[1].price = 775;\n strcpy(book_arr[2].title, \"Learn C++\");\n book_arr[2].pages = 350;\n book_arr[2].price = 520;\n strcpy(book_arr[3].title, \"Data Structures\");\n book_arr[3].pages = 380;\n book_arr[3].price = 430;\n strcpy(book_arr[4].title, \"Learn Python\");\n book_arr[4].pages = 500;\n book_arr[4].price = 300;\n qsort((void*)book_arr, 5, sizeof(book_arr[0]), compareBook);\n for(i = 0; i<5; i++) {\n printf(\"%s\\t\\t%d\\t\\t%f\\n\",book_arr[i].title, book_arr[i].pages, book_arr[i].price);\n }\n}" }, { "code": null, "e": 2869, "s": 2639, "text": "Learn Python 500 300.000000\nData Structures 380 430.000000\nC Programming 260 450.000000\nLearn C++ 350 520.000000\nDBMS Guide 850 775.000000" } ]
Bayesian Neural Networks with TensorFlow Probability | by Georgi Tancev | Towards Data Science
Machine learning models are usually developed from data as deterministic machines that map input to output using a point estimate of parameter weights calculated by maximum-likelihood methods. However, there is a lot of statistical fluke going on in the background. For instance, a dataset itself is a finite random set of points of arbitrary size from a unknown distribution superimposed by additive noise, and for such a particular collection of points, different models (i.e. different parameter combinations) might be reasonable. Hence, there is some uncertainty about the parameters and predictions being made. Bayesian statistics provides a framework to deal with the so-called aleoteric and epistemic uncertainty, and with the release of TensorFlow Probability, probabilistic modeling has been made a lot easier, as I shall demonstrate with this post. Be aware that no theoretical background will be provided; for theory on this topic, I can really recommend the book “Bayesian Data Analysis” by Gelman et al., which is available as PDF-file for free. www.stat.columbia.edu A Bayesian neural network is characterized by its distribution over weights (parameters) and/or outputs. Depending on wether aleotoric, epistemic, or both uncertainties are considered, the code for a Bayesian neural network looks slighty different. To demonstrate the working principle, the Air Quality dataset from De Vito will serve as an example. It contains data from different chemical sensors for pollutants (as voltage) together with references as a year-long time series, which has been collected at a main street in an Italian city characterized by heavy car traffic, and the goal is to construct a mapping from sensor responses to reference concentrations (Figure 1), i.e. building a calibration function as a regression task. If you have not installed TensorFlow Probability yet, you can do it with pip, but it might be a good idea to create a virtual environment before. (Since commands can change in later versions, you might want to install the ones I have used.) # Install libraries.pip install tensorflow==2.1.0pip install tensorflow-probability==0.9.0 Open your favorite editor or JupyterLab. Import all necessarty libraries. # Load libriaries and functions.import pandas as pdimport numpy as npimport tensorflow as tftfk = tf.kerastf.keras.backend.set_floatx("float64")import tensorflow_probability as tfptfd = tfp.distributionsfrom sklearn.preprocessing import StandardScalerfrom sklearn.ensemble import IsolationForest# Define helper functions.scaler = StandardScaler()detector = IsolationForest(n_estimators=1000, behaviour="deprecated", contamination="auto", random_state=0)neg_log_likelihood = lambda x, rv_x: -rv_x.log_prob(x) Next, grab the dataset (link can be found above) and load it as a pandas dataframe. As sensors tend to drift due to aging, it is better to discard the data past month six. # Load data and keep only first six months due to drift.data = pd.read_excel("data.xlsx")data = data[data["Date"] <= "2004-09-10"] The data is quite messy and has to be preprocessed first. We will focus on the inputs and outputs which were measured for most of the time (one sensor died quite early). Data is scaled after removing rows with missing values. Afterwards, outliers are detected and removed using an Isolation Forest. # Select columns and remove rows with missing values.columns = ["PT08.S1(CO)", "PT08.S3(NOx)", "PT08.S4(NO2)", "PT08.S5(O3)", "T", "AH", "CO(GT)", "C6H6(GT)", "NOx(GT)", "NO2(GT)"]data = data[columns].dropna(axis=0)# Scale data to zero mean and unit variance.X_t = scaler.fit_transform(data)# Remove outliers.is_inlier = detector.fit_predict(X_t)X_t = X_t[(is_inlier > 0),:]# Restore frame.dataset = pd.DataFrame(X_t, columns=columns)# Select labels for inputs and outputs.inputs = ["PT08.S1(CO)", "PT08.S3(NOx)", "PT08.S4(NO2)", "PT08.S5(O3)", "T", "AH"]outputs = ["CO(GT)", "C6H6(GT)", "NOx(GT)", "NO2(GT)"] TensorFlow offers a dataset class to construct training and test sets. We shall use 70% of the data as training set. The sets are shuffled and repeating batches are constructed. # Define some hyperparameters.n_epochs = 50n_samples = dataset.shape[0]n_batches = 10batch_size = np.floor(n_samples/n_batches)buffer_size = n_samples# Define training and test data sizes.n_train = int(0.7*dataset.shape[0])# Define dataset instance.data = tf.data.Dataset.from_tensor_slices((dataset[inputs].values, dataset[outputs].values))data = data.shuffle(n_samples, reshuffle_each_iteration=True)# Define train and test data instances.data_train = data.take(n_train).batch(batch_size).repeat(n_epochs)data_test = data.skip(n_train).batch(1) To account for aleotoric uncertainty, which arises from the noise in the output, dense layers are combined with probabilistic layers. More specifically, the mean and covariance matrix of the output is modelled as a function of the input and parameter weights. The first hidden layer shall consist of ten nodes, the second one needs four nodes for the means plus ten nodes for the variances and covariances of the four-dimensional (there are four outputs) multivariate Gaussian posterior probability distribution in the final layer. This is achieved using the params_size method of the last layer (MultivariateNormalTriL), which is the declaration of the posterior probability distribution structure, in this case a multivariate normal distribution in which only one half of the covariance matrix is estimated (due to symmetry). The total number of parameters in the model is 224 — estimated by variational methods. The deterministic version of this neural network consists of an input layer, ten latent variables (hidden nodes), and an output layer (114 parameters), which does not include the uncertainty in the parameters weights. # Define prior for regularization.prior = tfd.Independent(tfd.Normal(loc=tf.zeros(len(outputs), dtype=tf.float64), scale=1.0), reinterpreted_batch_ndims=1)# Define model instance.model = tfk.Sequential([tfk.layers.InputLayer(input_shape=(len(inputs),), name="input"),tfk.layers.Dense(10, activation="relu", name="dense_1"),tfk.layers.Dense(tfp.layers.MultivariateNormalTriL.params_size(len(outputs)), activation=None, name="distribution_weights"),tfp.layers.MultivariateNormalTriL(len(outputs), activity_regularizer=tfp.layers.KLDivergenceRegularizer(prior, weight=1/n_batches), name="output")], name="model")# Compile model.model.compile(optimizer="adam", loss=neg_log_likelihood)# Run training session.model.fit(data_train, epochs=n_epochs, validation_data=data_test, verbose=False)# Describe model.model.summary() The activity_regularizer argument acts as prior for the output layer (the weight has to be adjusted to the number of batches). The training session might take a while depending on the specifications of your machine. The algorithm needs about 50 epochs to converge (Figure 2). To account for aleotoric and epistemic uncertainty (uncertainty in parameter weights), the dense layers have to be exchanged with Flipout layers (DenseFlipout) or with Variational layers (DenseVariational). Such a model has more parameters, since every weight is parametrized by normal distribution with non-shared mean and standard deviation, hence doubling the amount of parameter weights. Weights will be resampled for different predictions, and in that case, the Bayesian neural network will act like an ensemble. tfp.layers.DenseFlipout(10, activation="relu", name="dense_1") The default prior distribution over weights is tfd.Normal(loc=0., scale=1.) and can be adjusted using the kernel_prior_fn argument. Since it is a probabilistic model, a Monte Carlo experiment is performed to provide a prediction. In particular, every prediction of a sample x results in a different output y, which is why the expectation over many individual predictions has to be calculated. Additionally, the variance can be determined this way. # Predict.samples = 500iterations = 10test_iterator = tf.compat.v1.data.make_one_shot_iterator(data_test)X_true, Y_true, Y_pred = np.empty(shape=(samples, len(inputs))), np.empty(shape=(samples, len(outputs))), np.empty(shape=(samples, len(outputs), iterations))for i in range(samples): features, labels = test_iterator.get_next() X_true[i,:] = features Y_true[i,:] = labels.numpy() for k in range(iterations): Y_pred[i,:,k] = model.predict(features) # Calculate mean and standard deviation.Y_pred_m = np.mean(Y_pred, axis=-1)Y_pred_s = np.std(Y_pred, axis=-1) Figure 3 shows the measured data versus the expectation of the predictions for all outputs. The coefficient of determination is about 0.86, the slope is 0.84 — not too bad. Predicted uncertainty can be visualized by plotting error bars together with the expectations (Figure 4). In this case, the error bar is 1.96 times the standard deviation, i.e. accounting for 95% of the probability. In theory, a Baysian approach is superior to a deterministic one due to the additional uncertainty information, but not always possible because of its high computational costs. Recent research revolves around developing novel methods to overcome these limitations.
[ { "code": null, "e": 1231, "s": 172, "text": "Machine learning models are usually developed from data as deterministic machines that map input to output using a point estimate of parameter weights calculated by maximum-likelihood methods. However, there is a lot of statistical fluke going on in the background. For instance, a dataset itself is a finite random set of points of arbitrary size from a unknown distribution superimposed by additive noise, and for such a particular collection of points, different models (i.e. different parameter combinations) might be reasonable. Hence, there is some uncertainty about the parameters and predictions being made. Bayesian statistics provides a framework to deal with the so-called aleoteric and epistemic uncertainty, and with the release of TensorFlow Probability, probabilistic modeling has been made a lot easier, as I shall demonstrate with this post. Be aware that no theoretical background will be provided; for theory on this topic, I can really recommend the book “Bayesian Data Analysis” by Gelman et al., which is available as PDF-file for free." }, { "code": null, "e": 1253, "s": 1231, "text": "www.stat.columbia.edu" }, { "code": null, "e": 1990, "s": 1253, "text": "A Bayesian neural network is characterized by its distribution over weights (parameters) and/or outputs. Depending on wether aleotoric, epistemic, or both uncertainties are considered, the code for a Bayesian neural network looks slighty different. To demonstrate the working principle, the Air Quality dataset from De Vito will serve as an example. It contains data from different chemical sensors for pollutants (as voltage) together with references as a year-long time series, which has been collected at a main street in an Italian city characterized by heavy car traffic, and the goal is to construct a mapping from sensor responses to reference concentrations (Figure 1), i.e. building a calibration function as a regression task." }, { "code": null, "e": 2231, "s": 1990, "text": "If you have not installed TensorFlow Probability yet, you can do it with pip, but it might be a good idea to create a virtual environment before. (Since commands can change in later versions, you might want to install the ones I have used.)" }, { "code": null, "e": 2322, "s": 2231, "text": "# Install libraries.pip install tensorflow==2.1.0pip install tensorflow-probability==0.9.0" }, { "code": null, "e": 2396, "s": 2322, "text": "Open your favorite editor or JupyterLab. Import all necessarty libraries." }, { "code": null, "e": 2904, "s": 2396, "text": "# Load libriaries and functions.import pandas as pdimport numpy as npimport tensorflow as tftfk = tf.kerastf.keras.backend.set_floatx(\"float64\")import tensorflow_probability as tfptfd = tfp.distributionsfrom sklearn.preprocessing import StandardScalerfrom sklearn.ensemble import IsolationForest# Define helper functions.scaler = StandardScaler()detector = IsolationForest(n_estimators=1000, behaviour=\"deprecated\", contamination=\"auto\", random_state=0)neg_log_likelihood = lambda x, rv_x: -rv_x.log_prob(x)" }, { "code": null, "e": 3076, "s": 2904, "text": "Next, grab the dataset (link can be found above) and load it as a pandas dataframe. As sensors tend to drift due to aging, it is better to discard the data past month six." }, { "code": null, "e": 3207, "s": 3076, "text": "# Load data and keep only first six months due to drift.data = pd.read_excel(\"data.xlsx\")data = data[data[\"Date\"] <= \"2004-09-10\"]" }, { "code": null, "e": 3506, "s": 3207, "text": "The data is quite messy and has to be preprocessed first. We will focus on the inputs and outputs which were measured for most of the time (one sensor died quite early). Data is scaled after removing rows with missing values. Afterwards, outliers are detected and removed using an Isolation Forest." }, { "code": null, "e": 4116, "s": 3506, "text": "# Select columns and remove rows with missing values.columns = [\"PT08.S1(CO)\", \"PT08.S3(NOx)\", \"PT08.S4(NO2)\", \"PT08.S5(O3)\", \"T\", \"AH\", \"CO(GT)\", \"C6H6(GT)\", \"NOx(GT)\", \"NO2(GT)\"]data = data[columns].dropna(axis=0)# Scale data to zero mean and unit variance.X_t = scaler.fit_transform(data)# Remove outliers.is_inlier = detector.fit_predict(X_t)X_t = X_t[(is_inlier > 0),:]# Restore frame.dataset = pd.DataFrame(X_t, columns=columns)# Select labels for inputs and outputs.inputs = [\"PT08.S1(CO)\", \"PT08.S3(NOx)\", \"PT08.S4(NO2)\", \"PT08.S5(O3)\", \"T\", \"AH\"]outputs = [\"CO(GT)\", \"C6H6(GT)\", \"NOx(GT)\", \"NO2(GT)\"]" }, { "code": null, "e": 4294, "s": 4116, "text": "TensorFlow offers a dataset class to construct training and test sets. We shall use 70% of the data as training set. The sets are shuffled and repeating batches are constructed." }, { "code": null, "e": 4841, "s": 4294, "text": "# Define some hyperparameters.n_epochs = 50n_samples = dataset.shape[0]n_batches = 10batch_size = np.floor(n_samples/n_batches)buffer_size = n_samples# Define training and test data sizes.n_train = int(0.7*dataset.shape[0])# Define dataset instance.data = tf.data.Dataset.from_tensor_slices((dataset[inputs].values, dataset[outputs].values))data = data.shuffle(n_samples, reshuffle_each_iteration=True)# Define train and test data instances.data_train = data.take(n_train).batch(batch_size).repeat(n_epochs)data_test = data.skip(n_train).batch(1)" }, { "code": null, "e": 5974, "s": 4841, "text": "To account for aleotoric uncertainty, which arises from the noise in the output, dense layers are combined with probabilistic layers. More specifically, the mean and covariance matrix of the output is modelled as a function of the input and parameter weights. The first hidden layer shall consist of ten nodes, the second one needs four nodes for the means plus ten nodes for the variances and covariances of the four-dimensional (there are four outputs) multivariate Gaussian posterior probability distribution in the final layer. This is achieved using the params_size method of the last layer (MultivariateNormalTriL), which is the declaration of the posterior probability distribution structure, in this case a multivariate normal distribution in which only one half of the covariance matrix is estimated (due to symmetry). The total number of parameters in the model is 224 — estimated by variational methods. The deterministic version of this neural network consists of an input layer, ten latent variables (hidden nodes), and an output layer (114 parameters), which does not include the uncertainty in the parameters weights." }, { "code": null, "e": 6791, "s": 5974, "text": "# Define prior for regularization.prior = tfd.Independent(tfd.Normal(loc=tf.zeros(len(outputs), dtype=tf.float64), scale=1.0), reinterpreted_batch_ndims=1)# Define model instance.model = tfk.Sequential([tfk.layers.InputLayer(input_shape=(len(inputs),), name=\"input\"),tfk.layers.Dense(10, activation=\"relu\", name=\"dense_1\"),tfk.layers.Dense(tfp.layers.MultivariateNormalTriL.params_size(len(outputs)), activation=None, name=\"distribution_weights\"),tfp.layers.MultivariateNormalTriL(len(outputs), activity_regularizer=tfp.layers.KLDivergenceRegularizer(prior, weight=1/n_batches), name=\"output\")], name=\"model\")# Compile model.model.compile(optimizer=\"adam\", loss=neg_log_likelihood)# Run training session.model.fit(data_train, epochs=n_epochs, validation_data=data_test, verbose=False)# Describe model.model.summary()" }, { "code": null, "e": 7067, "s": 6791, "text": "The activity_regularizer argument acts as prior for the output layer (the weight has to be adjusted to the number of batches). The training session might take a while depending on the specifications of your machine. The algorithm needs about 50 epochs to converge (Figure 2)." }, { "code": null, "e": 7585, "s": 7067, "text": "To account for aleotoric and epistemic uncertainty (uncertainty in parameter weights), the dense layers have to be exchanged with Flipout layers (DenseFlipout) or with Variational layers (DenseVariational). Such a model has more parameters, since every weight is parametrized by normal distribution with non-shared mean and standard deviation, hence doubling the amount of parameter weights. Weights will be resampled for different predictions, and in that case, the Bayesian neural network will act like an ensemble." }, { "code": null, "e": 7648, "s": 7585, "text": "tfp.layers.DenseFlipout(10, activation=\"relu\", name=\"dense_1\")" }, { "code": null, "e": 7780, "s": 7648, "text": "The default prior distribution over weights is tfd.Normal(loc=0., scale=1.) and can be adjusted using the kernel_prior_fn argument." }, { "code": null, "e": 8096, "s": 7780, "text": "Since it is a probabilistic model, a Monte Carlo experiment is performed to provide a prediction. In particular, every prediction of a sample x results in a different output y, which is why the expectation over many individual predictions has to be calculated. Additionally, the variance can be determined this way." }, { "code": null, "e": 8683, "s": 8096, "text": "# Predict.samples = 500iterations = 10test_iterator = tf.compat.v1.data.make_one_shot_iterator(data_test)X_true, Y_true, Y_pred = np.empty(shape=(samples, len(inputs))), np.empty(shape=(samples, len(outputs))), np.empty(shape=(samples, len(outputs), iterations))for i in range(samples): features, labels = test_iterator.get_next() X_true[i,:] = features Y_true[i,:] = labels.numpy() for k in range(iterations): Y_pred[i,:,k] = model.predict(features) # Calculate mean and standard deviation.Y_pred_m = np.mean(Y_pred, axis=-1)Y_pred_s = np.std(Y_pred, axis=-1)" }, { "code": null, "e": 8856, "s": 8683, "text": "Figure 3 shows the measured data versus the expectation of the predictions for all outputs. The coefficient of determination is about 0.86, the slope is 0.84 — not too bad." }, { "code": null, "e": 9072, "s": 8856, "text": "Predicted uncertainty can be visualized by plotting error bars together with the expectations (Figure 4). In this case, the error bar is 1.96 times the standard deviation, i.e. accounting for 95% of the probability." } ]
Gamma Distribution in R Programming – dgamma(), pgamma(), qgamma(), and rgamma() Functions
30 Jun, 2020 The Gamma distribution in R Language is defined as a two-parameter family of continuous probability distributions which is used in exponential distribution, Erlang distribution, and chi-squared distribution. This article is the implementation of functions of gamma distribution. dgamma() function is used to create gamma density plot which is basically used due to exponential and normal distributions factors. Syntax:dgamma(x_dgamma, shape) Parameters:x_dgamma: defines gamma functionshape: gamma density of input values Returns: Plot dgamma values Example : # R program to plot gamma distribution # Specify x-values for gamma functionx_dgamma <- seq(0, 2, by = 0.04) # Apply dgamma functiony_dgamma <- dgamma(x_dgamma, shape = 6) # Plot dgamma valuesplot(y_dgamma) Output : pgamma() function is used in cumulative distribution function (CDF) of the gamma distribution. Syntax:pgamma(x_pgamma, shape) Parameters:x_pgamma: defines gamma functionshape: gamma density of input values Returns: Plot pgamma values Example: # R program to plot gamma distribution # Specify x-values for gamma functionx_pgamma <- seq(0, 2, by = 0.04) # Apply pgamma functiony_pgamma <- pgamma(x_pgamma, shape = 6) # Plot pgamma valuesplot(y_pgamma) Output: It is known as gamma quantile function of the gamma distribution and used to plot qgamma distribution. Syntax:qgamma(x_qgamma, shape) Parameters:x_qgamma: defines gamma functionshape: gamma density of input values Returns: Plot qgamma values with gamma density Example : # R program to plot gamma distribution # Specify x-values for gamma functionx_qgamma <- seq(0, 1, by = 0.03) # Apply qgamma functiony_qgamma <- qgamma(x_qgamma, shape = 6) # Plot qgamma valuesplot(y_qgamma) Output: This function is basically used for generating random number in gamma distribution. Syntax:rgamma(N, shape) Parameters:N: gamma distributed valuesshape: gamma density of input values Returns: Plot rgamma values with gamma density Example : # R program to plot gamma distribution # Set seed for reproducibilityset.seed(1200) # Specify sample sizeN <- 800 # Draw N gamma distributed valuesy_rgamma <- rgamma(N, shape = 5) # Print values to RStudio consoley_rgamma # Plot of randomly drawn gamma densityhist(y_rgamma, breaks = 500, main = "") Output: R Statistics-Function R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Filter data by multiple conditions in R using Dplyr Change Color of Bars in Barchart using ggplot2 in R How to Split Column Into Multiple Columns in R DataFrame? Loops in R (for, while, repeat) Group by function in R using Dplyr How to change Row Names of DataFrame in R ? R Programming Language - Introduction How to Change Axis Scales in R Plots? R - if statement How to filter R DataFrame by values in a column?
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Jun, 2020" }, { "code": null, "e": 307, "s": 28, "text": "The Gamma distribution in R Language is defined as a two-parameter family of continuous probability distributions which is used in exponential distribution, Erlang distribution, and chi-squared distribution. This article is the implementation of functions of gamma distribution." }, { "code": null, "e": 439, "s": 307, "text": "dgamma() function is used to create gamma density plot which is basically used due to exponential and normal distributions factors." }, { "code": null, "e": 470, "s": 439, "text": "Syntax:dgamma(x_dgamma, shape)" }, { "code": null, "e": 550, "s": 470, "text": "Parameters:x_dgamma: defines gamma functionshape: gamma density of input values" }, { "code": null, "e": 578, "s": 550, "text": "Returns: Plot dgamma values" }, { "code": null, "e": 588, "s": 578, "text": "Example :" }, { "code": "# R program to plot gamma distribution # Specify x-values for gamma functionx_dgamma <- seq(0, 2, by = 0.04) # Apply dgamma functiony_dgamma <- dgamma(x_dgamma, shape = 6) # Plot dgamma valuesplot(y_dgamma)", "e": 802, "s": 588, "text": null }, { "code": null, "e": 811, "s": 802, "text": "Output :" }, { "code": null, "e": 906, "s": 811, "text": "pgamma() function is used in cumulative distribution function (CDF) of the gamma distribution." }, { "code": null, "e": 937, "s": 906, "text": "Syntax:pgamma(x_pgamma, shape)" }, { "code": null, "e": 1017, "s": 937, "text": "Parameters:x_pgamma: defines gamma functionshape: gamma density of input values" }, { "code": null, "e": 1045, "s": 1017, "text": "Returns: Plot pgamma values" }, { "code": null, "e": 1054, "s": 1045, "text": "Example:" }, { "code": "# R program to plot gamma distribution # Specify x-values for gamma functionx_pgamma <- seq(0, 2, by = 0.04) # Apply pgamma functiony_pgamma <- pgamma(x_pgamma, shape = 6) # Plot pgamma valuesplot(y_pgamma)", "e": 1268, "s": 1054, "text": null }, { "code": null, "e": 1276, "s": 1268, "text": "Output:" }, { "code": null, "e": 1379, "s": 1276, "text": "It is known as gamma quantile function of the gamma distribution and used to plot qgamma distribution." }, { "code": null, "e": 1410, "s": 1379, "text": "Syntax:qgamma(x_qgamma, shape)" }, { "code": null, "e": 1490, "s": 1410, "text": "Parameters:x_qgamma: defines gamma functionshape: gamma density of input values" }, { "code": null, "e": 1537, "s": 1490, "text": "Returns: Plot qgamma values with gamma density" }, { "code": null, "e": 1547, "s": 1537, "text": "Example :" }, { "code": "# R program to plot gamma distribution # Specify x-values for gamma functionx_qgamma <- seq(0, 1, by = 0.03) # Apply qgamma functiony_qgamma <- qgamma(x_qgamma, shape = 6) # Plot qgamma valuesplot(y_qgamma)", "e": 1761, "s": 1547, "text": null }, { "code": null, "e": 1769, "s": 1761, "text": "Output:" }, { "code": null, "e": 1853, "s": 1769, "text": "This function is basically used for generating random number in gamma distribution." }, { "code": null, "e": 1877, "s": 1853, "text": "Syntax:rgamma(N, shape)" }, { "code": null, "e": 1952, "s": 1877, "text": "Parameters:N: gamma distributed valuesshape: gamma density of input values" }, { "code": null, "e": 1999, "s": 1952, "text": "Returns: Plot rgamma values with gamma density" }, { "code": null, "e": 2009, "s": 1999, "text": "Example :" }, { "code": "# R program to plot gamma distribution # Set seed for reproducibilityset.seed(1200) # Specify sample sizeN <- 800 # Draw N gamma distributed valuesy_rgamma <- rgamma(N, shape = 5) # Print values to RStudio consoley_rgamma # Plot of randomly drawn gamma densityhist(y_rgamma, breaks = 500, main = \"\")", "e": 2319, "s": 2009, "text": null }, { "code": null, "e": 2327, "s": 2319, "text": "Output:" }, { "code": null, "e": 2349, "s": 2327, "text": "R Statistics-Function" }, { "code": null, "e": 2360, "s": 2349, "text": "R Language" }, { "code": null, "e": 2458, "s": 2360, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2510, "s": 2458, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 2562, "s": 2510, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 2620, "s": 2562, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 2652, "s": 2620, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 2687, "s": 2652, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 2731, "s": 2687, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 2769, "s": 2731, "text": "R Programming Language - Introduction" }, { "code": null, "e": 2807, "s": 2769, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 2824, "s": 2807, "text": "R - if statement" } ]
Find the nearest value present on the left of every array element
10 Jun, 2021 Given an array arr[] of size N, the task is for each array element is to find the nearest non-equal value present on its left in the array. If no such element is found, then print -1 Examples: Input: arr[] = { 2, 1, 5, 8, 3 }Output: -1 2 2 5 2Explanation:[2], it is the only number in this prefix. Hence, answer is -1. [2, 1], the closest number to 1 is 2[2, 1, 5], the closest number to 5 is 2[2, 1, 5, 8], the closest number to 8 is 5 [2, 1, 5, 8, 3], the closest number to 3 is 2 Input: arr[] = {3, 3, 2, 4, 6, 5, 5, 1}Output: -1 -1 3 3 4 4 4 2Explanation:[3], it is the only number in this prefix. Hence, answer is -1. [3, 3], it is the only number in this prefix. Hence, answer is -1[3, 3, 2], the closest number to 2 is 3[3, 3, 2, 4], the closest number to 4 is 3 [3, 3, 2, 4, 6], the closest number to 6 is 4[3, 3, 2, 4, 6, 5], the closest number to 5 is 4[3, 3, 2, 4, 6, 5, 5], the closest number to 5 is 4[3, 3, 2, 4, 6, 5, 5, 1], the closest number to 1 is 2 Naive Approach: The simplest idea is to traverse the given array and for every ith element, find the closest element on the left side of index i which is not equal to arr[i]. Time Complexity: O(N^2)Auxiliary Space: O(1) Efficient Approach: The idea is to insert the elements of the given array in a Set such that the inserted numbers are sorted and then for an integer, find its position and compare its next value with the previous value, and print the closer value out of the two.Follow the steps below to solve the problem: Initialize a Set of integers S to store the elements in sorted order. Traverse the array arr[] using the variable i. Now, find the nearest value smaller as well as greater than arr[i], say X and Y respectively.If X cannot be found, print Y.If Y cannot be found, print Z.If both X and Y cannot be found, print “-1”. If X cannot be found, print Y. If Y cannot be found, print Z. If both X and Y cannot be found, print “-1”. After that, add arr[i] to the Set S and print X if abs(X – arr[i]) is smaller than abs(Y – arr[i]). Otherwise, print Y. Repeat the above steps for every element. Below is the implementation of the above approach: C++14 // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the closest number on// the left side of xvoid printClosest(set<int>& streamNumbers, int x){ // Insert the value in set and store // its position auto it = streamNumbers.insert(x).first; // If x is the smallest element in set if (it == streamNumbers.begin()) { // If count of elements in the set // equal to 1 if (next(it) == streamNumbers.end()) { cout << "-1 "; return; } // Otherwise, print its // immediate greater element int rightVal = *next(it); cout << rightVal << " "; return; } // Store its immediate smaller element int leftVal = *prev(it); // If immediate greater element does not // exists print it's immediate // smaller element if (next(it) == streamNumbers.end()) { cout << leftVal << " "; return; } // Store the immediate // greater element int rightVal = *next(it); // Print the closest number if (x - leftVal <= rightVal - x) cout << leftVal << " "; else cout << rightVal << " ";} // Driver Codeint main(){ // Given array vector<int> arr = { 3, 3, 2, 4, 6, 5, 5, 1 }; // Initialize set set<int> streamNumbers; // Print Answer for (int i = 0; i < arr.size(); i++) { // Function Call printClosest(streamNumbers, arr[i]); } return 0;} -1 -1 3 3 4 4 4 2 Time Complexity: O(N * log(N))Auxiliary Space: O(N) pratikraut0000 khushboogoyal499 cpp-set Technical Scripter 2020 Arrays Hash Mathematical Searching Technical Scripter Arrays Searching Hash Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n10 Jun, 2021" }, { "code": null, "e": 237, "s": 54, "text": "Given an array arr[] of size N, the task is for each array element is to find the nearest non-equal value present on its left in the array. If no such element is found, then print -1" }, { "code": null, "e": 247, "s": 237, "text": "Examples:" }, { "code": null, "e": 537, "s": 247, "text": "Input: arr[] = { 2, 1, 5, 8, 3 }Output: -1 2 2 5 2Explanation:[2], it is the only number in this prefix. Hence, answer is -1. [2, 1], the closest number to 1 is 2[2, 1, 5], the closest number to 5 is 2[2, 1, 5, 8], the closest number to 8 is 5 [2, 1, 5, 8, 3], the closest number to 3 is 2" }, { "code": null, "e": 1023, "s": 537, "text": "Input: arr[] = {3, 3, 2, 4, 6, 5, 5, 1}Output: -1 -1 3 3 4 4 4 2Explanation:[3], it is the only number in this prefix. Hence, answer is -1. [3, 3], it is the only number in this prefix. Hence, answer is -1[3, 3, 2], the closest number to 2 is 3[3, 3, 2, 4], the closest number to 4 is 3 [3, 3, 2, 4, 6], the closest number to 6 is 4[3, 3, 2, 4, 6, 5], the closest number to 5 is 4[3, 3, 2, 4, 6, 5, 5], the closest number to 5 is 4[3, 3, 2, 4, 6, 5, 5, 1], the closest number to 1 is 2" }, { "code": null, "e": 1243, "s": 1023, "text": "Naive Approach: The simplest idea is to traverse the given array and for every ith element, find the closest element on the left side of index i which is not equal to arr[i]. Time Complexity: O(N^2)Auxiliary Space: O(1)" }, { "code": null, "e": 1264, "s": 1243, "text": "Efficient Approach: " }, { "code": null, "e": 1551, "s": 1264, "text": "The idea is to insert the elements of the given array in a Set such that the inserted numbers are sorted and then for an integer, find its position and compare its next value with the previous value, and print the closer value out of the two.Follow the steps below to solve the problem:" }, { "code": null, "e": 1621, "s": 1551, "text": "Initialize a Set of integers S to store the elements in sorted order." }, { "code": null, "e": 1668, "s": 1621, "text": "Traverse the array arr[] using the variable i." }, { "code": null, "e": 1866, "s": 1668, "text": "Now, find the nearest value smaller as well as greater than arr[i], say X and Y respectively.If X cannot be found, print Y.If Y cannot be found, print Z.If both X and Y cannot be found, print “-1”." }, { "code": null, "e": 1897, "s": 1866, "text": "If X cannot be found, print Y." }, { "code": null, "e": 1928, "s": 1897, "text": "If Y cannot be found, print Z." }, { "code": null, "e": 1973, "s": 1928, "text": "If both X and Y cannot be found, print “-1”." }, { "code": null, "e": 2093, "s": 1973, "text": "After that, add arr[i] to the Set S and print X if abs(X – arr[i]) is smaller than abs(Y – arr[i]). Otherwise, print Y." }, { "code": null, "e": 2135, "s": 2093, "text": "Repeat the above steps for every element." }, { "code": null, "e": 2188, "s": 2135, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 2194, "s": 2188, "text": "C++14" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the closest number on// the left side of xvoid printClosest(set<int>& streamNumbers, int x){ // Insert the value in set and store // its position auto it = streamNumbers.insert(x).first; // If x is the smallest element in set if (it == streamNumbers.begin()) { // If count of elements in the set // equal to 1 if (next(it) == streamNumbers.end()) { cout << \"-1 \"; return; } // Otherwise, print its // immediate greater element int rightVal = *next(it); cout << rightVal << \" \"; return; } // Store its immediate smaller element int leftVal = *prev(it); // If immediate greater element does not // exists print it's immediate // smaller element if (next(it) == streamNumbers.end()) { cout << leftVal << \" \"; return; } // Store the immediate // greater element int rightVal = *next(it); // Print the closest number if (x - leftVal <= rightVal - x) cout << leftVal << \" \"; else cout << rightVal << \" \";} // Driver Codeint main(){ // Given array vector<int> arr = { 3, 3, 2, 4, 6, 5, 5, 1 }; // Initialize set set<int> streamNumbers; // Print Answer for (int i = 0; i < arr.size(); i++) { // Function Call printClosest(streamNumbers, arr[i]); } return 0;}", "e": 3678, "s": 2194, "text": null }, { "code": null, "e": 3697, "s": 3678, "text": "-1 -1 3 3 4 4 4 2 " }, { "code": null, "e": 3749, "s": 3697, "text": "Time Complexity: O(N * log(N))Auxiliary Space: O(N)" }, { "code": null, "e": 3764, "s": 3749, "text": "pratikraut0000" }, { "code": null, "e": 3781, "s": 3764, "text": "khushboogoyal499" }, { "code": null, "e": 3789, "s": 3781, "text": "cpp-set" }, { "code": null, "e": 3813, "s": 3789, "text": "Technical Scripter 2020" }, { "code": null, "e": 3820, "s": 3813, "text": "Arrays" }, { "code": null, "e": 3825, "s": 3820, "text": "Hash" }, { "code": null, "e": 3838, "s": 3825, "text": "Mathematical" }, { "code": null, "e": 3848, "s": 3838, "text": "Searching" }, { "code": null, "e": 3867, "s": 3848, "text": "Technical Scripter" }, { "code": null, "e": 3874, "s": 3867, "text": "Arrays" }, { "code": null, "e": 3884, "s": 3874, "text": "Searching" }, { "code": null, "e": 3889, "s": 3884, "text": "Hash" }, { "code": null, "e": 3902, "s": 3889, "text": "Mathematical" } ]
N’th palindrome of K digits
27 Apr, 2021 Given two integers n and k, Find the lexicographical nth palindrome of k digits.Examples: Input : n = 5, k = 4 Output : 1441 Explanation: 4 digit lexicographical palindromes are: 1001, 1111, 1221, 1331, 1441 5th palindrome = 1441 Input : n = 4, k = 6 Output : 103301 Naive Approach A brute force is to run a loop from the smallest kth digit number and check for every number whether it is palindrome or not. If it is a palindrome number then decrements the value of k. Therefore the loop runs until k becomes exhausted. C++ Java Python3 C# PHP Javascript // A naive approach of C++ program of finding nth// palindrome of k digit#include<bits/stdc++.h>using namespace std; // Utility function to reverse the number nint reverseNum(int n){ int rem, rev=0; while (n) { rem = n % 10; rev = rev * 10 + rem; n /= 10; } return rev;} // Boolean Function to check for palindromic// numberbool isPalindrom(int num){ return num == reverseNum(num);} // Function for finding nth palindrome of k digitsint nthPalindrome(int n,int k){ // Get the smallest k digit number int num = (int)pow(10, k-1); while (true) { // check the number is palindrom or not if (isPalindrom(num)) --n; // if n'th palindrome found break the loop if (!n) break; // Increment number for checking next palindrome ++num; } return num;} // Driver codeint main(){ int n = 6, k = 5; printf("%dth palindrome of %d digit = %d\n", n, k, nthPalindrome(n, k)); n = 10, k = 6; printf("%dth palindrome of %d digit = %d", n, k, nthPalindrome(n, k)); return 0;} // A naive approach of Java program of finding nth// palindrome of k digitimport java.util.*; class GFG{// Utility function to reverse the number nstatic int reverseNum(int n){ int rem, rev = 0; while (n > 0) { rem = n % 10; rev = rev * 10 + rem; n /= 10; } return rev;} // Boolean Function to check for palindromic// numberstatic boolean isPalindrom(int num){ return num == reverseNum(num);} // Function for finding nth palindrome of k digitsstatic int nthPalindrome(int n, int k){ // Get the smallest k digit number int num = (int)Math.pow(10, k-1); while (true) { // check the number is palindrom or not if (isPalindrom(num)) --n; // if n'th palindrome found break the loop if (n == 0) break; // Increment number for checking next palindrome ++num; } return num;} // Driver codepublic static void main(String[] args){ int n = 6, k = 5; System.out.println(n + "th palindrome of " + k + " digit = " + nthPalindrome(n, k)); n = 10; k = 6; System.out.println(n + "th palindrome of " + k + " digit = " + nthPalindrome(n, k));}} // This code is contributed by mits # A naive approach of Python3 program# of finding nth palindrome of k digitimport math;# Utility function to# reverse the number ndef reverseNum(n): rev = 0; while (n): rem = n % 10; rev = (rev * 10) + rem; n = int(n / 10); return rev; # Boolean Function to check for# palindromic numberdef isPalindrom(num): return num == reverseNum(num); # Function for finding nth# palindrome of k digitsdef nthPalindrome(n, k): # Get the smallest k digit number num = math.pow(10, k - 1); while (True): # check the number is # palindrom or not if (isPalindrom(num)): n-=1; # if n'th palindrome found # break the loop if (not n): break; # Increment number for checking # next palindrome num+=1; return int(num); # Driver coden = 6;k = 5;print(n,"th palindrome of",k,"digit =",nthPalindrome(n, k)); n = 10;k = 6;print(n,"th palindrome of",k,"digit =",nthPalindrome(n, k)); # This code is contributed by mits // A naive approach of C# program of finding nth// palindrome of k digitusing System; class GFG{// Utility function to reverse the number nstatic int reverseNum(int n){ int rem, rev = 0; while (n > 0) { rem = n % 10; rev = rev * 10 + rem; n /= 10; } return rev;} // Boolean Function to check for palindromic// numberstatic bool isPalindrom(int num){ return num == reverseNum(num);} // Function for finding nth palindrome of k digitsstatic int nthPalindrome(int n, int k){ // Get the smallest k digit number int num = (int)Math.Pow(10, k-1); while (true) { // check the number is palindrom or not if (isPalindrom(num)) --n; // if n'th palindrome found break the loop if (n == 0) break; // Increment number for checking next palindrome ++num; } return num;} // Driver codepublic static void Main(){ int n = 6, k = 5; Console.WriteLine(n + "th palindrome of " + k + " digit = " + nthPalindrome(n, k)); n = 10; k = 6; Console.WriteLine(n + "th palindrome of " + k + " digit = " + nthPalindrome(n, k));}} // This code is contributed// by Akanksha Rai <?php// A naive approach of PHP program// of finding nth palindrome of k digit // Utility function to// reverse the number nfunction reverseNum($n){ $rem; $rev = 0; while ($n) { $rem = $n % 10; $rev = ($rev * 10) + $rem; $n = (int)($n / 10); } return $rev;} // Boolean Function to check for// palindromic numberfunction isPalindrom($num){ return $num == reverseNum($num);} // Function for finding nth// palindrome of k digitsfunction nthPalindrome($n, $k){ // Get the smallest k digit number $num = pow(10, $k - 1); while (true) { // check the number is // palindrom or not if (isPalindrom($num)) --$n; // if n'th palindrome found // break the loop if (!$n) break; // Increment number for checking // next palindrome ++$num; } return $num;} // Driver code$n = 6;$k = 5;echo $n, "th palindrome of ", $k, " digit = ", nthPalindrome($n, $k), "\n"; $n = 10;$k = 6;echo $n,"th palindrome of ", $k, " digit = ", nthPalindrome($n, $k), "\n"; // This code is contributed by ajit?> <script> // A naive approach of Javascript // program of finding nth // palindrome of k digit // Utility function to // reverse the number n function reverseNum(n) { let rem, rev = 0; while (n > 0) { rem = n % 10; rev = rev * 10 + rem; n = parseInt(n / 10); } return rev; } // Boolean Function to // check for palindromic // number function isPalindrom(num) { return num == reverseNum(num); } // Function for finding nth // palindrome of k digits function nthPalindrome(n, k) { // Get the smallest k digit number let num = Math.pow(10, k-1); while (true) { // check the number is // palindrom or not if (isPalindrom(num)) --n; // if n'th palindrome found // break the loop if (n == 0) break; // Increment number for checking // next palindrome ++num; } return num; } let n = 6, k = 5; document.write(n + "th palindrome of " + k + " digit = " + nthPalindrome(n, k) + "</br>"); n = 10; k = 6; document.write(n + "th palindrome of " + k + " digit = " + nthPalindrome(n, k)); </script> Output: 6th palindrome of 5 digit = 10501 10th palindrome of 6 digit = 109901 Time complexity: O(10k) Auxiliary space: O(1) Efficient approach An efficient method is to look for a pattern. According to the property of palindrome first, half digits are the same as the rest half digits in reverse order. Therefore, we only need to look for the first half digits as the rest of them can easily be generated. Let’s take k = 8, the smallest palindrome always starts from 1 as the leading digit and goes like that for the first 4 digits of the number. First half values for k = 8 1st: 1000 2nd: 1001 3rd: 1002 ... ... 100th: 1099 So we can easily write the above sequence for nth palindrome as: (n-1) + 1000 For k digit number, we can generalize above formula as: If k is odd => num = (n-1) + 10k/2 else => num = (n-1) + 10k/2 - 1 Now rest half digits can be expanded by just printing the value of num in reverse order. But before this if k is odd then we have to truncate the last digit of a value num Illustration: n = 6 k = 5 Determine the number of first half digits = floor(5/2) = 2Use formula: num = (6-1) + 102 = 105Expand the rest half digits by reversing the value of num. Final answer will be 10501 Determine the number of first half digits = floor(5/2) = 2 Use formula: num = (6-1) + 102 = 105 Expand the rest half digits by reversing the value of num. Final answer will be 10501 Below is the implementation of the above steps C++ Java Python3 C# PHP Javascript // C++ program of finding nth palindrome// of k digit#include<bits/stdc++.h>using namespace std; void nthPalindrome(int n, int k){ // Determine the first half digits int temp = (k & 1) ? (k / 2) : (k/2 - 1); int palindrome = (int)pow(10, temp); palindrome += n - 1; // Print the first half digits of palindrome printf("%d", palindrome); // If k is odd, truncate the last digit if (k & 1) palindrome /= 10; // print the last half digits of palindrome while (palindrome) { printf("%d", palindrome % 10); palindrome /= 10; } printf("\n");} // Driver codeint main(){ int n = 6, k = 5; printf("%dth palindrome of %d digit = ",n ,k); nthPalindrome(n ,k); n = 10, k = 6; printf("%dth palindrome of %d digit = ",n ,k); nthPalindrome(n, k); return 0;} // Java program of finding nth palindrome// of k digit class GFG{static void nthPalindrome(int n, int k){ // Determine the first half digits int temp = (k & 1)!=0 ? (k / 2) : (k/2 - 1); int palindrome = (int)Math.pow(10, temp); palindrome += n - 1; // Print the first half digits of palindrome System.out.print(palindrome); // If k is odd, truncate the last digit if ((k & 1)>0) palindrome /= 10; // print the last half digits of palindrome while (palindrome>0) { System.out.print(palindrome % 10); palindrome /= 10; } System.out.println("");} // Driver codepublic static void main(String[] args){ int n = 6, k = 5; System.out.print(n+"th palindrome of "+k+" digit = "); nthPalindrome(n ,k); n = 10; k = 6; System.out.print(n+"th palindrome of "+k+" digit = "); nthPalindrome(n, k); }}// This code is contributed by mits # Python3 program of finding nth palindrome# of k digit def nthPalindrome(n, k): # Determine the first half digits if(k & 1): temp = k // 2 else: temp = k // 2 - 1 palindrome = 10**temp palindrome = palindrome + n - 1 # Print the first half digits of palindrome print(palindrome, end="") # If k is odd, truncate the last digit if(k & 1): palindrome = palindrome // 10 # print the last half digits of palindrome while(palindrome): print(palindrome % 10, end="") palindrome = palindrome // 10 # Driver codeif __name__=='__main__': n = 6 k = 5 print(n, "th palindrome of", k, " digit = ", end=" ") nthPalindrome(n, k) print() n = 10 k = 6 print(n, "th palindrome of", k, "digit = ",end=" ") nthPalindrome(n, k) # This code is contributed by# Sanjit_Prasad // C# program of finding nth palindrome// of k digitusing System; class GFG{static void nthPalindrome(int n, int k){ // Determine the first half digits int temp = (k & 1) != 0 ? (k / 2) : (k / 2 - 1); int palindrome = (int)Math.Pow(10, temp); palindrome += n - 1; // Print the first half digits // of palindrome Console.Write(palindrome); // If k is odd, truncate the last digit if ((k & 1) > 0) palindrome /= 10; // print the last half digits // of palindrome while (palindrome>0) { Console.Write(palindrome % 10); palindrome /= 10; } Console.WriteLine("");} // Driver codestatic public void Main (){ int n = 6, k = 5; Console.Write(n+"th palindrome of " + k + " digit = "); nthPalindrome(n, k); n = 10; k = 6; Console.Write(n+"th palindrome of " + k + " digit = "); nthPalindrome(n, k);}} // This code is contributed by ajit <?php// PHP program of finding nth palindrome// of k digit function nthPalindrome($n, $k){ // Determine the first half digits $temp = ($k & 1) ? (int)($k / 2) : (int)($k / 2 - 1); $palindrome = (int)pow(10, $temp); $palindrome += $n - 1; // Print the first half digits of palindrome print($palindrome); // If k is odd, truncate the last digit if ($k & 1) $palindrome = (int)($palindrome / 10); // print the last half digits of palindrome while ($palindrome > 0) { print($palindrome % 10); $palindrome = (int)($palindrome / 10); } print("\n");} // Driver code$n = 6;$k = 5;print($n."th palindrome of $k digit = ");nthPalindrome($n, $k); $n = 10;$k = 6;print($n."th palindrome of $k digit = ");nthPalindrome($n, $k); // This code is contributed by mits?> <script> // Javascript program of finding nth palindrome of k digit function nthPalindrome(n, k) { // Determine the first half digits let temp = (k & 1) != 0 ? parseInt(k / 2, 10) : (parseInt(k / 2, 10) - 1); let palindrome = parseInt(Math.pow(10, temp), 10); palindrome += n - 1; // Print the first half digits // of palindrome document.write(palindrome); // If k is odd, truncate the last digit if ((k & 1) > 0) palindrome = parseInt(palindrome / 10, 10); // print the last half digits // of palindrome while (palindrome>0) { document.write(palindrome % 10); palindrome = parseInt(palindrome / 10, 10); } document.write("" + "</br>"); } let n = 6, k = 5; document.write(n+"th palindrome of " + k + " digit = "); nthPalindrome(n, k); n = 10; k = 6; document.write(n+"th palindrome of " + k + " digit = "); nthPalindrome(n, k); </script> Output: 6th palindrome of 5 digit = 10501 10th palindrome of 6 digit = 109901 Time complexity: O(k) Auxiliary space: O(1)Reference: http://stackoverflow.com/questions/11925840/how-to-calculate-nth-n-digit-palindrome-efficientlyThis article is contributed by Shubham Bansal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Sanjit_Prasad Mithun Kumar jit_t Akanksha_Rai divyeshrabadiya07 mukesh07 palindrome Mathematical Mathematical palindrome Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Set in C++ Standard Template Library (STL) Program for Fibonacci numbers C++ Data Types Write a program to print all permutations of a given string Merge two sorted arrays Coin Change | DP-7 Operators in C / C++ Prime Numbers Program to find GCD or HCF of two numbers Minimum number of jumps to reach end
[ { "code": null, "e": 52, "s": 24, "text": "\n27 Apr, 2021" }, { "code": null, "e": 144, "s": 52, "text": "Given two integers n and k, Find the lexicographical nth palindrome of k digits.Examples: " }, { "code": null, "e": 325, "s": 144, "text": "Input : n = 5, k = 4\nOutput : 1441\nExplanation:\n4 digit lexicographical palindromes are:\n1001, 1111, 1221, 1331, 1441\n5th palindrome = 1441\n\nInput : n = 4, k = 6\nOutput : 103301" }, { "code": null, "e": 344, "s": 329, "text": "Naive Approach" }, { "code": null, "e": 584, "s": 344, "text": "A brute force is to run a loop from the smallest kth digit number and check for every number whether it is palindrome or not. If it is a palindrome number then decrements the value of k. Therefore the loop runs until k becomes exhausted. " }, { "code": null, "e": 588, "s": 584, "text": "C++" }, { "code": null, "e": 593, "s": 588, "text": "Java" }, { "code": null, "e": 601, "s": 593, "text": "Python3" }, { "code": null, "e": 604, "s": 601, "text": "C#" }, { "code": null, "e": 608, "s": 604, "text": "PHP" }, { "code": null, "e": 619, "s": 608, "text": "Javascript" }, { "code": "// A naive approach of C++ program of finding nth// palindrome of k digit#include<bits/stdc++.h>using namespace std; // Utility function to reverse the number nint reverseNum(int n){ int rem, rev=0; while (n) { rem = n % 10; rev = rev * 10 + rem; n /= 10; } return rev;} // Boolean Function to check for palindromic// numberbool isPalindrom(int num){ return num == reverseNum(num);} // Function for finding nth palindrome of k digitsint nthPalindrome(int n,int k){ // Get the smallest k digit number int num = (int)pow(10, k-1); while (true) { // check the number is palindrom or not if (isPalindrom(num)) --n; // if n'th palindrome found break the loop if (!n) break; // Increment number for checking next palindrome ++num; } return num;} // Driver codeint main(){ int n = 6, k = 5; printf(\"%dth palindrome of %d digit = %d\\n\", n, k, nthPalindrome(n, k)); n = 10, k = 6; printf(\"%dth palindrome of %d digit = %d\", n, k, nthPalindrome(n, k)); return 0;}", "e": 1734, "s": 619, "text": null }, { "code": "// A naive approach of Java program of finding nth// palindrome of k digitimport java.util.*; class GFG{// Utility function to reverse the number nstatic int reverseNum(int n){ int rem, rev = 0; while (n > 0) { rem = n % 10; rev = rev * 10 + rem; n /= 10; } return rev;} // Boolean Function to check for palindromic// numberstatic boolean isPalindrom(int num){ return num == reverseNum(num);} // Function for finding nth palindrome of k digitsstatic int nthPalindrome(int n, int k){ // Get the smallest k digit number int num = (int)Math.pow(10, k-1); while (true) { // check the number is palindrom or not if (isPalindrom(num)) --n; // if n'th palindrome found break the loop if (n == 0) break; // Increment number for checking next palindrome ++num; } return num;} // Driver codepublic static void main(String[] args){ int n = 6, k = 5; System.out.println(n + \"th palindrome of \" + k + \" digit = \" + nthPalindrome(n, k)); n = 10; k = 6; System.out.println(n + \"th palindrome of \" + k + \" digit = \" + nthPalindrome(n, k));}} // This code is contributed by mits", "e": 2934, "s": 1734, "text": null }, { "code": "# A naive approach of Python3 program# of finding nth palindrome of k digitimport math;# Utility function to# reverse the number ndef reverseNum(n): rev = 0; while (n): rem = n % 10; rev = (rev * 10) + rem; n = int(n / 10); return rev; # Boolean Function to check for# palindromic numberdef isPalindrom(num): return num == reverseNum(num); # Function for finding nth# palindrome of k digitsdef nthPalindrome(n, k): # Get the smallest k digit number num = math.pow(10, k - 1); while (True): # check the number is # palindrom or not if (isPalindrom(num)): n-=1; # if n'th palindrome found # break the loop if (not n): break; # Increment number for checking # next palindrome num+=1; return int(num); # Driver coden = 6;k = 5;print(n,\"th palindrome of\",k,\"digit =\",nthPalindrome(n, k)); n = 10;k = 6;print(n,\"th palindrome of\",k,\"digit =\",nthPalindrome(n, k)); # This code is contributed by mits", "e": 3963, "s": 2934, "text": null }, { "code": "// A naive approach of C# program of finding nth// palindrome of k digitusing System; class GFG{// Utility function to reverse the number nstatic int reverseNum(int n){ int rem, rev = 0; while (n > 0) { rem = n % 10; rev = rev * 10 + rem; n /= 10; } return rev;} // Boolean Function to check for palindromic// numberstatic bool isPalindrom(int num){ return num == reverseNum(num);} // Function for finding nth palindrome of k digitsstatic int nthPalindrome(int n, int k){ // Get the smallest k digit number int num = (int)Math.Pow(10, k-1); while (true) { // check the number is palindrom or not if (isPalindrom(num)) --n; // if n'th palindrome found break the loop if (n == 0) break; // Increment number for checking next palindrome ++num; } return num;} // Driver codepublic static void Main(){ int n = 6, k = 5; Console.WriteLine(n + \"th palindrome of \" + k + \" digit = \" + nthPalindrome(n, k)); n = 10; k = 6; Console.WriteLine(n + \"th palindrome of \" + k + \" digit = \" + nthPalindrome(n, k));}} // This code is contributed// by Akanksha Rai", "e": 5147, "s": 3963, "text": null }, { "code": "<?php// A naive approach of PHP program// of finding nth palindrome of k digit // Utility function to// reverse the number nfunction reverseNum($n){ $rem; $rev = 0; while ($n) { $rem = $n % 10; $rev = ($rev * 10) + $rem; $n = (int)($n / 10); } return $rev;} // Boolean Function to check for// palindromic numberfunction isPalindrom($num){ return $num == reverseNum($num);} // Function for finding nth// palindrome of k digitsfunction nthPalindrome($n, $k){ // Get the smallest k digit number $num = pow(10, $k - 1); while (true) { // check the number is // palindrom or not if (isPalindrom($num)) --$n; // if n'th palindrome found // break the loop if (!$n) break; // Increment number for checking // next palindrome ++$num; } return $num;} // Driver code$n = 6;$k = 5;echo $n, \"th palindrome of \", $k, \" digit = \", nthPalindrome($n, $k), \"\\n\"; $n = 10;$k = 6;echo $n,\"th palindrome of \", $k, \" digit = \", nthPalindrome($n, $k), \"\\n\"; // This code is contributed by ajit?>", "e": 6302, "s": 5147, "text": null }, { "code": "<script> // A naive approach of Javascript // program of finding nth // palindrome of k digit // Utility function to // reverse the number n function reverseNum(n) { let rem, rev = 0; while (n > 0) { rem = n % 10; rev = rev * 10 + rem; n = parseInt(n / 10); } return rev; } // Boolean Function to // check for palindromic // number function isPalindrom(num) { return num == reverseNum(num); } // Function for finding nth // palindrome of k digits function nthPalindrome(n, k) { // Get the smallest k digit number let num = Math.pow(10, k-1); while (true) { // check the number is // palindrom or not if (isPalindrom(num)) --n; // if n'th palindrome found // break the loop if (n == 0) break; // Increment number for checking // next palindrome ++num; } return num; } let n = 6, k = 5; document.write(n + \"th palindrome of \" + k + \" digit = \" + nthPalindrome(n, k) + \"</br>\"); n = 10; k = 6; document.write(n + \"th palindrome of \" + k + \" digit = \" + nthPalindrome(n, k)); </script>", "e": 7625, "s": 6302, "text": null }, { "code": null, "e": 7634, "s": 7625, "text": "Output: " }, { "code": null, "e": 7704, "s": 7634, "text": "6th palindrome of 5 digit = 10501\n10th palindrome of 6 digit = 109901" }, { "code": null, "e": 7751, "s": 7704, "text": "Time complexity: O(10k) Auxiliary space: O(1) " }, { "code": null, "e": 7770, "s": 7751, "text": "Efficient approach" }, { "code": null, "e": 8176, "s": 7770, "text": "An efficient method is to look for a pattern. According to the property of palindrome first, half digits are the same as the rest half digits in reverse order. Therefore, we only need to look for the first half digits as the rest of them can easily be generated. Let’s take k = 8, the smallest palindrome always starts from 1 as the leading digit and goes like that for the first 4 digits of the number. " }, { "code": null, "e": 8636, "s": 8176, "text": "First half values for k = 8\n1st: 1000\n2nd: 1001\n3rd: 1002\n...\n...\n100th: 1099\n\nSo we can easily write the above sequence for nth\npalindrome as: (n-1) + 1000\nFor k digit number, we can generalize above formula as:\n\nIf k is odd\n=> num = (n-1) + 10k/2\nelse \n=> num = (n-1) + 10k/2 - 1 \n\nNow rest half digits can be expanded by just \nprinting the value of num in reverse order. \nBut before this if k is odd then we have to truncate \nthe last digit of a value num " }, { "code": null, "e": 8664, "s": 8636, "text": "Illustration: n = 6 k = 5 " }, { "code": null, "e": 8844, "s": 8664, "text": "Determine the number of first half digits = floor(5/2) = 2Use formula: num = (6-1) + 102 = 105Expand the rest half digits by reversing the value of num. Final answer will be 10501" }, { "code": null, "e": 8903, "s": 8844, "text": "Determine the number of first half digits = floor(5/2) = 2" }, { "code": null, "e": 8940, "s": 8903, "text": "Use formula: num = (6-1) + 102 = 105" }, { "code": null, "e": 9026, "s": 8940, "text": "Expand the rest half digits by reversing the value of num. Final answer will be 10501" }, { "code": null, "e": 9075, "s": 9026, "text": "Below is the implementation of the above steps " }, { "code": null, "e": 9079, "s": 9075, "text": "C++" }, { "code": null, "e": 9084, "s": 9079, "text": "Java" }, { "code": null, "e": 9092, "s": 9084, "text": "Python3" }, { "code": null, "e": 9095, "s": 9092, "text": "C#" }, { "code": null, "e": 9099, "s": 9095, "text": "PHP" }, { "code": null, "e": 9110, "s": 9099, "text": "Javascript" }, { "code": "// C++ program of finding nth palindrome// of k digit#include<bits/stdc++.h>using namespace std; void nthPalindrome(int n, int k){ // Determine the first half digits int temp = (k & 1) ? (k / 2) : (k/2 - 1); int palindrome = (int)pow(10, temp); palindrome += n - 1; // Print the first half digits of palindrome printf(\"%d\", palindrome); // If k is odd, truncate the last digit if (k & 1) palindrome /= 10; // print the last half digits of palindrome while (palindrome) { printf(\"%d\", palindrome % 10); palindrome /= 10; } printf(\"\\n\");} // Driver codeint main(){ int n = 6, k = 5; printf(\"%dth palindrome of %d digit = \",n ,k); nthPalindrome(n ,k); n = 10, k = 6; printf(\"%dth palindrome of %d digit = \",n ,k); nthPalindrome(n, k); return 0;}", "e": 9938, "s": 9110, "text": null }, { "code": "// Java program of finding nth palindrome// of k digit class GFG{static void nthPalindrome(int n, int k){ // Determine the first half digits int temp = (k & 1)!=0 ? (k / 2) : (k/2 - 1); int palindrome = (int)Math.pow(10, temp); palindrome += n - 1; // Print the first half digits of palindrome System.out.print(palindrome); // If k is odd, truncate the last digit if ((k & 1)>0) palindrome /= 10; // print the last half digits of palindrome while (palindrome>0) { System.out.print(palindrome % 10); palindrome /= 10; } System.out.println(\"\");} // Driver codepublic static void main(String[] args){ int n = 6, k = 5; System.out.print(n+\"th palindrome of \"+k+\" digit = \"); nthPalindrome(n ,k); n = 10; k = 6; System.out.print(n+\"th palindrome of \"+k+\" digit = \"); nthPalindrome(n, k); }}// This code is contributed by mits", "e": 10845, "s": 9938, "text": null }, { "code": "# Python3 program of finding nth palindrome# of k digit def nthPalindrome(n, k): # Determine the first half digits if(k & 1): temp = k // 2 else: temp = k // 2 - 1 palindrome = 10**temp palindrome = palindrome + n - 1 # Print the first half digits of palindrome print(palindrome, end=\"\") # If k is odd, truncate the last digit if(k & 1): palindrome = palindrome // 10 # print the last half digits of palindrome while(palindrome): print(palindrome % 10, end=\"\") palindrome = palindrome // 10 # Driver codeif __name__=='__main__': n = 6 k = 5 print(n, \"th palindrome of\", k, \" digit = \", end=\" \") nthPalindrome(n, k) print() n = 10 k = 6 print(n, \"th palindrome of\", k, \"digit = \",end=\" \") nthPalindrome(n, k) # This code is contributed by# Sanjit_Prasad", "e": 11698, "s": 10845, "text": null }, { "code": "// C# program of finding nth palindrome// of k digitusing System; class GFG{static void nthPalindrome(int n, int k){ // Determine the first half digits int temp = (k & 1) != 0 ? (k / 2) : (k / 2 - 1); int palindrome = (int)Math.Pow(10, temp); palindrome += n - 1; // Print the first half digits // of palindrome Console.Write(palindrome); // If k is odd, truncate the last digit if ((k & 1) > 0) palindrome /= 10; // print the last half digits // of palindrome while (palindrome>0) { Console.Write(palindrome % 10); palindrome /= 10; } Console.WriteLine(\"\");} // Driver codestatic public void Main (){ int n = 6, k = 5; Console.Write(n+\"th palindrome of \" + k + \" digit = \"); nthPalindrome(n, k); n = 10; k = 6; Console.Write(n+\"th palindrome of \" + k + \" digit = \"); nthPalindrome(n, k);}} // This code is contributed by ajit", "e": 12682, "s": 11698, "text": null }, { "code": "<?php// PHP program of finding nth palindrome// of k digit function nthPalindrome($n, $k){ // Determine the first half digits $temp = ($k & 1) ? (int)($k / 2) : (int)($k / 2 - 1); $palindrome = (int)pow(10, $temp); $palindrome += $n - 1; // Print the first half digits of palindrome print($palindrome); // If k is odd, truncate the last digit if ($k & 1) $palindrome = (int)($palindrome / 10); // print the last half digits of palindrome while ($palindrome > 0) { print($palindrome % 10); $palindrome = (int)($palindrome / 10); } print(\"\\n\");} // Driver code$n = 6;$k = 5;print($n.\"th palindrome of $k digit = \");nthPalindrome($n, $k); $n = 10;$k = 6;print($n.\"th palindrome of $k digit = \");nthPalindrome($n, $k); // This code is contributed by mits?>", "e": 13509, "s": 12682, "text": null }, { "code": "<script> // Javascript program of finding nth palindrome of k digit function nthPalindrome(n, k) { // Determine the first half digits let temp = (k & 1) != 0 ? parseInt(k / 2, 10) : (parseInt(k / 2, 10) - 1); let palindrome = parseInt(Math.pow(10, temp), 10); palindrome += n - 1; // Print the first half digits // of palindrome document.write(palindrome); // If k is odd, truncate the last digit if ((k & 1) > 0) palindrome = parseInt(palindrome / 10, 10); // print the last half digits // of palindrome while (palindrome>0) { document.write(palindrome % 10); palindrome = parseInt(palindrome / 10, 10); } document.write(\"\" + \"</br>\"); } let n = 6, k = 5; document.write(n+\"th palindrome of \" + k + \" digit = \"); nthPalindrome(n, k); n = 10; k = 6; document.write(n+\"th palindrome of \" + k + \" digit = \"); nthPalindrome(n, k); </script>", "e": 14537, "s": 13509, "text": null }, { "code": null, "e": 14546, "s": 14537, "text": "Output: " }, { "code": null, "e": 14616, "s": 14546, "text": "6th palindrome of 5 digit = 10501\n10th palindrome of 6 digit = 109901" }, { "code": null, "e": 15192, "s": 14616, "text": "Time complexity: O(k) Auxiliary space: O(1)Reference: http://stackoverflow.com/questions/11925840/how-to-calculate-nth-n-digit-palindrome-efficientlyThis article is contributed by Shubham Bansal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 15206, "s": 15192, "text": "Sanjit_Prasad" }, { "code": null, "e": 15219, "s": 15206, "text": "Mithun Kumar" }, { "code": null, "e": 15225, "s": 15219, "text": "jit_t" }, { "code": null, "e": 15238, "s": 15225, "text": "Akanksha_Rai" }, { "code": null, "e": 15256, "s": 15238, "text": "divyeshrabadiya07" }, { "code": null, "e": 15265, "s": 15256, "text": "mukesh07" }, { "code": null, "e": 15276, "s": 15265, "text": "palindrome" }, { "code": null, "e": 15289, "s": 15276, "text": "Mathematical" }, { "code": null, "e": 15302, "s": 15289, "text": "Mathematical" }, { "code": null, "e": 15313, "s": 15302, "text": "palindrome" }, { "code": null, "e": 15411, "s": 15313, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 15454, "s": 15411, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 15484, "s": 15454, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 15499, "s": 15484, "text": "C++ Data Types" }, { "code": null, "e": 15559, "s": 15499, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 15583, "s": 15559, "text": "Merge two sorted arrays" }, { "code": null, "e": 15602, "s": 15583, "text": "Coin Change | DP-7" }, { "code": null, "e": 15623, "s": 15602, "text": "Operators in C / C++" }, { "code": null, "e": 15637, "s": 15623, "text": "Prime Numbers" }, { "code": null, "e": 15679, "s": 15637, "text": "Program to find GCD or HCF of two numbers" } ]
Python Pillow – Using Image Module
19 Nov, 2021 In this article, we will see how to work with Image Module of PIL in Python. First, let’s see how to install the PIL. Linux: On the Linux terminal type the following: pip install Pillow Installing pip via terminal: sudo apt-get update sudo apt-get install python-pip Here, we will go through some methods and properties provided by the image module which are as follows: Open Image, Save Image, Size of Image, Rotate Image, Crop Image, Resize Image and many more. Let’s discuss this one by one with the help of some examples. To open the image using PIL, we are using the open() method. Syntax: PIL.Image.open(fp, mode=’r’, formats=None) Python3 # importing Image from PILfrom PIL import Image # open an imageimg = Image.open('gfg.png') Output: To retrieve the size of the image we will use the property provided by the Image object i.e; Image.size property. Syntax: Image.size Python3 from PIL import Image with Image.open("gfg.png") as image: width, height = image.size print((width,height)) Output: (200, 200) To save the image, we are using Image.save() method. Syntax: Image.save(fp, format=None, **params) Parameters: fp – A filename (string), pathlib.Path object or file object. format – Optional format override. If omitted, the format to use is determined from the filename extension. If a file object was used instead of a filename, this parameter should always be used. options – Extra parameters to the image writer. Returns: None Python3 from PIL import Image img = Image.open("gfg.png") img.save("logo.jpg") Output: The image rotation needs an angle as a parameter to get the image rotated. Syntax: Image.rotate(angle, resample=0, expand=0, center=None, translate=None, fillcolor=None) Parameters: angle – In degrees counterclockwise. resample – An optional resampling filter. expand – Optional expansion flag. If true, expands the output image to make it large enough to hold the entire rotated image. center – Optional center of rotation (a 2-tuple). Origin is the upper left corner. Default is the center of the image. translate – An optional post-rotate translation (a 2-tuple). fillcolor – An optional color for area outside the rotated image. Python3 from PIL import Image img = Image.open("gfg.png") rot_img = img.rotate(180) rot_img.save("rotated_gfg.png") Output: Original Image Rotated Image The Image.crop(box) takes a 4-tuple (left, upper, right, lower) pixel coordinate, and returns a rectangular region from the used image. Syntax: PIL.Image.crop(box = None) Parameters: box – a 4-tuple defining the left, upper, right, and lower pixel coordinate. Return type: Image (Returns a rectangular region as (left, upper, right, lower)-tuple). Return: An Image object. Python3 from PIL import Image # open image and get sizeimg = Image.open("gfg.jpg")width, height = img.size # cropped image using coordinatesarea = (0, 0, width/2, height/2)crop_img = img.crop(area)crop_img.save("cropped_image.jpg") Output: Cropped Image The Image.resize(size) is used to resize. Here size is provided as a 2-tuple width and height. Syntax: Image.resize(size, resample=0) Parameters: size – The requested size in pixels, as a 2-tuple: (width, height). resample – An optional resampling filter. This can be one of PIL.Image.NEAREST (use nearest neighbour), PIL.Image.BILINEAR (linear interpolation), PIL.Image.BICUBIC (cubic spline interpolation), or PIL.Image.LANCZOS (a high-quality downsampling filter). If omitted, or if the image has mode “1” or “P”, it is set PIL.Image.NEAREST. Returns type: An Image object. Python3 from PIL import Image img = Image.open("gfg.png")width, height = img.size #resizing the image img = img.resize((width//2, height//2)) img.save("resized_picture.png") Output: Resized Image The second argument can be a 2-tuple (specifying the top left corner), or a 4-tuple (left, upper, right, lower) – in this case, the size of the pasted image must match the size of this box region or None which is equivalent to (0, 0). Syntax: PIL.Image.Image.paste(image_1, image_2, box=None, mask=None) OR image_object.paste(image_2, box=None, mask=None) Parameters: image_1/image_object : It the image on which other image is to be pasted. image_2: Source image or pixel value (integer or tuple). box: An optional 4-tuple giving the region to paste into. If a 2-tuple is used instead, it’s treated as the upper left corner. If omitted or None, the source is pasted into the upper left corner. mask: An optional mask image. If an image is given as the second argument and there is no third, the box defaults to (0, 0), and the second argument is interpreted as a mask image. Python3 from PIL import Image img1 = Image.open("gfg.jpg") #pasting img2 on img1img2 = Image.open("gfg.png")img1.paste(img2, (50, 50)) img1.save("pasted_picture.jpg") Output: This feature gives us the mirror image of an image Syntax: Transpose image (flip or rotate in 90 degree steps) Parameters: method – One of PIL.Image.FLIP_LEFT_RIGHT, PIL.Image.FLIP_TOP_BOTTOM, PIL.Image.ROTATE_90, PIL.Image.ROTATE_180, PIL.Image.ROTATE_270 or PIL.Image.TRANSPOSE. Returns type: An Image object. Python3 from PIL import Image img = Image.open("gfg.png") #flipping the image by 180 degree horizontallytransposed_img = img.transpose(Image.FLIP_LEFT_RIGHT) transposed_img.save("transposed.png") Output: Original Transposed Image This method creates a thumbnail of the image that is opened. It does not return a new image object, it makes in-place modifications to the currently opened image object itself. If you do not want to change the original image object, create a copy and then apply this method. This method also evaluates the appropriate to maintain the aspect ratio of the image according to the size passed. Syntax: Image.thumbnail(size, resample=3) Parameters: size – Requested size. resample – Optional resampling filter. Returns Type: An Image object. Python3 from PIL import Image img = Image.open("gfg.png") img.thumbnail((200, 200)) img.save("thumb.png") Output: Thumbnail of 200 x 200 pixels simmytarika5 Picked Python-pil Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n19 Nov, 2021" }, { "code": null, "e": 147, "s": 28, "text": "In this article, we will see how to work with Image Module of PIL in Python. First, let’s see how to install the PIL. " }, { "code": null, "e": 196, "s": 147, "text": "Linux: On the Linux terminal type the following:" }, { "code": null, "e": 215, "s": 196, "text": "pip install Pillow" }, { "code": null, "e": 244, "s": 215, "text": "Installing pip via terminal:" }, { "code": null, "e": 296, "s": 244, "text": "sudo apt-get update\nsudo apt-get install python-pip" }, { "code": null, "e": 400, "s": 296, "text": "Here, we will go through some methods and properties provided by the image module which are as follows:" }, { "code": null, "e": 412, "s": 400, "text": "Open Image," }, { "code": null, "e": 424, "s": 412, "text": "Save Image," }, { "code": null, "e": 439, "s": 424, "text": "Size of Image," }, { "code": null, "e": 453, "s": 439, "text": "Rotate Image," }, { "code": null, "e": 465, "s": 453, "text": "Crop Image," }, { "code": null, "e": 493, "s": 465, "text": "Resize Image and many more." }, { "code": null, "e": 556, "s": 493, "text": " Let’s discuss this one by one with the help of some examples." }, { "code": null, "e": 617, "s": 556, "text": "To open the image using PIL, we are using the open() method." }, { "code": null, "e": 668, "s": 617, "text": "Syntax: PIL.Image.open(fp, mode=’r’, formats=None)" }, { "code": null, "e": 676, "s": 668, "text": "Python3" }, { "code": "# importing Image from PILfrom PIL import Image # open an imageimg = Image.open('gfg.png')", "e": 767, "s": 676, "text": null }, { "code": null, "e": 775, "s": 767, "text": "Output:" }, { "code": null, "e": 889, "s": 775, "text": "To retrieve the size of the image we will use the property provided by the Image object i.e; Image.size property." }, { "code": null, "e": 908, "s": 889, "text": "Syntax: Image.size" }, { "code": null, "e": 916, "s": 908, "text": "Python3" }, { "code": "from PIL import Image with Image.open(\"gfg.png\") as image: width, height = image.size print((width,height))", "e": 1029, "s": 916, "text": null }, { "code": null, "e": 1037, "s": 1029, "text": "Output:" }, { "code": null, "e": 1048, "s": 1037, "text": "(200, 200)" }, { "code": null, "e": 1101, "s": 1048, "text": "To save the image, we are using Image.save() method." }, { "code": null, "e": 1147, "s": 1101, "text": "Syntax: Image.save(fp, format=None, **params)" }, { "code": null, "e": 1159, "s": 1147, "text": "Parameters:" }, { "code": null, "e": 1221, "s": 1159, "text": "fp – A filename (string), pathlib.Path object or file object." }, { "code": null, "e": 1416, "s": 1221, "text": "format – Optional format override. If omitted, the format to use is determined from the filename extension. If a file object was used instead of a filename, this parameter should always be used." }, { "code": null, "e": 1464, "s": 1416, "text": "options – Extra parameters to the image writer." }, { "code": null, "e": 1478, "s": 1464, "text": "Returns: None" }, { "code": null, "e": 1486, "s": 1478, "text": "Python3" }, { "code": "from PIL import Image img = Image.open(\"gfg.png\") img.save(\"logo.jpg\")", "e": 1559, "s": 1486, "text": null }, { "code": null, "e": 1567, "s": 1559, "text": "Output:" }, { "code": null, "e": 1642, "s": 1567, "text": "The image rotation needs an angle as a parameter to get the image rotated." }, { "code": null, "e": 1737, "s": 1642, "text": "Syntax: Image.rotate(angle, resample=0, expand=0, center=None, translate=None, fillcolor=None)" }, { "code": null, "e": 1749, "s": 1737, "text": "Parameters:" }, { "code": null, "e": 1786, "s": 1749, "text": "angle – In degrees counterclockwise." }, { "code": null, "e": 1828, "s": 1786, "text": "resample – An optional resampling filter." }, { "code": null, "e": 1954, "s": 1828, "text": "expand – Optional expansion flag. If true, expands the output image to make it large enough to hold the entire rotated image." }, { "code": null, "e": 2073, "s": 1954, "text": "center – Optional center of rotation (a 2-tuple). Origin is the upper left corner. Default is the center of the image." }, { "code": null, "e": 2134, "s": 2073, "text": "translate – An optional post-rotate translation (a 2-tuple)." }, { "code": null, "e": 2200, "s": 2134, "text": "fillcolor – An optional color for area outside the rotated image." }, { "code": null, "e": 2208, "s": 2200, "text": "Python3" }, { "code": "from PIL import Image img = Image.open(\"gfg.png\") rot_img = img.rotate(180) rot_img.save(\"rotated_gfg.png\")", "e": 2316, "s": 2208, "text": null }, { "code": null, "e": 2324, "s": 2316, "text": "Output:" }, { "code": null, "e": 2339, "s": 2324, "text": "Original Image" }, { "code": null, "e": 2353, "s": 2339, "text": "Rotated Image" }, { "code": null, "e": 2489, "s": 2353, "text": "The Image.crop(box) takes a 4-tuple (left, upper, right, lower) pixel coordinate, and returns a rectangular region from the used image." }, { "code": null, "e": 2524, "s": 2489, "text": "Syntax: PIL.Image.crop(box = None)" }, { "code": null, "e": 2536, "s": 2524, "text": "Parameters:" }, { "code": null, "e": 2613, "s": 2536, "text": "box – a 4-tuple defining the left, upper, right, and lower pixel coordinate." }, { "code": null, "e": 2701, "s": 2613, "text": "Return type: Image (Returns a rectangular region as (left, upper, right, lower)-tuple)." }, { "code": null, "e": 2726, "s": 2701, "text": "Return: An Image object." }, { "code": null, "e": 2734, "s": 2726, "text": "Python3" }, { "code": "from PIL import Image # open image and get sizeimg = Image.open(\"gfg.jpg\")width, height = img.size # cropped image using coordinatesarea = (0, 0, width/2, height/2)crop_img = img.crop(area)crop_img.save(\"cropped_image.jpg\")", "e": 2959, "s": 2734, "text": null }, { "code": null, "e": 2967, "s": 2959, "text": "Output:" }, { "code": null, "e": 2981, "s": 2967, "text": "Cropped Image" }, { "code": null, "e": 3076, "s": 2981, "text": "The Image.resize(size) is used to resize. Here size is provided as a 2-tuple width and height." }, { "code": null, "e": 3115, "s": 3076, "text": "Syntax: Image.resize(size, resample=0)" }, { "code": null, "e": 3127, "s": 3115, "text": "Parameters:" }, { "code": null, "e": 3195, "s": 3127, "text": "size – The requested size in pixels, as a 2-tuple: (width, height)." }, { "code": null, "e": 3527, "s": 3195, "text": "resample – An optional resampling filter. This can be one of PIL.Image.NEAREST (use nearest neighbour), PIL.Image.BILINEAR (linear interpolation), PIL.Image.BICUBIC (cubic spline interpolation), or PIL.Image.LANCZOS (a high-quality downsampling filter). If omitted, or if the image has mode “1” or “P”, it is set PIL.Image.NEAREST." }, { "code": null, "e": 3558, "s": 3527, "text": "Returns type: An Image object." }, { "code": null, "e": 3566, "s": 3558, "text": "Python3" }, { "code": "from PIL import Image img = Image.open(\"gfg.png\")width, height = img.size #resizing the image img = img.resize((width//2, height//2)) img.save(\"resized_picture.png\")", "e": 3741, "s": 3566, "text": null }, { "code": null, "e": 3749, "s": 3741, "text": "Output:" }, { "code": null, "e": 3763, "s": 3749, "text": "Resized Image" }, { "code": null, "e": 3999, "s": 3763, "text": "The second argument can be a 2-tuple (specifying the top left corner), or a 4-tuple (left, upper, right, lower) – in this case, the size of the pasted image must match the size of this box region or None which is equivalent to (0, 0). " }, { "code": null, "e": 4068, "s": 3999, "text": "Syntax: PIL.Image.Image.paste(image_1, image_2, box=None, mask=None)" }, { "code": null, "e": 4072, "s": 4068, "text": "OR " }, { "code": null, "e": 4134, "s": 4072, "text": " image_object.paste(image_2, box=None, mask=None)" }, { "code": null, "e": 4146, "s": 4134, "text": "Parameters:" }, { "code": null, "e": 4220, "s": 4146, "text": "image_1/image_object : It the image on which other image is to be pasted." }, { "code": null, "e": 4277, "s": 4220, "text": "image_2: Source image or pixel value (integer or tuple)." }, { "code": null, "e": 4473, "s": 4277, "text": "box: An optional 4-tuple giving the region to paste into. If a 2-tuple is used instead, it’s treated as the upper left corner. If omitted or None, the source is pasted into the upper left corner." }, { "code": null, "e": 4503, "s": 4473, "text": "mask: An optional mask image." }, { "code": null, "e": 4654, "s": 4503, "text": "If an image is given as the second argument and there is no third, the box defaults to (0, 0), and the second argument is interpreted as a mask image." }, { "code": null, "e": 4662, "s": 4654, "text": "Python3" }, { "code": "from PIL import Image img1 = Image.open(\"gfg.jpg\") #pasting img2 on img1img2 = Image.open(\"gfg.png\")img1.paste(img2, (50, 50)) img1.save(\"pasted_picture.jpg\")", "e": 4821, "s": 4662, "text": null }, { "code": null, "e": 4830, "s": 4821, "text": "Output: " }, { "code": null, "e": 4881, "s": 4830, "text": "This feature gives us the mirror image of an image" }, { "code": null, "e": 4941, "s": 4881, "text": "Syntax: Transpose image (flip or rotate in 90 degree steps)" }, { "code": null, "e": 4953, "s": 4941, "text": "Parameters:" }, { "code": null, "e": 5111, "s": 4953, "text": "method – One of PIL.Image.FLIP_LEFT_RIGHT, PIL.Image.FLIP_TOP_BOTTOM, PIL.Image.ROTATE_90, PIL.Image.ROTATE_180, PIL.Image.ROTATE_270 or PIL.Image.TRANSPOSE." }, { "code": null, "e": 5142, "s": 5111, "text": "Returns type: An Image object." }, { "code": null, "e": 5150, "s": 5142, "text": "Python3" }, { "code": "from PIL import Image img = Image.open(\"gfg.png\") #flipping the image by 180 degree horizontallytransposed_img = img.transpose(Image.FLIP_LEFT_RIGHT) transposed_img.save(\"transposed.png\")", "e": 5350, "s": 5150, "text": null }, { "code": null, "e": 5358, "s": 5350, "text": "Output:" }, { "code": null, "e": 5367, "s": 5358, "text": "Original" }, { "code": null, "e": 5384, "s": 5367, "text": "Transposed Image" }, { "code": null, "e": 5774, "s": 5384, "text": "This method creates a thumbnail of the image that is opened. It does not return a new image object, it makes in-place modifications to the currently opened image object itself. If you do not want to change the original image object, create a copy and then apply this method. This method also evaluates the appropriate to maintain the aspect ratio of the image according to the size passed." }, { "code": null, "e": 5816, "s": 5774, "text": "Syntax: Image.thumbnail(size, resample=3)" }, { "code": null, "e": 5828, "s": 5816, "text": "Parameters:" }, { "code": null, "e": 5851, "s": 5828, "text": "size – Requested size." }, { "code": null, "e": 5890, "s": 5851, "text": "resample – Optional resampling filter." }, { "code": null, "e": 5921, "s": 5890, "text": "Returns Type: An Image object." }, { "code": null, "e": 5929, "s": 5921, "text": "Python3" }, { "code": "from PIL import Image img = Image.open(\"gfg.png\") img.thumbnail((200, 200)) img.save(\"thumb.png\")", "e": 6027, "s": 5929, "text": null }, { "code": null, "e": 6035, "s": 6027, "text": "Output:" }, { "code": null, "e": 6065, "s": 6035, "text": "Thumbnail of 200 x 200 pixels" }, { "code": null, "e": 6078, "s": 6065, "text": "simmytarika5" }, { "code": null, "e": 6085, "s": 6078, "text": "Picked" }, { "code": null, "e": 6096, "s": 6085, "text": "Python-pil" }, { "code": null, "e": 6103, "s": 6096, "text": "Python" } ]
How to handle Frames/iFrames in Selenium with Python
08 Jul, 2022 Selenium is an effective device for controlling an internet browser through the program. It is purposeful for all browsers, works on all fundamental OS and its scripts are written in numerous languages i.e Python, Java, C#, etc, we can be running with Python. HTML outlines are utilized to isolate your program window into numerous segments where each part can stack a different HTML report. An assortment of edges in the program window is known as a frame set. The window is partitioned into outlines likewise the tables are composed: into lines and segments. Requirement: You need to install chromedriver and set path. Click here to download.for more information follows this link. Handle Frames/iFrames:- switch_to.frame(name) Process: This web page is divided into three frames, left top (1st frame) and left bottom(2nd frame) and the third frame. All the frames interconnected. Then we perform these actions by selenium: First of all, switch to the default frame to the first frame. Then find the element using link text method Go back to the default frame. Then go to the 2nd frame Find element using the link text method Go back to the default frame Then switch to the 3rd frame. Then find element by x path. Implementation: Python3 # importing the modulesfrom selenium import webdriverfrom selenium.webdriver.support.ui import Selectimport time # using chrome driverdriver = webdriver.Chrome() # web page urldriver.get("https://www.selenium.dev/selenium/docs/api/java/index.html") # switch to 1st framedriver.switch_to.frame("packageListFrame") # click on 1st framedriver.find_element_by_link_text("org.openqa.selenium.opera").click() # back to default web page framedriver.switch_to.default_content() # switch to 2nd framedriver.switch_to.frame("packageFrame") # click on 2nd framedriver.find_element_by_link_text("OperaOptions").click() # back to default web page framedriver.switch_to.default_content() # switch to 3rd framedriver.switch_to.frame("classFrame") # click on 2nd framedriver.find_element_by_xpath('/html/body/div[1]/ul/li[4]/a').click()time.sleep(4) Output:– mitalibhola94 Python-selenium Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Iterate over a list in Python Rotate axis tick labels in Seaborn and Matplotlib Enumerate() in Python Deque in Python Stack in Python Python Dictionary sum() function in Python Print lists in Python (5 Different Ways) Different ways to create Pandas Dataframe Queue in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Jul, 2022" }, { "code": null, "e": 288, "s": 28, "text": "Selenium is an effective device for controlling an internet browser through the program. It is purposeful for all browsers, works on all fundamental OS and its scripts are written in numerous languages i.e Python, Java, C#, etc, we can be running with Python." }, { "code": null, "e": 589, "s": 288, "text": "HTML outlines are utilized to isolate your program window into numerous segments where each part can stack a different HTML report. An assortment of edges in the program window is known as a frame set. The window is partitioned into outlines likewise the tables are composed: into lines and segments." }, { "code": null, "e": 712, "s": 589, "text": "Requirement: You need to install chromedriver and set path. Click here to download.for more information follows this link." }, { "code": null, "e": 737, "s": 712, "text": " Handle Frames/iFrames:-" }, { "code": null, "e": 759, "s": 737, "text": "switch_to.frame(name)" }, { "code": null, "e": 768, "s": 759, "text": "Process:" }, { "code": null, "e": 955, "s": 768, "text": "This web page is divided into three frames, left top (1st frame) and left bottom(2nd frame) and the third frame. All the frames interconnected. Then we perform these actions by selenium:" }, { "code": null, "e": 1017, "s": 955, "text": "First of all, switch to the default frame to the first frame." }, { "code": null, "e": 1062, "s": 1017, "text": "Then find the element using link text method" }, { "code": null, "e": 1092, "s": 1062, "text": "Go back to the default frame." }, { "code": null, "e": 1117, "s": 1092, "text": "Then go to the 2nd frame" }, { "code": null, "e": 1157, "s": 1117, "text": "Find element using the link text method" }, { "code": null, "e": 1186, "s": 1157, "text": "Go back to the default frame" }, { "code": null, "e": 1216, "s": 1186, "text": "Then switch to the 3rd frame." }, { "code": null, "e": 1245, "s": 1216, "text": "Then find element by x path." }, { "code": null, "e": 1261, "s": 1245, "text": "Implementation:" }, { "code": null, "e": 1269, "s": 1261, "text": "Python3" }, { "code": "# importing the modulesfrom selenium import webdriverfrom selenium.webdriver.support.ui import Selectimport time # using chrome driverdriver = webdriver.Chrome() # web page urldriver.get(\"https://www.selenium.dev/selenium/docs/api/java/index.html\") # switch to 1st framedriver.switch_to.frame(\"packageListFrame\") # click on 1st framedriver.find_element_by_link_text(\"org.openqa.selenium.opera\").click() # back to default web page framedriver.switch_to.default_content() # switch to 2nd framedriver.switch_to.frame(\"packageFrame\") # click on 2nd framedriver.find_element_by_link_text(\"OperaOptions\").click() # back to default web page framedriver.switch_to.default_content() # switch to 3rd framedriver.switch_to.frame(\"classFrame\") # click on 2nd framedriver.find_element_by_xpath('/html/body/div[1]/ul/li[4]/a').click()time.sleep(4)", "e": 2105, "s": 1269, "text": null }, { "code": null, "e": 2114, "s": 2105, "text": "Output:–" }, { "code": null, "e": 2128, "s": 2114, "text": "mitalibhola94" }, { "code": null, "e": 2144, "s": 2128, "text": "Python-selenium" }, { "code": null, "e": 2151, "s": 2144, "text": "Python" }, { "code": null, "e": 2249, "s": 2151, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2279, "s": 2249, "text": "Iterate over a list in Python" }, { "code": null, "e": 2329, "s": 2279, "text": "Rotate axis tick labels in Seaborn and Matplotlib" }, { "code": null, "e": 2351, "s": 2329, "text": "Enumerate() in Python" }, { "code": null, "e": 2367, "s": 2351, "text": "Deque in Python" }, { "code": null, "e": 2383, "s": 2367, "text": "Stack in Python" }, { "code": null, "e": 2401, "s": 2383, "text": "Python Dictionary" }, { "code": null, "e": 2426, "s": 2401, "text": "sum() function in Python" }, { "code": null, "e": 2467, "s": 2426, "text": "Print lists in Python (5 Different Ways)" }, { "code": null, "e": 2509, "s": 2467, "text": "Different ways to create Pandas Dataframe" } ]
Number of permutation with K inversions
12 Jan, 2022 Given an array, an inversion is defined as a pair a[i], a[j] such that a[i] > a[j] and i < j. We are given two numbers N and k, we need to tell how many permutations of the first N number have exactly K inversion. Examples: Input : N = 3, K = 1 Output : 2 Explanation : Total Permutation of first N number, 123, 132, 213, 231, 312, 321 Permutation with 1 inversion : 132 and 213 Input : N = 4, K = 2 Output : 5 A Naïve way to solve this problem is noting down all permutations then checking the count of inversion in them but iterating through permutation itself will take O(N!) time, which is too large. We can solve this problem using a dynamic programming approach. Below is the recursive formula. If N is 0, Count(0, K) = 0 If K is 0, Count(N, 0) = 1 (Only sorted array) In general case, If we have N number and require K inversion, Count(N, K) = Count(N - 1, K) + Count(N – 1, K - 1) + Count(N – 1, K – 2) + .... + Count(N – 1, 0) How does the above recursive formula work? If we have N number and want to have K permutation and suppose all permutation of (N – 1) number are written somewhere, the new number (Nth number and largest) need to be placed in all permutation of (N – 1) number and those whose inversion count becomes K after adding this number should be added in our answer. Now take those sets of permutation of (N – 1) number which has let (K – 3) inversion, now we can place this new largest number at position 3 from last, then inversion count will be K, so count(N – 1, K – 3) should be added to our answer, the same argument can be given for another inversion also and we will reach to above recursion as the final answer. The below code is written following the above recursion in a memorization way. C++ Java Python3 C# PHP Javascript // C++ program to find number of permutation// with K inversion using Memoization#include <bits/stdc++.h>using namespace std; // Limit on N and Kconst int M = 100; // 2D array memo for stopping// solving same problem againint memo[M][M]; // method recursively calculates// permutation with K inversionint numberOfPermWithKInversion(int N, int K){ // base cases if (N == 0) return 0; if (K == 0) return 1; // if already solved then // return result directly if (memo[N][K] != 0) return memo[N][K]; // calling recursively all subproblem // of permutation size N - 1 int sum = 0; for (int i = 0; i <= K; i++) { // Call recursively only // if total inversion // to be made are less // than size if (i <= N - 1) sum += numberOfPermWithKInversion(N - 1, K - i); } // store result into memo memo[N][K] = sum; return sum;} // Driver codeint main(){ int N = 4; int K = 2; cout << numberOfPermWithKInversion(N, K); return 0;} // Java program to find number of permutation with// K inversion using Memoization import java.io.*; class GFG { // Limit on N and K static int M = 100; // 2D array memo for stopping solving same problem // again static int memo[][] = new int[M][M]; // method recursively calculates permutation with // K inversion static int numberOfPermWithKInversion(int N, int K) { // base cases if (N == 0) return 0; if (K == 0) return 1; // if already solved then return result directly if (memo[N][K] != 0) return memo[N][K]; // calling recursively all subproblem of // permutation size N - 1 int sum = 0; for (int i = 0; i <= K; i++) { // Call recursively only if total inversion // to be made are less than size if (i <= N - 1) sum += numberOfPermWithKInversion(N - 1, K - i); } // store result into memo memo[N][K] = sum; return sum; } // Driver code to test above methods public static void main(String[] args) { int N = 4; int K = 2; System.out.println(numberOfPermWithKInversion(N, K)); }} // This code is contributed by vt_m. # Python3 program to find number of permutation# with K inversion using Memoization # Limit on N and KM = 100 # 2D array memo for stopping # solving same problem againmemo = [[0 for i in range(M)] for j in range(M)] # method recursively calculates# permutation with K inversiondef numberOfPermWithKInversion(N, K): # Base cases if (N == 0): return 0 if (K == 0): return 1 # If already solved then # return result directly if (memo[N][K] != 0): return memo[N][K] # Calling recursively all subproblem # of permutation size N - 1 sum = 0 for i in range(K + 1): # Call recursively only if # total inversion to be made # are less than size if (i <= N - 1): sum += numberOfPermWithKInversion(N - 1, K - i) # store result into memo memo[N][K] = sum return sum # Driver codeN = 4; K = 2print(numberOfPermWithKInversion(N, K)) # This code is contributed by Anant Agarwal. // C# program to find number of// permutation with K inversion// using Memoizationusing System; class GFG{ // Limit on N and Kstatic int M = 100; // 2D array memo for stopping// solving same problem againstatic int [,]memo = new int[M, M]; // method recursively calculates// permutation with K inversionstatic int numberOfPermWithKInversion(int N, int K){ // base cases if (N == 0) return 0; if (K == 0) return 1; // if already solved then // return result directly if (memo[N, K] != 0) return memo[N, K]; // calling recursively all // subproblem of permutation // size N - 1 int sum = 0; for (int i = 0; i <= K; i++) { // Call recursively only if // total inversion to be // made are less than size if (i <= N - 1) sum += numberOfPermWithKInversion(N - 1, K - i); } // store result into memo memo[N, K] = sum; return sum;} // Driver Codestatic public void Main (){ int N = 4; int K = 2; Console.WriteLine(numberOfPermWithKInversion(N, K));}} // This code is contributed by ajit <?php// PHP program to find number of permutation// with K inversion using Memoization // method recursively calculates// permutation with K inversionfunction numberOfPermWithKInversion($N, $K){ $memo = array(); // base cases if ($N == 0) return 0; if ($K == 0) return 1; // if already solved then // return result directly if ($memo[$N][$K] != 0) return $memo[$N][$K]; // calling recursively all subproblem // of permutation size N - 1 $sum = 0; for ($i = 0; $i <= $K; $i++) { // Call recursively only // if total inversion // to be made are less // than size if ($i <= $N - 1) $sum += numberOfPermWithKInversion($N - 1, $K - $i); } // store result into memo $memo[$N][$K] = $sum; return $sum;} // Driver code$N = 4;$K = 2;echo numberOfPermWithKInversion($N, $K); // This code is contributed// by Akanksha Rai(Abby_akku)?> <script> // Javascript program to find number of// permutation with K inversion using// Memoization // Limit on N and Klet M = 100; // 2D array memo for stopping solving// same problem againlet memo = new Array(M);for(let i = 0; i < M; i++){ memo[i] = new Array(M); for(let j = 0; j < M; j++) { memo[i][j] = 0; }} // Method recursively calculates permutation// with K inversionfunction numberOfPermWithKInversion(N, K){ // base cases if (N == 0) return 0; if (K == 0) return 1; // If already solved then return // result directly if (memo[N][K] != 0) return memo[N][K]; // Calling recursively all subproblem of // permutation size N - 1 let sum = 0; for(let i = 0; i <= K; i++) { // Call recursively only if total inversion // to be made are less than size if (i <= N - 1) sum += numberOfPermWithKInversion( N - 1, K - i); } // Store result into memo memo[N][K] = sum; return sum;} // Driver codelet N = 4;let K = 2; document.write(numberOfPermWithKInversion(N, K)); // This code is contributed by divyesh072019 </script> 5 Time Complexity: O(N*N*K) Optimized Approach: Using Tabulation and cumulative sum C++ // C++ program to find number of permutation// with K inversions #include <bits/stdc++.h>using namespace std; int numberOfPermWithKInversions(int N, int K) { vector<vector<int>> dp(N+1,vector<int>(K+1)); // As for k=0, number of permutations is 1 for every N for(int i = 1; i <= N; i++) dp[i][0] = 1; // Using Dynamic Programming with cumulative sum for(int i = 1; i <= N; i++) { for(int j = 1; j <= K; j++) { // This is same as val = dp[i-1][j] - dp[i-1][j-i] // i.e. dp[i-1][j........j-i], just taking care of // boundaries int val = dp[i-1][j]; if(j >= i) val -= dp[i-1][j-i]; dp[i][j] = dp[i][j-1] + val; } } // And, in the end calculate the dp[n][k] // which is dp[n][k]-dp[n][k-1] int ans = dp[N][K]; if(K >= 1) ans -= dp[N][K-1]; return ans;} int main() { int N = 4; int K = 2; cout << numberOfPermWithKInversions(N,K) << "\n"; return 0;} 5 Time Complexity: O(N*K) This article is contributed by Utkarsh Trivedi and Ankit Kumar Sharma. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. jit_t Akanksha_Rai divyesh072019 anonysharma chhabradhanvi inversion permutation Dynamic Programming Dynamic Programming permutation Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Subset Sum Problem | DP-25 Longest Palindromic Substring | Set 1 Floyd Warshall Algorithm | DP-16 Coin Change | DP-7 Matrix Chain Multiplication | DP-8 Sieve of Eratosthenes Bellman–Ford Algorithm | DP-23 Minimum number of jumps to reach end Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Find minimum number of coins that make a given value
[ { "code": null, "e": 52, "s": 24, "text": "\n12 Jan, 2022" }, { "code": null, "e": 266, "s": 52, "text": "Given an array, an inversion is defined as a pair a[i], a[j] such that a[i] > a[j] and i < j. We are given two numbers N and k, we need to tell how many permutations of the first N number have exactly K inversion." }, { "code": null, "e": 277, "s": 266, "text": "Examples: " }, { "code": null, "e": 469, "s": 277, "text": "Input : N = 3, K = 1\nOutput : 2\nExplanation : \nTotal Permutation of first N number,\n123, 132, 213, 231, 312, 321\nPermutation with 1 inversion : 132 and 213\n\nInput : N = 4, K = 2\nOutput : 5" }, { "code": null, "e": 665, "s": 469, "text": "A Naïve way to solve this problem is noting down all permutations then checking the count of inversion in them but iterating through permutation itself will take O(N!) time, which is too large. " }, { "code": null, "e": 763, "s": 665, "text": "We can solve this problem using a dynamic programming approach. Below is the recursive formula. " }, { "code": null, "e": 1062, "s": 763, "text": "If N is 0, Count(0, K) = 0\n\nIf K is 0, Count(N, 0) = 1 (Only sorted array)\n\nIn general case, \nIf we have N number and require K inversion, \nCount(N, K) = Count(N - 1, K) + \n Count(N – 1, K - 1) + \n Count(N – 1, K – 2) + \n .... + \n Count(N – 1, 0)" }, { "code": null, "e": 1772, "s": 1062, "text": "How does the above recursive formula work? If we have N number and want to have K permutation and suppose all permutation of (N – 1) number are written somewhere, the new number (Nth number and largest) need to be placed in all permutation of (N – 1) number and those whose inversion count becomes K after adding this number should be added in our answer. Now take those sets of permutation of (N – 1) number which has let (K – 3) inversion, now we can place this new largest number at position 3 from last, then inversion count will be K, so count(N – 1, K – 3) should be added to our answer, the same argument can be given for another inversion also and we will reach to above recursion as the final answer." }, { "code": null, "e": 1853, "s": 1772, "text": "The below code is written following the above recursion in a memorization way. " }, { "code": null, "e": 1857, "s": 1853, "text": "C++" }, { "code": null, "e": 1862, "s": 1857, "text": "Java" }, { "code": null, "e": 1870, "s": 1862, "text": "Python3" }, { "code": null, "e": 1873, "s": 1870, "text": "C#" }, { "code": null, "e": 1877, "s": 1873, "text": "PHP" }, { "code": null, "e": 1888, "s": 1877, "text": "Javascript" }, { "code": "// C++ program to find number of permutation// with K inversion using Memoization#include <bits/stdc++.h>using namespace std; // Limit on N and Kconst int M = 100; // 2D array memo for stopping// solving same problem againint memo[M][M]; // method recursively calculates// permutation with K inversionint numberOfPermWithKInversion(int N, int K){ // base cases if (N == 0) return 0; if (K == 0) return 1; // if already solved then // return result directly if (memo[N][K] != 0) return memo[N][K]; // calling recursively all subproblem // of permutation size N - 1 int sum = 0; for (int i = 0; i <= K; i++) { // Call recursively only // if total inversion // to be made are less // than size if (i <= N - 1) sum += numberOfPermWithKInversion(N - 1, K - i); } // store result into memo memo[N][K] = sum; return sum;} // Driver codeint main(){ int N = 4; int K = 2; cout << numberOfPermWithKInversion(N, K); return 0;}", "e": 2983, "s": 1888, "text": null }, { "code": "// Java program to find number of permutation with// K inversion using Memoization import java.io.*; class GFG { // Limit on N and K static int M = 100; // 2D array memo for stopping solving same problem // again static int memo[][] = new int[M][M]; // method recursively calculates permutation with // K inversion static int numberOfPermWithKInversion(int N, int K) { // base cases if (N == 0) return 0; if (K == 0) return 1; // if already solved then return result directly if (memo[N][K] != 0) return memo[N][K]; // calling recursively all subproblem of // permutation size N - 1 int sum = 0; for (int i = 0; i <= K; i++) { // Call recursively only if total inversion // to be made are less than size if (i <= N - 1) sum += numberOfPermWithKInversion(N - 1, K - i); } // store result into memo memo[N][K] = sum; return sum; } // Driver code to test above methods public static void main(String[] args) { int N = 4; int K = 2; System.out.println(numberOfPermWithKInversion(N, K)); }} // This code is contributed by vt_m.", "e": 4324, "s": 2983, "text": null }, { "code": "# Python3 program to find number of permutation# with K inversion using Memoization # Limit on N and KM = 100 # 2D array memo for stopping # solving same problem againmemo = [[0 for i in range(M)] for j in range(M)] # method recursively calculates# permutation with K inversiondef numberOfPermWithKInversion(N, K): # Base cases if (N == 0): return 0 if (K == 0): return 1 # If already solved then # return result directly if (memo[N][K] != 0): return memo[N][K] # Calling recursively all subproblem # of permutation size N - 1 sum = 0 for i in range(K + 1): # Call recursively only if # total inversion to be made # are less than size if (i <= N - 1): sum += numberOfPermWithKInversion(N - 1, K - i) # store result into memo memo[N][K] = sum return sum # Driver codeN = 4; K = 2print(numberOfPermWithKInversion(N, K)) # This code is contributed by Anant Agarwal.", "e": 5287, "s": 4324, "text": null }, { "code": "// C# program to find number of// permutation with K inversion// using Memoizationusing System; class GFG{ // Limit on N and Kstatic int M = 100; // 2D array memo for stopping// solving same problem againstatic int [,]memo = new int[M, M]; // method recursively calculates// permutation with K inversionstatic int numberOfPermWithKInversion(int N, int K){ // base cases if (N == 0) return 0; if (K == 0) return 1; // if already solved then // return result directly if (memo[N, K] != 0) return memo[N, K]; // calling recursively all // subproblem of permutation // size N - 1 int sum = 0; for (int i = 0; i <= K; i++) { // Call recursively only if // total inversion to be // made are less than size if (i <= N - 1) sum += numberOfPermWithKInversion(N - 1, K - i); } // store result into memo memo[N, K] = sum; return sum;} // Driver Codestatic public void Main (){ int N = 4; int K = 2; Console.WriteLine(numberOfPermWithKInversion(N, K));}} // This code is contributed by ajit", "e": 6483, "s": 5287, "text": null }, { "code": "<?php// PHP program to find number of permutation// with K inversion using Memoization // method recursively calculates// permutation with K inversionfunction numberOfPermWithKInversion($N, $K){ $memo = array(); // base cases if ($N == 0) return 0; if ($K == 0) return 1; // if already solved then // return result directly if ($memo[$N][$K] != 0) return $memo[$N][$K]; // calling recursively all subproblem // of permutation size N - 1 $sum = 0; for ($i = 0; $i <= $K; $i++) { // Call recursively only // if total inversion // to be made are less // than size if ($i <= $N - 1) $sum += numberOfPermWithKInversion($N - 1, $K - $i); } // store result into memo $memo[$N][$K] = $sum; return $sum;} // Driver code$N = 4;$K = 2;echo numberOfPermWithKInversion($N, $K); // This code is contributed// by Akanksha Rai(Abby_akku)?>", "e": 7483, "s": 6483, "text": null }, { "code": "<script> // Javascript program to find number of// permutation with K inversion using// Memoization // Limit on N and Klet M = 100; // 2D array memo for stopping solving// same problem againlet memo = new Array(M);for(let i = 0; i < M; i++){ memo[i] = new Array(M); for(let j = 0; j < M; j++) { memo[i][j] = 0; }} // Method recursively calculates permutation// with K inversionfunction numberOfPermWithKInversion(N, K){ // base cases if (N == 0) return 0; if (K == 0) return 1; // If already solved then return // result directly if (memo[N][K] != 0) return memo[N][K]; // Calling recursively all subproblem of // permutation size N - 1 let sum = 0; for(let i = 0; i <= K; i++) { // Call recursively only if total inversion // to be made are less than size if (i <= N - 1) sum += numberOfPermWithKInversion( N - 1, K - i); } // Store result into memo memo[N][K] = sum; return sum;} // Driver codelet N = 4;let K = 2; document.write(numberOfPermWithKInversion(N, K)); // This code is contributed by divyesh072019 </script>", "e": 8660, "s": 7483, "text": null }, { "code": null, "e": 8662, "s": 8660, "text": "5" }, { "code": null, "e": 8688, "s": 8662, "text": "Time Complexity: O(N*N*K)" }, { "code": null, "e": 8744, "s": 8688, "text": "Optimized Approach: Using Tabulation and cumulative sum" }, { "code": null, "e": 8748, "s": 8744, "text": "C++" }, { "code": "// C++ program to find number of permutation// with K inversions #include <bits/stdc++.h>using namespace std; int numberOfPermWithKInversions(int N, int K) { vector<vector<int>> dp(N+1,vector<int>(K+1)); // As for k=0, number of permutations is 1 for every N for(int i = 1; i <= N; i++) dp[i][0] = 1; // Using Dynamic Programming with cumulative sum for(int i = 1; i <= N; i++) { for(int j = 1; j <= K; j++) { // This is same as val = dp[i-1][j] - dp[i-1][j-i] // i.e. dp[i-1][j........j-i], just taking care of // boundaries int val = dp[i-1][j]; if(j >= i) val -= dp[i-1][j-i]; dp[i][j] = dp[i][j-1] + val; } } // And, in the end calculate the dp[n][k] // which is dp[n][k]-dp[n][k-1] int ans = dp[N][K]; if(K >= 1) ans -= dp[N][K-1]; return ans;} int main() { int N = 4; int K = 2; cout << numberOfPermWithKInversions(N,K) << \"\\n\"; return 0;}", "e": 9788, "s": 8748, "text": null }, { "code": null, "e": 9790, "s": 9788, "text": "5" }, { "code": null, "e": 9814, "s": 9790, "text": "Time Complexity: O(N*K)" }, { "code": null, "e": 10261, "s": 9814, "text": "This article is contributed by Utkarsh Trivedi and Ankit Kumar Sharma. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 10267, "s": 10261, "text": "jit_t" }, { "code": null, "e": 10280, "s": 10267, "text": "Akanksha_Rai" }, { "code": null, "e": 10294, "s": 10280, "text": "divyesh072019" }, { "code": null, "e": 10306, "s": 10294, "text": "anonysharma" }, { "code": null, "e": 10320, "s": 10306, "text": "chhabradhanvi" }, { "code": null, "e": 10330, "s": 10320, "text": "inversion" }, { "code": null, "e": 10342, "s": 10330, "text": "permutation" }, { "code": null, "e": 10362, "s": 10342, "text": "Dynamic Programming" }, { "code": null, "e": 10382, "s": 10362, "text": "Dynamic Programming" }, { "code": null, "e": 10394, "s": 10382, "text": "permutation" }, { "code": null, "e": 10492, "s": 10394, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 10519, "s": 10492, "text": "Subset Sum Problem | DP-25" }, { "code": null, "e": 10557, "s": 10519, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 10590, "s": 10557, "text": "Floyd Warshall Algorithm | DP-16" }, { "code": null, "e": 10609, "s": 10590, "text": "Coin Change | DP-7" }, { "code": null, "e": 10644, "s": 10609, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 10666, "s": 10644, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 10697, "s": 10666, "text": "Bellman–Ford Algorithm | DP-23" }, { "code": null, "e": 10734, "s": 10697, "text": "Minimum number of jumps to reach end" }, { "code": null, "e": 10802, "s": 10734, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" } ]
How to move a ggplot2 legend with multiple rows to the bottom of a plot in R
23 May, 2021 In this article, we are going to see how to draw ggplot2 legend at the bottom and with two Rows in R Programming Language. First, we have to create a simple data plot with legend. Here we will draw a Simple Scatter plot. First, load the ggplot2 package by using library() function. library("ggplot2") Create a DataFrame for example. Here we create a simple DataFrame with three variables named Year, Points, and Users and then assign it to the data object. R library("ggplot2") # Create a DataFramedata <- data.frame(Year = c(2011, 2012, 2013, 2014, 2015), Points = c(30, 20, 15, 35, 50), Users = c("user1", "user2", "user3", "user4", "user5"))print(data) Output: dataframe For Create an R plot, we use ggplot() function and for make it scatter plot we add geom_point() function to ggplot() function. assign this whole plot to gplot data object. Code: R # Load Packagelibrary("ggplot2") # Create a DataFrame data <- data.frame(Year = c(2011, 2012, 2013, 2014, 2015), Points = c(30, 20, 15, 35, 50), Users = c("user1", "user2", "user3", "user4", "user5")) # Create a Scatter Plot and assign it # to gplot data objectgplot <- ggplot(data, aes(Year, Points, color = Users)) + geom_point(size = 7)gplot Output: Simple Scatter Plot with legend To draw ggplot2 legend at the bottom of the plot, we simply add the theme() function to geom_point() function. Syntax : theme(legend.position) Parameter : In General, theme() function has many parameters to specify the theme of the plot but here we use only legend.position parameter which specify the position of Legend. Return : Theme of the plot. We can specify the value of legend.position parameter from left, right, top and bottom. To draw legend at bottom of graph, we use ‘bottom’ as a value of legend.position parameter. R # Load Packagelibrary(ggplot2) # Create a DataFrame For plotdata <- data.frame(Year = c(2011, 2012, 2013, 2014, 2015), Points = c(30, 20, 15, 35, 50), Users = c("user1", "user2", "user3", "user4", "user5")) # Create a simple scatter plot # with legend at bottom.ggplot(data, aes(Year, Points, color = Users)) + geom_point(size = 7)+ theme(legend.position = "bottom") Output: Scatter Plot with Legend at bottom If we want to draw ggplot2 Legend at the bottom of the plot with two rows, we have to add guides and guide_legend functions to the theme() function. Inside guides() function, we take parameter named color, which has call to guide_legend() guide function as value. Inside guide_legend() function, we take an argument called nrow, which has the desired number of rows of legend as value. Syntax : guide_legend(nrow) Parameter : nrow : The Desired Number of rows of legend. Return : Legend Guides for various scales Code: R # Load Packagelibrary(ggplot2) # Create a DataFrame For plotdata <- data.frame(Year = c(2011, 2012, 2013, 2014, 2015), Points = c(30, 20, 15, 35, 50), Users = c("user1", "user2", "user3", "user4", "user5")) # Create a simple scatter plot with# legend at bottom and with Two Rows.# Specifies the Number of legend Rowsggplot(data, aes(Year, Points, color = Users)) + geom_point(size = 7)+ theme(legend.position = "bottom")+ guides(color = guide_legend(nrow = 2)) Output: Scatter plot with Legend at bottom with Two Rows Picked R-ggplot R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n23 May, 2021" }, { "code": null, "e": 249, "s": 28, "text": "In this article, we are going to see how to draw ggplot2 legend at the bottom and with two Rows in R Programming Language. First, we have to create a simple data plot with legend. Here we will draw a Simple Scatter plot." }, { "code": null, "e": 310, "s": 249, "text": "First, load the ggplot2 package by using library() function." }, { "code": null, "e": 330, "s": 310, "text": " library(\"ggplot2\")" }, { "code": null, "e": 486, "s": 330, "text": "Create a DataFrame for example. Here we create a simple DataFrame with three variables named Year, Points, and Users and then assign it to the data object." }, { "code": null, "e": 488, "s": 486, "text": "R" }, { "code": "library(\"ggplot2\") # Create a DataFramedata <- data.frame(Year = c(2011, 2012, 2013, 2014, 2015), Points = c(30, 20, 15, 35, 50), Users = c(\"user1\", \"user2\", \"user3\", \"user4\", \"user5\"))print(data)", "e": 750, "s": 488, "text": null }, { "code": null, "e": 758, "s": 750, "text": "Output:" }, { "code": null, "e": 768, "s": 758, "text": "dataframe" }, { "code": null, "e": 940, "s": 768, "text": "For Create an R plot, we use ggplot() function and for make it scatter plot we add geom_point() function to ggplot() function. assign this whole plot to gplot data object." }, { "code": null, "e": 946, "s": 940, "text": "Code:" }, { "code": null, "e": 948, "s": 946, "text": "R" }, { "code": "# Load Packagelibrary(\"ggplot2\") # Create a DataFrame data <- data.frame(Year = c(2011, 2012, 2013, 2014, 2015), Points = c(30, 20, 15, 35, 50), Users = c(\"user1\", \"user2\", \"user3\", \"user4\", \"user5\")) # Create a Scatter Plot and assign it # to gplot data objectgplot <- ggplot(data, aes(Year, Points, color = Users)) + geom_point(size = 7)gplot", "e": 1364, "s": 948, "text": null }, { "code": null, "e": 1372, "s": 1364, "text": "Output:" }, { "code": null, "e": 1404, "s": 1372, "text": "Simple Scatter Plot with legend" }, { "code": null, "e": 1515, "s": 1404, "text": "To draw ggplot2 legend at the bottom of the plot, we simply add the theme() function to geom_point() function." }, { "code": null, "e": 1547, "s": 1515, "text": "Syntax : theme(legend.position)" }, { "code": null, "e": 1726, "s": 1547, "text": "Parameter : In General, theme() function has many parameters to specify the theme of the plot but here we use only legend.position parameter which specify the position of Legend." }, { "code": null, "e": 1754, "s": 1726, "text": "Return : Theme of the plot." }, { "code": null, "e": 1934, "s": 1754, "text": "We can specify the value of legend.position parameter from left, right, top and bottom. To draw legend at bottom of graph, we use ‘bottom’ as a value of legend.position parameter." }, { "code": null, "e": 1936, "s": 1934, "text": "R" }, { "code": "# Load Packagelibrary(ggplot2) # Create a DataFrame For plotdata <- data.frame(Year = c(2011, 2012, 2013, 2014, 2015), Points = c(30, 20, 15, 35, 50), Users = c(\"user1\", \"user2\", \"user3\", \"user4\", \"user5\")) # Create a simple scatter plot # with legend at bottom.ggplot(data, aes(Year, Points, color = Users)) + geom_point(size = 7)+ theme(legend.position = \"bottom\")", "e": 2375, "s": 1936, "text": null }, { "code": null, "e": 2383, "s": 2375, "text": "Output:" }, { "code": null, "e": 2418, "s": 2383, "text": "Scatter Plot with Legend at bottom" }, { "code": null, "e": 2804, "s": 2418, "text": "If we want to draw ggplot2 Legend at the bottom of the plot with two rows, we have to add guides and guide_legend functions to the theme() function. Inside guides() function, we take parameter named color, which has call to guide_legend() guide function as value. Inside guide_legend() function, we take an argument called nrow, which has the desired number of rows of legend as value." }, { "code": null, "e": 2832, "s": 2804, "text": "Syntax : guide_legend(nrow)" }, { "code": null, "e": 2845, "s": 2832, "text": "Parameter : " }, { "code": null, "e": 2890, "s": 2845, "text": "nrow : The Desired Number of rows of legend." }, { "code": null, "e": 2932, "s": 2890, "text": "Return : Legend Guides for various scales" }, { "code": null, "e": 2938, "s": 2932, "text": "Code:" }, { "code": null, "e": 2940, "s": 2938, "text": "R" }, { "code": "# Load Packagelibrary(ggplot2) # Create a DataFrame For plotdata <- data.frame(Year = c(2011, 2012, 2013, 2014, 2015), Points = c(30, 20, 15, 35, 50), Users = c(\"user1\", \"user2\", \"user3\", \"user4\", \"user5\")) # Create a simple scatter plot with# legend at bottom and with Two Rows.# Specifies the Number of legend Rowsggplot(data, aes(Year, Points, color = Users)) + geom_point(size = 7)+ theme(legend.position = \"bottom\")+ guides(color = guide_legend(nrow = 2)) ", "e": 3479, "s": 2940, "text": null }, { "code": null, "e": 3487, "s": 3479, "text": "Output:" }, { "code": null, "e": 3536, "s": 3487, "text": "Scatter plot with Legend at bottom with Two Rows" }, { "code": null, "e": 3543, "s": 3536, "text": "Picked" }, { "code": null, "e": 3552, "s": 3543, "text": "R-ggplot" }, { "code": null, "e": 3563, "s": 3552, "text": "R Language" } ]
MongoDB – Replication and Sharding
19 Oct, 2021 In context to the scaling of the MongoDB database, it has some features know as Replication and Sharding. Replication can be simply understood as the duplication of the data-set whereas sharding is partitioning the data-set into discrete parts. By sharding, you divided your collection into different parts. Replicating your database means you make imagers of your data-set. In terms of functionality delivered. Replication is the method of duplication of data across multiple servers. For example, we have an application and it reads and writes data to a database and says this server A has a name and balance which will be copied/replicate to two other servers in two different locations. By doing this, will get redundancy and increases data availability with multiple copies of data on different database servers. So, it will increase the performance of reading scaling. The set of servers that maintain the same copy of data is known as replica servers or MongoDB instances. Replication Key Features : Replica sets are the clusters of N different nodes that maintain the same copy of the data set. The primary server receives all write operations and record all the changes to the data i.e, oplog. The secondary members then copy and apply these changes in an asynchronous process. All the secondary nodes are connected with the primary nodes. there is one heartbeat signal from the primary nodes. If the primary server goes down an eligible secondary will hold the new primary. Why Replication? High Availability of data disasters recovery No downtime for maintenance ( like backups index rebuilds and compaction) Read Scaling (Extra copies to read from) How replication is formed? In order to perform replication in MongoDB, we need to first create replica sets and give permission to script the file. The basics syntax of –replSet is − mongod --port "PORT" --dbpath "YOUR_DB_DATA_PATH" --replSet "REPLICA_SET_INSTANCE_NAME" Or create a ".sh" file create_replicaset.sh and init_mongoreplica.js Examples: Then run the following script : ./create_replicaset.sh Directories will be created and then run the mongo. In the Mongo terminal, use the command rs.initiate() to initiate a new replica set. Sharding is a method for allocating data across multiple machines. MongoDB used sharding to help deployment with very big data sets and large throughput the operation. By sharding, you combine more devices to carry data extension and the needs of read and write operations. Why Sharding? Database systems having big data sets or high throughput requests can doubt the ability of a single server. For example, High query flows can drain the CPU limit of the server. The working set sizes are larger than the system’s RAM to stress the I/O capacity of the disk drive. How does Sharding work? Sharding determines the problem with horizontal scaling breaking the system dataset and store over multiple servers, adding new servers to increase the volume as needed. Now, instead of one signal as primary, we have multiple servers called Shard. We have different routing servers that will route data to the shard servers. For example: Let say we have Data 1, Data 2, and Data 3 this will be going to the routing server which will route the data (i.e, Different Data will go to a particular Shard ) Each Shard holds some pieces of data. Here the configuration server will hold the metadata and it will configure the routing server to integrate the particular data to a shard however configure server is the MongoDB instance if it goes down then the entire server will go down, So it again has Replica Configure database. Advantages of Sharding : Sharding adds more server to a data field automatically adjust data loads across various servers. The number of operations each shard manage got reduced. It also increases the write capacity by splitting the write load over multiple instances. It gives high availability due to the deployment of replica servers for shard and config. Total capacity will get increased by adding multiple shards. In order to create sharded clusters in MongoDB, We need to configure the shard, a config server, and a query router. Picked TrueGeek-2021 MongoDB TrueGeek Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to connect MongoDB with ReactJS ? MongoDB - limit() Method Create user and add role in MongoDB MongoDB - Compound Indexes MongoDB - sort() Method How to redirect to another page in ReactJS ? Basics of API Testing Using Postman How to remove duplicate elements from JavaScript Array ? How to Convert Char to String in Java? Types of Internet Protocols
[ { "code": null, "e": 54, "s": 26, "text": "\n19 Oct, 2021" }, { "code": null, "e": 467, "s": 54, "text": "In context to the scaling of the MongoDB database, it has some features know as Replication and Sharding. Replication can be simply understood as the duplication of the data-set whereas sharding is partitioning the data-set into discrete parts. By sharding, you divided your collection into different parts. Replicating your database means you make imagers of your data-set. In terms of functionality delivered. " }, { "code": null, "e": 746, "s": 467, "text": "Replication is the method of duplication of data across multiple servers. For example, we have an application and it reads and writes data to a database and says this server A has a name and balance which will be copied/replicate to two other servers in two different locations." }, { "code": null, "e": 1035, "s": 746, "text": "By doing this, will get redundancy and increases data availability with multiple copies of data on different database servers. So, it will increase the performance of reading scaling. The set of servers that maintain the same copy of data is known as replica servers or MongoDB instances." }, { "code": null, "e": 1062, "s": 1035, "text": "Replication Key Features :" }, { "code": null, "e": 1158, "s": 1062, "text": "Replica sets are the clusters of N different nodes that maintain the same copy of the data set." }, { "code": null, "e": 1258, "s": 1158, "text": "The primary server receives all write operations and record all the changes to the data i.e, oplog." }, { "code": null, "e": 1342, "s": 1258, "text": "The secondary members then copy and apply these changes in an asynchronous process." }, { "code": null, "e": 1539, "s": 1342, "text": "All the secondary nodes are connected with the primary nodes. there is one heartbeat signal from the primary nodes. If the primary server goes down an eligible secondary will hold the new primary." }, { "code": null, "e": 1556, "s": 1539, "text": "Why Replication?" }, { "code": null, "e": 1601, "s": 1556, "text": "High Availability of data disasters recovery" }, { "code": null, "e": 1675, "s": 1601, "text": "No downtime for maintenance ( like backups index rebuilds and compaction)" }, { "code": null, "e": 1716, "s": 1675, "text": "Read Scaling (Extra copies to read from)" }, { "code": null, "e": 1743, "s": 1716, "text": "How replication is formed?" }, { "code": null, "e": 1900, "s": 1743, "text": "In order to perform replication in MongoDB, we need to first create replica sets and give permission to script the file. The basics syntax of –replSet is −" }, { "code": null, "e": 1988, "s": 1900, "text": "mongod --port \"PORT\" --dbpath \"YOUR_DB_DATA_PATH\" --replSet \"REPLICA_SET_INSTANCE_NAME\"" }, { "code": null, "e": 1992, "s": 1988, "text": " Or" }, { "code": null, "e": 2059, "s": 1992, "text": "create a \".sh\" file create_replicaset.sh and init_mongoreplica.js" }, { "code": null, "e": 2070, "s": 2059, "text": "Examples: " }, { "code": null, "e": 2102, "s": 2070, "text": "Then run the following script :" }, { "code": null, "e": 2125, "s": 2102, "text": "./create_replicaset.sh" }, { "code": null, "e": 2177, "s": 2125, "text": "Directories will be created and then run the mongo." }, { "code": null, "e": 2261, "s": 2177, "text": "In the Mongo terminal, use the command rs.initiate() to initiate a new replica set." }, { "code": null, "e": 2535, "s": 2261, "text": "Sharding is a method for allocating data across multiple machines. MongoDB used sharding to help deployment with very big data sets and large throughput the operation. By sharding, you combine more devices to carry data extension and the needs of read and write operations." }, { "code": null, "e": 2549, "s": 2535, "text": "Why Sharding?" }, { "code": null, "e": 2657, "s": 2549, "text": "Database systems having big data sets or high throughput requests can doubt the ability of a single server." }, { "code": null, "e": 2726, "s": 2657, "text": "For example, High query flows can drain the CPU limit of the server." }, { "code": null, "e": 2827, "s": 2726, "text": "The working set sizes are larger than the system’s RAM to stress the I/O capacity of the disk drive." }, { "code": null, "e": 2851, "s": 2827, "text": "How does Sharding work?" }, { "code": null, "e": 3021, "s": 2851, "text": "Sharding determines the problem with horizontal scaling breaking the system dataset and store over multiple servers, adding new servers to increase the volume as needed." }, { "code": null, "e": 3674, "s": 3021, "text": "Now, instead of one signal as primary, we have multiple servers called Shard. We have different routing servers that will route data to the shard servers. For example: Let say we have Data 1, Data 2, and Data 3 this will be going to the routing server which will route the data (i.e, Different Data will go to a particular Shard ) Each Shard holds some pieces of data. Here the configuration server will hold the metadata and it will configure the routing server to integrate the particular data to a shard however configure server is the MongoDB instance if it goes down then the entire server will go down, So it again has Replica Configure database." }, { "code": null, "e": 3700, "s": 3674, "text": "Advantages of Sharding : " }, { "code": null, "e": 3798, "s": 3700, "text": "Sharding adds more server to a data field automatically adjust data loads across various servers." }, { "code": null, "e": 3854, "s": 3798, "text": "The number of operations each shard manage got reduced." }, { "code": null, "e": 3944, "s": 3854, "text": "It also increases the write capacity by splitting the write load over multiple instances." }, { "code": null, "e": 4034, "s": 3944, "text": "It gives high availability due to the deployment of replica servers for shard and config." }, { "code": null, "e": 4095, "s": 4034, "text": "Total capacity will get increased by adding multiple shards." }, { "code": null, "e": 4213, "s": 4095, "text": "In order to create sharded clusters in MongoDB, We need to configure the shard, a config server, and a query router. " }, { "code": null, "e": 4220, "s": 4213, "text": "Picked" }, { "code": null, "e": 4234, "s": 4220, "text": "TrueGeek-2021" }, { "code": null, "e": 4242, "s": 4234, "text": "MongoDB" }, { "code": null, "e": 4251, "s": 4242, "text": "TrueGeek" }, { "code": null, "e": 4349, "s": 4251, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4387, "s": 4349, "text": "How to connect MongoDB with ReactJS ?" }, { "code": null, "e": 4412, "s": 4387, "text": "MongoDB - limit() Method" }, { "code": null, "e": 4448, "s": 4412, "text": "Create user and add role in MongoDB" }, { "code": null, "e": 4475, "s": 4448, "text": "MongoDB - Compound Indexes" }, { "code": null, "e": 4499, "s": 4475, "text": "MongoDB - sort() Method" }, { "code": null, "e": 4544, "s": 4499, "text": "How to redirect to another page in ReactJS ?" }, { "code": null, "e": 4580, "s": 4544, "text": "Basics of API Testing Using Postman" }, { "code": null, "e": 4637, "s": 4580, "text": "How to remove duplicate elements from JavaScript Array ?" }, { "code": null, "e": 4676, "s": 4637, "text": "How to Convert Char to String in Java?" } ]
Computer Network | Leaky bucket algorithm
20 Jun, 2022 In the network layer, before the network can make Quality of service guarantees, it must know what traffic is being guaranteed. One of the main causes of congestion is that traffic is often bursty. To understand this concept first we have to know little about traffic shaping. Traffic Shaping is a mechanism to control the amount and the rate of the traffic sent to the network. Approach of congestion management is called Traffic shaping. Traffic shaping helps to regulate rate of data transmission and reduces congestion.There are 2 types of traffic shaping algorithms: Leaky BucketToken Bucket Leaky Bucket Token Bucket Suppose we have a bucket in which we are pouring water in a random order but we have to get water in a fixed rate, for this we will make a hole at the bottom of the bucket. It will ensure that water coming out is in a some fixed rate, and also if bucket will full we will stop pouring in it.The input rate can vary, but the output rate remains constant. Similarly, in networking, a technique called leaky bucket can smooth out bursty traffic. Bursty chunks are stored in the bucket and sent out at an average rate. In the figure, we assume that the network has committed a bandwidth of 3 Mbps for a host. The use of the leaky bucket shapes the input traffic to make it conform to this commitment. In Figure the host sends a burst of data at a rate of 12 Mbps for 2 s, for a total of 24 Mbits of data. The host is silent for 5 s and then sends data at a rate of 2 Mbps for 3 s, for a total of 6 Mbits of data. In all, the host has sent 30 Mbits of data in 10 s. The leaky bucket smooths the traffic by sending out data at a rate of 3 Mbps during the same 10 s. Without the leaky bucket, the beginning burst may have hurt the network by consuming more bandwidth than is set aside for this host. We can also see that the leaky bucket may prevent congestion.A simple leaky bucket algorithm can be implemented using FIFO queue. A FIFO queue holds the packets. If the traffic consists of fixed-size packets (e.g., cells in ATM networks), the process removes a fixed number of packets from the queue at each tick of the clock. If the traffic consists of variable-length packets, the fixed output rate must be based on the number of bytes or bits.The following is an algorithm for variable-length packets: Initialize a counter to n at the tick of the clock.If n is greater than the size of the packet, send the packet and decrement the counter by the packet size. Repeat this step until n is smaller than the packet size.Reset the counter and go to step 1. Initialize a counter to n at the tick of the clock. If n is greater than the size of the packet, send the packet and decrement the counter by the packet size. Repeat this step until n is smaller than the packet size. Reset the counter and go to step 1. Example – Let n=1000 Packet= Since n> front of Queue i.e. n>200 Therefore, n=1000-200=800 Packet size of 200 is sent to the network. Now Again n>front of the queue i.e. n > 400 Therefore, n=800-400=400 Packet size of 400 is sent to the network. Since n< front of queue Therefore, the procedure is stop. Initialize n=1000 on another tick of clock. This procedure is repeated until all the packets are sent to the network.Below is the implementation of above approach: C++ Java Python3 // cpp program to implement leakybucket#include<bits/stdc++.h>using namespace std;int main(){ int no_of_queries, storage, output_pkt_size; int input_pkt_size, bucket_size, size_left; // initial packets in the bucket storage = 0; // total no. of times bucket content is checked no_of_queries = 4; // total no. of packets that can // be accommodated in the bucket bucket_size = 10; // no. of packets that enters the bucket at a time input_pkt_size = 4; // no. of packets that exits the bucket at a time output_pkt_size = 1; for(int i = 0; i < no_of_queries; i++) //space left { size_left = bucket_size - storage; if(input_pkt_size <= size_left) { // update storage storage += input_pkt_size; printf("Buffer size= %d out of bucket size= %d\n", storage, bucket_size); } else { printf("Packet loss = %d\n", (input_pkt_size-(size_left))); // full size storage=bucket_size; printf("Buffer size= %d out of bucket size= %d\n", storage, bucket_size); } storage -= output_pkt_size; } return 0;} // This code is contributed by bunny09262002 //Java Implementation of Leaky bucket import java.io.*;import java.util.*; class Leakybucket { public static void main (String[] args) { int no_of_queries,storage,output_pkt_size; int input_pkt_size,bucket_size,size_left; //initial packets in the bucket storage=0; //total no. of times bucket content is checked no_of_queries=4; //total no. of packets that can // be accommodated in the bucket bucket_size=10; //no. of packets that enters the bucket at a time input_pkt_size=4; //no. of packets that exits the bucket at a time output_pkt_size=1; for(int i=0;i<no_of_queries;i++) { size_left=bucket_size-storage; //space left if(input_pkt_size<=(size_left)) { storage+=input_pkt_size; System.out.println("Buffer size= "+storage+ " out of bucket size= "+bucket_size); } else { System.out.println("Packet loss = " +(input_pkt_size-(size_left))); //full size storage=bucket_size; System.out.println("Buffer size= "+storage+ " out of bucket size= "+bucket_size); } storage-=output_pkt_size; } }} # initial packets in the bucketstorage = 0; # total no. of times bucket content is checkedno_of_queries = 4; # total no. of packets that can# be accommodated in the bucketbucket_size = 10 # no. of packets that enters the bucket at a timeinput_pkt_size = 4 # no. of packets that exits the bucket at a timeoutput_pkt_size = 1for i in range(0,no_of_queries): #space left size_left = bucket_size - storage; if input_pkt_size <= size_left: # update storage storage += input_pkt_size print("Buffer size = {} out of bucket size= {} ".format(storage, bucket_size)) else: print("Packet loss = ", (input_pkt_size-(size_left)),end=" "); # full size storage=bucket_size; print("Buffer size= {} out of bucket size = {}".format(storage, bucket_size)); storage -= output_pkt_size; # This code is contributed by Arpit Jain Output Buffer size= 4 out of bucket size= 10 Buffer size= 7 out of bucket size= 10 Buffer size= 10 out of bucket size= 10 Packet loss = 3 Buffer size= 10 out of bucket size= 10 Difference between Leaky and Token buckets – Some advantage of token Bucket over leaky bucket – If bucket is full in token Bucket , tokens are discard not packets. While in leaky bucket, packets are discarded. Token Bucket can send Large bursts at a faster rate while leaky bucket always sends packets at constant rate. This article is contributed by Abhishek Kumar and Himanshu Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. amanakmsd shahnirmit2503 clintra bunny09262002 111arpit1 Transport Layer Computer Networks GATE CS Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n20 Jun, 2022" }, { "code": null, "e": 625, "s": 52, "text": "In the network layer, before the network can make Quality of service guarantees, it must know what traffic is being guaranteed. One of the main causes of congestion is that traffic is often bursty. To understand this concept first we have to know little about traffic shaping. Traffic Shaping is a mechanism to control the amount and the rate of the traffic sent to the network. Approach of congestion management is called Traffic shaping. Traffic shaping helps to regulate rate of data transmission and reduces congestion.There are 2 types of traffic shaping algorithms: " }, { "code": null, "e": 650, "s": 625, "text": "Leaky BucketToken Bucket" }, { "code": null, "e": 663, "s": 650, "text": "Leaky Bucket" }, { "code": null, "e": 676, "s": 663, "text": "Token Bucket" }, { "code": null, "e": 1192, "s": 676, "text": "Suppose we have a bucket in which we are pouring water in a random order but we have to get water in a fixed rate, for this we will make a hole at the bottom of the bucket. It will ensure that water coming out is in a some fixed rate, and also if bucket will full we will stop pouring in it.The input rate can vary, but the output rate remains constant. Similarly, in networking, a technique called leaky bucket can smooth out bursty traffic. Bursty chunks are stored in the bucket and sent out at an average rate. " }, { "code": null, "e": 2377, "s": 1192, "text": "In the figure, we assume that the network has committed a bandwidth of 3 Mbps for a host. The use of the leaky bucket shapes the input traffic to make it conform to this commitment. In Figure the host sends a burst of data at a rate of 12 Mbps for 2 s, for a total of 24 Mbits of data. The host is silent for 5 s and then sends data at a rate of 2 Mbps for 3 s, for a total of 6 Mbits of data. In all, the host has sent 30 Mbits of data in 10 s. The leaky bucket smooths the traffic by sending out data at a rate of 3 Mbps during the same 10 s. Without the leaky bucket, the beginning burst may have hurt the network by consuming more bandwidth than is set aside for this host. We can also see that the leaky bucket may prevent congestion.A simple leaky bucket algorithm can be implemented using FIFO queue. A FIFO queue holds the packets. If the traffic consists of fixed-size packets (e.g., cells in ATM networks), the process removes a fixed number of packets from the queue at each tick of the clock. If the traffic consists of variable-length packets, the fixed output rate must be based on the number of bytes or bits.The following is an algorithm for variable-length packets: " }, { "code": null, "e": 2628, "s": 2377, "text": "Initialize a counter to n at the tick of the clock.If n is greater than the size of the packet, send the packet and decrement the counter by the packet size. Repeat this step until n is smaller than the packet size.Reset the counter and go to step 1." }, { "code": null, "e": 2680, "s": 2628, "text": "Initialize a counter to n at the tick of the clock." }, { "code": null, "e": 2845, "s": 2680, "text": "If n is greater than the size of the packet, send the packet and decrement the counter by the packet size. Repeat this step until n is smaller than the packet size." }, { "code": null, "e": 2881, "s": 2845, "text": "Reset the counter and go to step 1." }, { "code": null, "e": 2910, "s": 2881, "text": "Example – Let n=1000 Packet=" }, { "code": null, "e": 3017, "s": 2910, "text": " Since n> front of Queue i.e. n>200 Therefore, n=1000-200=800 Packet size of 200 is sent to the network. " }, { "code": null, "e": 3131, "s": 3017, "text": "Now Again n>front of the queue i.e. n > 400 Therefore, n=800-400=400 Packet size of 400 is sent to the network. " }, { "code": null, "e": 3355, "s": 3131, "text": "Since n< front of queue Therefore, the procedure is stop. Initialize n=1000 on another tick of clock. This procedure is repeated until all the packets are sent to the network.Below is the implementation of above approach: " }, { "code": null, "e": 3359, "s": 3355, "text": "C++" }, { "code": null, "e": 3364, "s": 3359, "text": "Java" }, { "code": null, "e": 3372, "s": 3364, "text": "Python3" }, { "code": "// cpp program to implement leakybucket#include<bits/stdc++.h>using namespace std;int main(){ int no_of_queries, storage, output_pkt_size; int input_pkt_size, bucket_size, size_left; // initial packets in the bucket storage = 0; // total no. of times bucket content is checked no_of_queries = 4; // total no. of packets that can // be accommodated in the bucket bucket_size = 10; // no. of packets that enters the bucket at a time input_pkt_size = 4; // no. of packets that exits the bucket at a time output_pkt_size = 1; for(int i = 0; i < no_of_queries; i++) //space left { size_left = bucket_size - storage; if(input_pkt_size <= size_left) { // update storage storage += input_pkt_size; printf(\"Buffer size= %d out of bucket size= %d\\n\", storage, bucket_size); } else { printf(\"Packet loss = %d\\n\", (input_pkt_size-(size_left))); // full size storage=bucket_size; printf(\"Buffer size= %d out of bucket size= %d\\n\", storage, bucket_size); } storage -= output_pkt_size; } return 0;} // This code is contributed by bunny09262002", "e": 4526, "s": 3372, "text": null }, { "code": "//Java Implementation of Leaky bucket import java.io.*;import java.util.*; class Leakybucket { public static void main (String[] args) { int no_of_queries,storage,output_pkt_size; int input_pkt_size,bucket_size,size_left; //initial packets in the bucket storage=0; //total no. of times bucket content is checked no_of_queries=4; //total no. of packets that can // be accommodated in the bucket bucket_size=10; //no. of packets that enters the bucket at a time input_pkt_size=4; //no. of packets that exits the bucket at a time output_pkt_size=1; for(int i=0;i<no_of_queries;i++) { size_left=bucket_size-storage; //space left if(input_pkt_size<=(size_left)) { storage+=input_pkt_size; System.out.println(\"Buffer size= \"+storage+ \" out of bucket size= \"+bucket_size); } else { System.out.println(\"Packet loss = \" +(input_pkt_size-(size_left))); //full size storage=bucket_size; System.out.println(\"Buffer size= \"+storage+ \" out of bucket size= \"+bucket_size); } storage-=output_pkt_size; } }}", "e": 6030, "s": 4526, "text": null }, { "code": "# initial packets in the bucketstorage = 0; # total no. of times bucket content is checkedno_of_queries = 4; # total no. of packets that can# be accommodated in the bucketbucket_size = 10 # no. of packets that enters the bucket at a timeinput_pkt_size = 4 # no. of packets that exits the bucket at a timeoutput_pkt_size = 1for i in range(0,no_of_queries): #space left size_left = bucket_size - storage; if input_pkt_size <= size_left: # update storage storage += input_pkt_size print(\"Buffer size = {} out of bucket size= {} \".format(storage, bucket_size)) else: print(\"Packet loss = \", (input_pkt_size-(size_left)),end=\" \"); # full size storage=bucket_size; print(\"Buffer size= {} out of bucket size = {}\".format(storage, bucket_size)); storage -= output_pkt_size; # This code is contributed by Arpit Jain", "e": 6940, "s": 6030, "text": null }, { "code": null, "e": 6949, "s": 6940, "text": "Output " }, { "code": null, "e": 7119, "s": 6949, "text": "Buffer size= 4 out of bucket size= 10\nBuffer size= 7 out of bucket size= 10\nBuffer size= 10 out of bucket size= 10\nPacket loss = 3\nBuffer size= 10 out of bucket size= 10" }, { "code": null, "e": 7165, "s": 7119, "text": "Difference between Leaky and Token buckets – " }, { "code": null, "e": 7217, "s": 7165, "text": "Some advantage of token Bucket over leaky bucket – " }, { "code": null, "e": 7331, "s": 7217, "text": "If bucket is full in token Bucket , tokens are discard not packets. While in leaky bucket, packets are discarded." }, { "code": null, "e": 7441, "s": 7331, "text": "Token Bucket can send Large bursts at a faster rate while leaky bucket always sends packets at constant rate." }, { "code": null, "e": 7882, "s": 7441, "text": "This article is contributed by Abhishek Kumar and Himanshu Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 7892, "s": 7882, "text": "amanakmsd" }, { "code": null, "e": 7907, "s": 7892, "text": "shahnirmit2503" }, { "code": null, "e": 7915, "s": 7907, "text": "clintra" }, { "code": null, "e": 7929, "s": 7915, "text": "bunny09262002" }, { "code": null, "e": 7939, "s": 7929, "text": "111arpit1" }, { "code": null, "e": 7955, "s": 7939, "text": "Transport Layer" }, { "code": null, "e": 7973, "s": 7955, "text": "Computer Networks" }, { "code": null, "e": 7981, "s": 7973, "text": "GATE CS" }, { "code": null, "e": 7999, "s": 7981, "text": "Computer Networks" } ]
LMNs-Data Structure - GeeksforGeeks
28 Jun, 2021 Arrays An array is collection of items stored at continuous memory locations. The idea is to declare multiple items of same type together. Array declaration: In C, we can declare an array by specifying its and size or by initializing it or by both. // Array declaration by specifying size int arr[10]; // Array declaration by initializing elements int arr[] = {10, 20, 30, 40}; // Array declaration by specifying size and // initializing elements int arr[6] = {10, 20, 30, 40} Formulas: Length of Array = UB - LB + 1 Given the address of first element, address of any other element is calculated using the formula:- Loc (arr [k]) = base (arr) + w * k w = number of bytes per storage location of for one element k = index of array whose address we want to calculate Elements of two-dimensional arrays (mXn) are stored in two ways:- Column major order: Elements are stored column by column, i.e. all elements of first column are stored, and then all elements of second column stored and so on. Loc(arr[i][j]) = base(arr) + w (m *j + i) Row major order: Elements are stored row by row, i.e. all elements of first row are stored, and then all elements of second row stored and so on. Loc(arr[i][j]) = base(arr) + w (n*i + j) Stacks Stack is a linear data structure which follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). Basic operations : Push: Adds an item in the stack. If the stack is full, then it is said to be an Overflow condition. (Top=Top+1) Pop: Removes an item from the stack. The items are popped in the reversed order in which they are pushed. If the stack is empty, then it is said to be an Underflow condition.(Top=Top-1)Peek: Get the topmost item. Infix, prefix, Postfix notations Infix notation: X + Y – Operators are written in-between their operands. This is the usual way we write expressions. An expression such as A * ( B + C ) / D Postfix notation (also known as “Reverse Polish notation”): X Y + Operators are written after their operands. The infix expression given above is equivalent to A B C + * D/ Prefix notation (also known as “Polish notation”): + X Y Operators are written before their operands. The expressions given above are equivalent to / * A + B C D Converting between these notations: Click here Tower of Hanoi is a mathematical puzzle where we have three rods and n disks. The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules: 1) Only one disk can be moved at a time. 2) Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack. 3) No disk may be placed on top of a smaller disk. For n disks, total 2n – 1 moves are required Time complexity : O(2n) [exponential time] Queues Queue is a linear structure which follows a particular order in which the operations are performed. The order is First In First Out (FIFO). A good example of queue is any queue of consumers for a resource where the consumer that came first is served first. Stack : Remove the item the most recently added Queue: Remove the item the least recently added Operations on Queue: Enqueue: Adds an item to the queue. If the queue is full, then it is said to be an Overflow condition. Dequeue: Removes an item from the queue. The items are popped in the same order in which they are pushed. If the queue is empty, then it is said to be an Underflow condition. Front: Get the front item from queue. Rear: Get the last item from queue. Linked Lists Linked List is a linear data structure. Unlike arrays, linked list elements are not stored at contiguous location; the elements are linked using pointers. Advantages over arrays1) Dynamic size2) Ease of insertion/deletionDrawbacks:1) Random access is not allowed. We have to access elements sequentially starting from the first node. So we cannot do binary search with linked lists.2) Extra memory space for a pointer is required with each element of the list. Representation in C: A linked list is represented by a pointer to the first node of the linked list. The first node is called head. If the linked list is empty, then value of head is NULL.Each node in a list consists of at least two parts:1) data2) pointer to the next node In C, we can represent a node using structures. Below is an example of a linked list node with an integer data. // A linked list node struct node { int data; struct node *next; }; Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 29498, "s": 29470, "text": "\n28 Jun, 2021" }, { "code": null, "e": 29506, "s": 29498, "text": "Arrays " }, { "code": null, "e": 29748, "s": 29506, "text": "An array is collection of items stored at continuous memory locations. The idea is to declare multiple items of same type together. Array declaration: In C, we can declare an array by specifying its and size or by initializing it or by both." }, { "code": null, "e": 29979, "s": 29748, "text": "// Array declaration by specifying size\nint arr[10];\n\n// Array declaration by initializing elements\nint arr[] = {10, 20, 30, 40};\n\n// Array declaration by specifying size and\n// initializing elements\nint arr[6] = {10, 20, 30, 40}\n" }, { "code": null, "e": 29989, "s": 29979, "text": "Formulas:" }, { "code": null, "e": 30024, "s": 29989, "text": " \n Length of Array = UB - LB + 1 " }, { "code": null, "e": 30123, "s": 30024, "text": "Given the address of first element, address of any other element is calculated using the formula:-" }, { "code": null, "e": 30298, "s": 30123, "text": " Loc (arr [k]) = base (arr) + w * k\n w = number of bytes per storage location \n of for one element \n k = index of array whose address we want \n to calculate" }, { "code": null, "e": 30364, "s": 30298, "text": "Elements of two-dimensional arrays (mXn) are stored in two ways:-" }, { "code": null, "e": 30525, "s": 30364, "text": "Column major order: Elements are stored column by column, i.e. all elements of first column are stored, and then all elements of second column stored and so on." }, { "code": null, "e": 30570, "s": 30525, "text": " Loc(arr[i][j]) = base(arr) + w (m *j + i)" }, { "code": null, "e": 30716, "s": 30570, "text": "Row major order: Elements are stored row by row, i.e. all elements of first row are stored, and then all elements of second row stored and so on." }, { "code": null, "e": 30760, "s": 30716, "text": " Loc(arr[i][j]) = base(arr) + w (n*i + j)" }, { "code": null, "e": 30767, "s": 30760, "text": "Stacks" }, { "code": null, "e": 30941, "s": 30767, "text": "Stack is a linear data structure which follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out)." }, { "code": null, "e": 30960, "s": 30941, "text": "Basic operations :" }, { "code": null, "e": 31285, "s": 30960, "text": "Push: Adds an item in the stack. If the stack is full, then it is said to be an Overflow condition. (Top=Top+1) Pop: Removes an item from the stack. The items are popped in the reversed order in which they are pushed. If the stack is empty, then it is said to be an Underflow condition.(Top=Top-1)Peek: Get the topmost item." }, { "code": null, "e": 31318, "s": 31285, "text": "Infix, prefix, Postfix notations" }, { "code": null, "e": 31457, "s": 31318, "text": "Infix notation: X + Y – Operators are written in-between their operands. This is the usual way we write expressions. An expression such as" }, { "code": null, "e": 31478, "s": 31457, "text": " A * ( B + C ) / D" }, { "code": null, "e": 31638, "s": 31478, "text": "Postfix notation (also known as “Reverse Polish notation”): X Y + Operators are written after their operands. The infix expression given above is equivalent to" }, { "code": null, "e": 31656, "s": 31638, "text": " \n A B C + * D/" }, { "code": null, "e": 31804, "s": 31656, "text": "Prefix notation (also known as “Polish notation”): + X Y Operators are written before their operands. The expressions given above are equivalent to" }, { "code": null, "e": 31823, "s": 31804, "text": " \n / * A + B C D" }, { "code": null, "e": 31870, "s": 31823, "text": "Converting between these notations: Click here" }, { "code": null, "e": 32056, "s": 31870, "text": "Tower of Hanoi is a mathematical puzzle where we have three rods and n disks. The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules:" }, { "code": null, "e": 32097, "s": 32056, "text": "1) Only one disk can be moved at a time." }, { "code": null, "e": 32276, "s": 32097, "text": "2) Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack." }, { "code": null, "e": 32327, "s": 32276, "text": "3) No disk may be placed on top of a smaller disk." }, { "code": null, "e": 32416, "s": 32327, "text": "For n disks, total 2n – 1 moves are required \nTime complexity : O(2n) [exponential time]" }, { "code": null, "e": 32423, "s": 32416, "text": "Queues" }, { "code": null, "e": 32799, "s": 32423, "text": "Queue is a linear structure which follows a particular order in which the operations are performed. The order is First In First Out (FIFO). A good example of queue is any queue of consumers for a resource where the consumer that came first is served first. Stack : Remove the item the most recently added Queue: Remove the item the least recently added Operations on Queue:" }, { "code": null, "e": 32902, "s": 32799, "text": "Enqueue: Adds an item to the queue. If the queue is full, then it is said to be an Overflow condition." }, { "code": null, "e": 33077, "s": 32902, "text": "Dequeue: Removes an item from the queue. The items are popped in the same order in which they are pushed. If the queue is empty, then it is said to be an Underflow condition." }, { "code": null, "e": 33115, "s": 33077, "text": "Front: Get the front item from queue." }, { "code": null, "e": 33151, "s": 33115, "text": "Rear: Get the last item from queue." }, { "code": null, "e": 33164, "s": 33151, "text": "Linked Lists" }, { "code": null, "e": 33319, "s": 33164, "text": "Linked List is a linear data structure. Unlike arrays, linked list elements are not stored at contiguous location; the elements are linked using pointers." }, { "code": null, "e": 34011, "s": 33319, "text": "Advantages over arrays1) Dynamic size2) Ease of insertion/deletionDrawbacks:1) Random access is not allowed. We have to access elements sequentially starting from the first node. So we cannot do binary search with linked lists.2) Extra memory space for a pointer is required with each element of the list. Representation in C: A linked list is represented by a pointer to the first node of the linked list. The first node is called head. If the linked list is empty, then value of head is NULL.Each node in a list consists of at least two parts:1) data2) pointer to the next node In C, we can represent a node using structures. Below is an example of a linked list node with an integer data." }, { "code": null, "e": 34083, "s": 34011, "text": "// A linked list node\nstruct node\n{\n int data;\n struct node *next;\n};" } ]
SQL | DELETE Statement
28 Jun, 2021 The DELETE Statement in SQL is used to delete existing records from a table. We can delete a single record or multiple records depending on the condition we specify in the WHERE clause. Basic Syntax: DELETE FROM table_name WHERE some_condition; table_name: name of the table some_condition: condition to choose particular record. Note: We can delete single as well as multiple records depending on the condition we provide in WHERE clause. If we omit the WHERE clause then all of the records will be deleted and the table will be empty. Sample Table: Example Queries: Deleting single record: Delete the rows where NAME = ‘Ram’. This will delete only the first row.DELETE FROM Student WHERE NAME = 'Ram'; Output:The above query will delete only the first row and the table Student will now look like,ROLL_NONAMEADDRESSPHONEAge2RAMESHGURGAONXXXXXXXXXX183SUJITROHTAKXXXXXXXXXX204SURESHDelhiXXXXXXXXXX183SUJITROHTAKXXXXXXXXXX202RAMESHGURGAONXXXXXXXXXX18 DELETE FROM Student WHERE NAME = 'Ram'; Output:The above query will delete only the first row and the table Student will now look like, Deleting multiple records: Delete the rows from the table Student where Age is 20. This will delete 2 rows(third row and fifth row).DELETE FROM Student WHERE Age = 20; Output:The above query will delete two rows(third row and fifth row) and the table Student will now look like,ROLL_NONAMEADDRESSPHONEAge1RamDelhiXXXXXXXXXX182RAMESHGURGAONXXXXXXXXXX184SURESHDelhiXXXXXXXXXX182RAMESHGURGAONXXXXXXXXXX18 DELETE FROM Student WHERE Age = 20; Output:The above query will delete two rows(third row and fifth row) and the table Student will now look like, Delete all of the records: There are two queries to do this as shown below,query1: "DELETE FROM Student"; query2: "DELETE * FROM Student"; Output:All of the records in the table will be deleted, there are no records left to display. The table Student will become empty! query1: "DELETE FROM Student"; query2: "DELETE * FROM Student"; Output:All of the records in the table will be deleted, there are no records left to display. The table Student will become empty! SQL Quiz This article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. SQL-Clauses-Operators Articles DBMS SQL DBMS SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n28 Jun, 2021" }, { "code": null, "e": 238, "s": 52, "text": "The DELETE Statement in SQL is used to delete existing records from a table. We can delete a single record or multiple records depending on the condition we specify in the WHERE clause." }, { "code": null, "e": 252, "s": 238, "text": "Basic Syntax:" }, { "code": null, "e": 384, "s": 252, "text": "DELETE FROM table_name WHERE some_condition;\n\ntable_name: name of the table\nsome_condition: condition to choose particular record.\n" }, { "code": null, "e": 591, "s": 384, "text": "Note: We can delete single as well as multiple records depending on the condition we provide in WHERE clause. If we omit the WHERE clause then all of the records will be deleted and the table will be empty." }, { "code": null, "e": 605, "s": 591, "text": "Sample Table:" }, { "code": null, "e": 622, "s": 605, "text": "Example Queries:" }, { "code": null, "e": 1004, "s": 622, "text": "Deleting single record: Delete the rows where NAME = ‘Ram’. This will delete only the first row.DELETE FROM Student WHERE NAME = 'Ram';\nOutput:The above query will delete only the first row and the table Student will now look like,ROLL_NONAMEADDRESSPHONEAge2RAMESHGURGAONXXXXXXXXXX183SUJITROHTAKXXXXXXXXXX204SURESHDelhiXXXXXXXXXX183SUJITROHTAKXXXXXXXXXX202RAMESHGURGAONXXXXXXXXXX18" }, { "code": null, "e": 1045, "s": 1004, "text": "DELETE FROM Student WHERE NAME = 'Ram';\n" }, { "code": null, "e": 1141, "s": 1045, "text": "Output:The above query will delete only the first row and the table Student will now look like," }, { "code": null, "e": 1543, "s": 1141, "text": "Deleting multiple records: Delete the rows from the table Student where Age is 20. This will delete 2 rows(third row and fifth row).DELETE FROM Student WHERE Age = 20;\nOutput:The above query will delete two rows(third row and fifth row) and the table Student will now look like,ROLL_NONAMEADDRESSPHONEAge1RamDelhiXXXXXXXXXX182RAMESHGURGAONXXXXXXXXXX184SURESHDelhiXXXXXXXXXX182RAMESHGURGAONXXXXXXXXXX18" }, { "code": null, "e": 1580, "s": 1543, "text": "DELETE FROM Student WHERE Age = 20;\n" }, { "code": null, "e": 1691, "s": 1580, "text": "Output:The above query will delete two rows(third row and fifth row) and the table Student will now look like," }, { "code": null, "e": 1962, "s": 1691, "text": "Delete all of the records: There are two queries to do this as shown below,query1: \"DELETE FROM Student\";\n\nquery2: \"DELETE * FROM Student\";\nOutput:All of the records in the table will be deleted, there are no records left to display. The table Student will become empty!" }, { "code": null, "e": 2028, "s": 1962, "text": "query1: \"DELETE FROM Student\";\n\nquery2: \"DELETE * FROM Student\";\n" }, { "code": null, "e": 2159, "s": 2028, "text": "Output:All of the records in the table will be deleted, there are no records left to display. The table Student will become empty!" }, { "code": null, "e": 2168, "s": 2159, "text": "SQL Quiz" }, { "code": null, "e": 2465, "s": 2168, "text": "This article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 2590, "s": 2465, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 2612, "s": 2590, "text": "SQL-Clauses-Operators" }, { "code": null, "e": 2621, "s": 2612, "text": "Articles" }, { "code": null, "e": 2626, "s": 2621, "text": "DBMS" }, { "code": null, "e": 2630, "s": 2626, "text": "SQL" }, { "code": null, "e": 2635, "s": 2630, "text": "DBMS" }, { "code": null, "e": 2639, "s": 2635, "text": "SQL" } ]
Generate Random Numbers From The Uniform Distribution using NumPy
05 Sep, 2020 Random numbers are the numbers that cannot be predicted logically and in Numpy we are provided with the module called random module that allows us to work with random numbers. To generate random numbers from the Uniform distribution we will use random.uniform() method of random module. Syntax: numpy.random.uniform(low = 0.0, high = 1.0, size = None) In uniform distribution samples are uniformly distributed over the half-open interval [low, high) it includes low but excludes high interval. Examples: Python3 # importing moduleimport numpy as np # numpy.random.uniform() methodr = np.random.uniform(size=4) # printing numbersprint(r) Output: [0.3829765 0.50958636 0.42844207 0.4260992 0.3513896 ] Example 2: Python3 # importing moduleimport numpy as np # numpy.random.uniform() methodrandom_array = np.random.uniform(0.0, 1.0, 5) # printing 1D array with random numbersprint("1D Array with random values : \n", random_array) Output: 1D Array with random values : [0.2167103 0.07881761 0.89666672 0.31143605 0.31481039] Python numpy-Random Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n05 Sep, 2020" }, { "code": null, "e": 342, "s": 54, "text": "Random numbers are the numbers that cannot be predicted logically and in Numpy we are provided with the module called random module that allows us to work with random numbers. To generate random numbers from the Uniform distribution we will use random.uniform() method of random module. " }, { "code": null, "e": 350, "s": 342, "text": "Syntax:" }, { "code": null, "e": 409, "s": 350, "text": "numpy.random.uniform(low = 0.0, high = 1.0, size = None) " }, { "code": null, "e": 551, "s": 409, "text": "In uniform distribution samples are uniformly distributed over the half-open interval [low, high) it includes low but excludes high interval." }, { "code": null, "e": 561, "s": 551, "text": "Examples:" }, { "code": null, "e": 569, "s": 561, "text": "Python3" }, { "code": "# importing moduleimport numpy as np # numpy.random.uniform() methodr = np.random.uniform(size=4) # printing numbersprint(r)", "e": 698, "s": 569, "text": null }, { "code": null, "e": 706, "s": 698, "text": "Output:" }, { "code": null, "e": 764, "s": 706, "text": "[0.3829765 0.50958636 0.42844207 0.4260992 0.3513896 ]\n" }, { "code": null, "e": 775, "s": 764, "text": "Example 2:" }, { "code": null, "e": 783, "s": 775, "text": "Python3" }, { "code": "# importing moduleimport numpy as np # numpy.random.uniform() methodrandom_array = np.random.uniform(0.0, 1.0, 5) # printing 1D array with random numbersprint(\"1D Array with random values : \\n\", random_array)", "e": 996, "s": 783, "text": null }, { "code": null, "e": 1004, "s": 996, "text": "Output:" }, { "code": null, "e": 1092, "s": 1004, "text": "1D Array with random values :\n[0.2167103 0.07881761 0.89666672 0.31143605 0.31481039]\n" }, { "code": null, "e": 1112, "s": 1092, "text": "Python numpy-Random" }, { "code": null, "e": 1125, "s": 1112, "text": "Python-numpy" }, { "code": null, "e": 1132, "s": 1125, "text": "Python" } ]
Interrupting a Thread in Java
17 Dec, 2021 In Java Threads, if any thread is in sleeping or waiting state (i.e. sleep() or wait() is invoked), calling the interrupt() method on the thread, breaks out the sleeping or waiting state throwing InterruptedException. If the thread is not in the sleeping or waiting state, calling the interrupt() method performs normal behavior and doesn’t interrupt the thread but sets the interrupt flag to true. interrupt() method: If any thread is in sleeping or waiting for a state then using the interrupt() method, we can interrupt the execution of that thread by showing InterruptedException. A thread that is in the sleeping or waiting state can be interrupted with the help of the interrupt() method of Thread class. Example: Suppose there are two threads and If one of the threads is blocked in an invocation of the wait(), wait(long), or wait(long, int) methods of the Object class, or of the join(), join(long), join(long, int), sleep(long), or sleep(long, int), methods of this class, then its interrupt status will be cleared and it will receive an InterruptedException, which gives the chance to another thread to execute the corresponding run() method of another thread which results into high performance and reduces the waiting time of the threads. Case 1: Interrupting a thread that doesn’t stop working: In the program, we handle the InterruptedException using try and catch block, so whenever any thread interrupts the currently executing thread it will come out from the sleeping state but it will not stop working. Java // Java Program to illustrate the// concept of interrupt() method// while a thread does not stops working class MyClass extends Thread { public void run() { try { for (int i = 0; i < 5; i++) { System.out.println("Child Thread executing"); // Here current threads goes to sleeping state // Another thread gets the chance to execute Thread.sleep(1000); } } catch (InterruptedException e) { System.out.println("InterruptedException occur"); } }} class Test { public static void main(String[] args) throws InterruptedException { MyClass thread = new MyClass(); thread.start(); // main thread calls interrupt() method on // child thread thread.interrupt(); System.out.println("Main thread execution completes"); }} Main thread execution completes Child Thread executing InterruptedException occur Case 2: Interrupting a thread that stops working: In the program, after interrupting the currently executing thread, we are throwing a new exception in the catch block so it will stop working. Java // Java Program to illustrate the// concept of interrupt() method// while a thread stops working class Geeks extends Thread { public void run() { try { Thread.sleep(2000); System.out.println("Geeksforgeeks"); } catch (InterruptedException e) { throw new RuntimeException("Thread " + "interrupted"); } } public static void main(String args[]) { Geeks t1 = new Geeks(); t1.start(); try { t1.interrupt(); } catch (Exception e) { System.out.println("Exception handled"); } }} Output Exception in thread "Thread-0" java.lang.RuntimeException: Thread interrupted at Geeks.run(File.java:13) Case 3: Interrupting a thread that works normally: In the program, there is no exception occurred during the execution of the thread. Here, interrupt only sets the interrupted flag to true, which can be used by Java programmers later. Java // Java Program to illustrate the concept of// interrupt() method class Geeks extends Thread { public void run() { for (int i = 0; i < 5; i++) System.out.println(i); } public static void main(String args[]) { Geeks t1 = new Geeks(); t1.start(); t1.interrupt(); }} 0 1 2 3 4 This article is contributed by Bishal Kumar Dubey. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. nishkarshgandhi Java-Multithreading Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Interfaces in Java ArrayList in Java Collections in Java Multidimensional Arrays in Java Stream In Java Set in Java Singleton Class in Java Initializing a List in Java Stack Class in Java Introduction to Java
[ { "code": null, "e": 52, "s": 24, "text": "\n17 Dec, 2021" }, { "code": null, "e": 452, "s": 52, "text": "In Java Threads, if any thread is in sleeping or waiting state (i.e. sleep() or wait() is invoked), calling the interrupt() method on the thread, breaks out the sleeping or waiting state throwing InterruptedException. If the thread is not in the sleeping or waiting state, calling the interrupt() method performs normal behavior and doesn’t interrupt the thread but sets the interrupt flag to true. " }, { "code": null, "e": 764, "s": 452, "text": "interrupt() method: If any thread is in sleeping or waiting for a state then using the interrupt() method, we can interrupt the execution of that thread by showing InterruptedException. A thread that is in the sleeping or waiting state can be interrupted with the help of the interrupt() method of Thread class." }, { "code": null, "e": 1305, "s": 764, "text": "Example: Suppose there are two threads and If one of the threads is blocked in an invocation of the wait(), wait(long), or wait(long, int) methods of the Object class, or of the join(), join(long), join(long, int), sleep(long), or sleep(long, int), methods of this class, then its interrupt status will be cleared and it will receive an InterruptedException, which gives the chance to another thread to execute the corresponding run() method of another thread which results into high performance and reduces the waiting time of the threads." }, { "code": null, "e": 1577, "s": 1305, "text": "Case 1: Interrupting a thread that doesn’t stop working: In the program, we handle the InterruptedException using try and catch block, so whenever any thread interrupts the currently executing thread it will come out from the sleeping state but it will not stop working. " }, { "code": null, "e": 1582, "s": 1577, "text": "Java" }, { "code": "// Java Program to illustrate the// concept of interrupt() method// while a thread does not stops working class MyClass extends Thread { public void run() { try { for (int i = 0; i < 5; i++) { System.out.println(\"Child Thread executing\"); // Here current threads goes to sleeping state // Another thread gets the chance to execute Thread.sleep(1000); } } catch (InterruptedException e) { System.out.println(\"InterruptedException occur\"); } }} class Test { public static void main(String[] args) throws InterruptedException { MyClass thread = new MyClass(); thread.start(); // main thread calls interrupt() method on // child thread thread.interrupt(); System.out.println(\"Main thread execution completes\"); }}", "e": 2492, "s": 1582, "text": null }, { "code": null, "e": 2574, "s": 2492, "text": "Main thread execution completes\nChild Thread executing\nInterruptedException occur" }, { "code": null, "e": 2767, "s": 2574, "text": "Case 2: Interrupting a thread that stops working: In the program, after interrupting the currently executing thread, we are throwing a new exception in the catch block so it will stop working." }, { "code": null, "e": 2772, "s": 2767, "text": "Java" }, { "code": "// Java Program to illustrate the// concept of interrupt() method// while a thread stops working class Geeks extends Thread { public void run() { try { Thread.sleep(2000); System.out.println(\"Geeksforgeeks\"); } catch (InterruptedException e) { throw new RuntimeException(\"Thread \" + \"interrupted\"); } } public static void main(String args[]) { Geeks t1 = new Geeks(); t1.start(); try { t1.interrupt(); } catch (Exception e) { System.out.println(\"Exception handled\"); } }}", "e": 3423, "s": 2772, "text": null }, { "code": null, "e": 3430, "s": 3423, "text": "Output" }, { "code": null, "e": 3539, "s": 3430, "text": "Exception in thread \"Thread-0\" java.lang.RuntimeException: Thread interrupted\n at Geeks.run(File.java:13)" }, { "code": null, "e": 3775, "s": 3539, "text": "Case 3: Interrupting a thread that works normally: In the program, there is no exception occurred during the execution of the thread. Here, interrupt only sets the interrupted flag to true, which can be used by Java programmers later. " }, { "code": null, "e": 3780, "s": 3775, "text": "Java" }, { "code": "// Java Program to illustrate the concept of// interrupt() method class Geeks extends Thread { public void run() { for (int i = 0; i < 5; i++) System.out.println(i); } public static void main(String args[]) { Geeks t1 = new Geeks(); t1.start(); t1.interrupt(); }}", "e": 4102, "s": 3780, "text": null }, { "code": null, "e": 4112, "s": 4102, "text": "0\n1\n2\n3\n4" }, { "code": null, "e": 4539, "s": 4112, "text": "This article is contributed by Bishal Kumar Dubey. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 4555, "s": 4539, "text": "nishkarshgandhi" }, { "code": null, "e": 4575, "s": 4555, "text": "Java-Multithreading" }, { "code": null, "e": 4580, "s": 4575, "text": "Java" }, { "code": null, "e": 4585, "s": 4580, "text": "Java" }, { "code": null, "e": 4683, "s": 4585, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4702, "s": 4683, "text": "Interfaces in Java" }, { "code": null, "e": 4720, "s": 4702, "text": "ArrayList in Java" }, { "code": null, "e": 4740, "s": 4720, "text": "Collections in Java" }, { "code": null, "e": 4772, "s": 4740, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 4787, "s": 4772, "text": "Stream In Java" }, { "code": null, "e": 4799, "s": 4787, "text": "Set in Java" }, { "code": null, "e": 4823, "s": 4799, "text": "Singleton Class in Java" }, { "code": null, "e": 4851, "s": 4823, "text": "Initializing a List in Java" }, { "code": null, "e": 4871, "s": 4851, "text": "Stack Class in Java" } ]
Difference between reactstrap and react-bootstrap
25 Oct, 2020 Bootstrap is a popular front-end CSS framework used by web developers to design their web applications. Bootstrap components include HTML, CSS, and JavaScript with additional dependencies like jQuery which makes it hard to use in React applications. There are two libraries available which are reactstrap and react-bootstrap that help us overcome this problem. Both libraries have a similar approach to Bootstrap components. However, there exists minor differences between the two libraries that make one preferable over the other as per the requirements. Let us see a comparison between the two: React-Bootstrap: The following are the steps to create a simple react-bootstrap application npm install -g create-react-app create-react-app my_app cd my_app/ npm start Open the application at “http://localhost:3000/” Adding Bootstrap: npm install react-bootstrap bootstrap In the “myapp” directory, there is an “src” folder that has “index.js” and “App.js” files which are of our interest. Write the following code in each file as follows and view the app at http://localhost:3000/ App.js file: The “App.js” file has the following code. Javascript // Importing individual react componentsimport React from 'react'; import Jumbotron from 'react-bootstrap/Jumbotron';import Container from 'react-bootstrap/Container';import Button from 'react-bootstrap/Button'; // App function is created which contains the html// code that is displayed in the webpageconst App = () => ( <Container className="p-3"> <Jumbotron> <h1 className="header">Welcome To React-Bootstrap</h1> <Button variant="danger">Click here</Button> </Jumbotron> </Container>); export default App; index.js: The “index.js” file has the following code. Javascript import React from 'react';import ReactDOM from 'react-dom';import './index.css';import App from './App';import * as serviceWorker from './serviceWorker'; // Importing the Bootstrap CSSimport 'bootstrap/dist/css/bootstrap.min.css'; ReactDOM.render( <React.StrictMode> <App /> </React.StrictMode>, document.getElementById('root')); // For faster loading and working of app,// you can change unregister() to register()// below. Note this comes with some pitfalls.// Learn more about service workers: // https://bit.ly/CRA-PWAserviceWorker.unregister(); Output: Reactstrap: The following are the steps to create a simple reactstrap application npm install -g create-react-app create-react-app myapp cd myapp/ npm start Open “http://localhost:3000/” to see your app. Adding Bootstrap: npm i bootstrap npm i reactstrap react react-dom In the “myapp” directory, there is a “src” folder that has “index.js” and “App.js” files which are of our interest. Write the following code in each file as follows and view the app at http://localhost:3000/ App.js: The “App.js” file has the following code. Javascript // Importing individual react components to // reduce the code sizeimport React, { Component } from 'react';import { Button } from 'reactstrap';import { Jumbotron } from 'reactstrap';import { Row } from 'reactstrap';import { Col } from 'reactstrap';import { Container } from 'reactstrap'; // This is what is displayed on the webpage// we create a jumbotron having a message// and a buttonclass App extends Component { render() { return ( <div> <Jumbotron> <Container> <Row> <Col> <h1>Welcome to Reactstrap</h1> <p> <Button color="danger"> Click Me </Button> </p> </Col> </Row> </Container> </Jumbotron> </div> ); }} export default App; index.js: The “index.js” file has the following code. Javascript import React from 'react';import ReactDOM from 'react-dom';import './index.css';import App from './App';import * as serviceWorker from './serviceWorker'; import 'bootstrap/dist/css/bootstrap.css'; ReactDOM.render( <React.StrictMode> <App /> </React.StrictMode>, document.getElementById('root')); // If you want your app to work offline// and load faster, you can change// unregister() to register() below. // Note this comes with some pitfalls.// Learn more about service workers: // https://bit.ly/CRA-PWAserviceWorker.unregister(); Output: Conclusion: Reactstrap makes use of class components whereas React-bootstrap makes use of functions and hooks. Both the codes yield similar output and the only difference is the use of the components. The user may choose either depending on their preferences. Bootstrap-Misc Bootstrap Difference Between Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n25 Oct, 2020" }, { "code": null, "e": 608, "s": 52, "text": "Bootstrap is a popular front-end CSS framework used by web developers to design their web applications. Bootstrap components include HTML, CSS, and JavaScript with additional dependencies like jQuery which makes it hard to use in React applications. There are two libraries available which are reactstrap and react-bootstrap that help us overcome this problem. Both libraries have a similar approach to Bootstrap components. However, there exists minor differences between the two libraries that make one preferable over the other as per the requirements." }, { "code": null, "e": 649, "s": 608, "text": "Let us see a comparison between the two:" }, { "code": null, "e": 666, "s": 649, "text": "React-Bootstrap:" }, { "code": null, "e": 741, "s": 666, "text": "The following are the steps to create a simple react-bootstrap application" }, { "code": null, "e": 773, "s": 741, "text": "npm install -g create-react-app" }, { "code": null, "e": 797, "s": 773, "text": "create-react-app my_app" }, { "code": null, "e": 808, "s": 797, "text": "cd my_app/" }, { "code": null, "e": 818, "s": 808, "text": "npm start" }, { "code": null, "e": 868, "s": 818, "text": "Open the application at “http://localhost:3000/” " }, { "code": null, "e": 886, "s": 868, "text": "Adding Bootstrap:" }, { "code": null, "e": 924, "s": 886, "text": "npm install react-bootstrap bootstrap" }, { "code": null, "e": 1133, "s": 924, "text": "In the “myapp” directory, there is an “src” folder that has “index.js” and “App.js” files which are of our interest. Write the following code in each file as follows and view the app at http://localhost:3000/" }, { "code": null, "e": 1188, "s": 1133, "text": "App.js file: The “App.js” file has the following code." }, { "code": null, "e": 1199, "s": 1188, "text": "Javascript" }, { "code": "// Importing individual react componentsimport React from 'react'; import Jumbotron from 'react-bootstrap/Jumbotron';import Container from 'react-bootstrap/Container';import Button from 'react-bootstrap/Button'; // App function is created which contains the html// code that is displayed in the webpageconst App = () => ( <Container className=\"p-3\"> <Jumbotron> <h1 className=\"header\">Welcome To React-Bootstrap</h1> <Button variant=\"danger\">Click here</Button> </Jumbotron> </Container>); export default App;", "e": 1730, "s": 1199, "text": null }, { "code": null, "e": 1784, "s": 1730, "text": "index.js: The “index.js” file has the following code." }, { "code": null, "e": 1795, "s": 1784, "text": "Javascript" }, { "code": "import React from 'react';import ReactDOM from 'react-dom';import './index.css';import App from './App';import * as serviceWorker from './serviceWorker'; // Importing the Bootstrap CSSimport 'bootstrap/dist/css/bootstrap.min.css'; ReactDOM.render( <React.StrictMode> <App /> </React.StrictMode>, document.getElementById('root')); // For faster loading and working of app,// you can change unregister() to register()// below. Note this comes with some pitfalls.// Learn more about service workers: // https://bit.ly/CRA-PWAserviceWorker.unregister();", "e": 2354, "s": 1795, "text": null }, { "code": null, "e": 2362, "s": 2354, "text": "Output:" }, { "code": null, "e": 2374, "s": 2362, "text": "Reactstrap:" }, { "code": null, "e": 2444, "s": 2374, "text": "The following are the steps to create a simple reactstrap application" }, { "code": null, "e": 2476, "s": 2444, "text": "npm install -g create-react-app" }, { "code": null, "e": 2499, "s": 2476, "text": "create-react-app myapp" }, { "code": null, "e": 2509, "s": 2499, "text": "cd myapp/" }, { "code": null, "e": 2519, "s": 2509, "text": "npm start" }, { "code": null, "e": 2566, "s": 2519, "text": "Open “http://localhost:3000/” to see your app." }, { "code": null, "e": 2584, "s": 2566, "text": "Adding Bootstrap:" }, { "code": null, "e": 2600, "s": 2584, "text": "npm i bootstrap" }, { "code": null, "e": 2633, "s": 2600, "text": "npm i reactstrap react react-dom" }, { "code": null, "e": 2841, "s": 2633, "text": "In the “myapp” directory, there is a “src” folder that has “index.js” and “App.js” files which are of our interest. Write the following code in each file as follows and view the app at http://localhost:3000/" }, { "code": null, "e": 2891, "s": 2841, "text": "App.js: The “App.js” file has the following code." }, { "code": null, "e": 2902, "s": 2891, "text": "Javascript" }, { "code": "// Importing individual react components to // reduce the code sizeimport React, { Component } from 'react';import { Button } from 'reactstrap';import { Jumbotron } from 'reactstrap';import { Row } from 'reactstrap';import { Col } from 'reactstrap';import { Container } from 'reactstrap'; // This is what is displayed on the webpage// we create a jumbotron having a message// and a buttonclass App extends Component { render() { return ( <div> <Jumbotron> <Container> <Row> <Col> <h1>Welcome to Reactstrap</h1> <p> <Button color=\"danger\"> Click Me </Button> </p> </Col> </Row> </Container> </Jumbotron> </div> ); }} export default App;", "e": 3952, "s": 2902, "text": null }, { "code": null, "e": 4006, "s": 3952, "text": "index.js: The “index.js” file has the following code." }, { "code": null, "e": 4017, "s": 4006, "text": "Javascript" }, { "code": "import React from 'react';import ReactDOM from 'react-dom';import './index.css';import App from './App';import * as serviceWorker from './serviceWorker'; import 'bootstrap/dist/css/bootstrap.css'; ReactDOM.render( <React.StrictMode> <App /> </React.StrictMode>, document.getElementById('root')); // If you want your app to work offline// and load faster, you can change// unregister() to register() below. // Note this comes with some pitfalls.// Learn more about service workers: // https://bit.ly/CRA-PWAserviceWorker.unregister();", "e": 4560, "s": 4017, "text": null }, { "code": null, "e": 4568, "s": 4560, "text": "Output:" }, { "code": null, "e": 4580, "s": 4568, "text": "Conclusion:" }, { "code": null, "e": 4830, "s": 4580, "text": "Reactstrap makes use of class components whereas React-bootstrap makes use of functions and hooks. Both the codes yield similar output and the only difference is the use of the components. The user may choose either depending on their preferences." }, { "code": null, "e": 4845, "s": 4830, "text": "Bootstrap-Misc" }, { "code": null, "e": 4855, "s": 4845, "text": "Bootstrap" }, { "code": null, "e": 4874, "s": 4855, "text": "Difference Between" }, { "code": null, "e": 4891, "s": 4874, "text": "Web Technologies" } ]
Implementing Inorder, Preorder, Postorder Using Stack in Java
04 Jan, 2021 Data structures of two types of Linear Data Structure and the second is Non-linear Data Structure the main difference between these Data structures is the way of transverse the elements of these data structures. Linear Data Structure Transverse all elements in a single run whereas Non-Linear Data structure Transverse all elements in Hierarchy way. In this article, we will implement different types of Depth First Traversals in the Binary Tree of Non-Linear Data structure using the stack data structure. Input Binary Tree: Depth First Traversals: Inorder (Left, Root, Right) : 4 2 5 1 3Preorder (Root, Left, Right) : 1 2 4 5 3Postorder (Left, Right, Root) : 4 5 2 3 1 Inorder (Left, Root, Right) : 4 2 5 1 3 Preorder (Root, Left, Right) : 1 2 4 5 3 Postorder (Left, Right, Root) : 4 5 2 3 1 1. Create an empty stack S. 2. Initialize the current node as root. 3. Push the current node to S and set current = current->left until the current is NULL. 4. If the current is NULL and the stack is not empty then Pop the top item from the stack. Print the popped item, set current = popped_item->right Go to step 3. 5. If the current is NULL and the stack is empty then we are done. Below is the implementation of the above approach: Java // Non-Recursive Java program for inorder traversalimport java.util.Stack; // Class containing left and right child of// current node and key valueclass Node { int data; Node left, right; public Node(int item) { data = item; left = right = null; }} // Class to print the inorder traversalclass BinaryTree { Node root; void inorder() { if (root == null) return; Stack<Node> s = new Stack<Node>(); Node curr = root; // traverse the tree while (curr != null || s.size() > 0) { // Reach the left most // Node of the current Node while (curr != null) { // place pointer to a tree node on // the stack before traversing // the node's left subtree s.push(curr); curr = curr.left; } // Current must be NULL at this point curr = s.pop(); System.out.print(curr.data + " "); // we have visited the node and its // left subtree. Now, it's right // subtree's turn curr = curr.right; } } public static void main(String args[]) { // Creating a binary tree and // entering the nodes BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.inorder(); }} 4 2 5 1 3 TimeComplexity: O(n) SpaceComplexity: O(n) There are two approaches for Preorder Transversal of Binary Tree using the Stack data structure: Approach 1: This approach is totally the same which discussed in the above Transversal. Create an empty stack S.Initialize the current node as root.Push the current node to S and set current = current->left print the peek element in the stack until the current is NULL.If current is NULL and stack is not empty then a) Pop the top item from stack. b) set current = popped_item->right. c) Go to step 3.If the current is NULL and the stack is empty then we are done. Create an empty stack S. Initialize the current node as root. Push the current node to S and set current = current->left print the peek element in the stack until the current is NULL. If current is NULL and stack is not empty then a) Pop the top item from stack. b) set current = popped_item->right. c) Go to step 3. If the current is NULL and the stack is empty then we are done. Below is the implementation of the above approach: Java // Java Program for Pre order Traversalimport java.util.*;import java.io.*;class Node { int data; Node left, right; public Node(int item) { data = item; left = right = null; }} // Class to print the preorder traversalclass BinaryTree { Node root; void preorder() { if (root == null) return; Stack<Node> s = new Stack<Node>(); Node curr = root; // traverse the tree while (curr != null || s.size() > 0) { // Reach the left most // Node of the curr Node while (curr != null) { // place pointer to a tree node on // the stack before traversing // the node's left subtree s.push(curr); // print the peak element System.out.print(s.peek().data + " "); curr = curr.left; } // Current must be NULL at this point curr = s.pop(); // we have visited the node and its // left subtree. Now, it's right // subtree's turn curr = curr.right; } } public static void main(String args[]) { // creating a binary tree and // entering the nodes BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.preorder(); }} 1 2 4 5 3 Time Complexity: O(n) Space Complexity: O(n) Approach 2: In Preorder Transversal, First print the root element first then the left subtree, and then the right subtree. We know that Stack data structure follows LIFO(Last in First Out), So we take the advantage of this feature of this stack we first push the right part of the current tree and after the left part of the current tree, and in every iteration, we pop the peak element from stack and print and then again push right part of the pop element and left part of the pop element till the size of the stack is not equal to 1 because we have already printed the first element. Algorithm: Create an empty stack S. Print the root element. Push the right subtree to the stack. Push the left subtree to the stack. If the stack size is not 1 thenPop the top item from the stack.print the elementPush right Subtree of pop element to the stack.Push left Subtree of pop element to the stack. Pop the top item from the stack. print the element Push right Subtree of pop element to the stack. Push left Subtree of pop element to the stack. If the Size of the stack is 1 return to the main method Below is the implementation of the above approach: Java // Non-Recursive Java Program for preorder traversalimport java.util.Stack;// Class containing left and right child of// current node and key valueclass Node { int data; Node left, right; public Node(int item) { data = item; left = right = null; }} // Class to print the preorder traversalclass BinaryTree { Node root; void preorder() { if (root == null) { return; } Stack<Node> S = new Stack<>(); // Push root element in the stack S.add(root); // print the root element System.out.print(root.data + " "); // Push right subtree to the stack if (root.right != null) { S.add(root.right); } // Push left subtree to the stack if (root.left != null) { S.add(root.left); } // Iterate till Size of the Stack not equal to 1 while (S.size() != 1) { // Peek element of the stack Node temp = S.peek(); // pop the element from the stack S.pop(); if (temp != null) { // print the pop element System.out.print(temp.data + " "); // Push right subtree of the pop element if (temp.right != null) { S.add(temp.right); } // Push left subtree of the pop element if (temp.left != null) { S.add(temp.left); } } } } public static void main(String args[]) { // creating a binary tree and // entering the nodes BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.preorder(); }} 1 2 4 5 3 TimeComplexity: O(n) SpaceComplexity: O(n) 1. Create an empty stack 2. Do the following while the root is not NULL Push root’s right child and then the root to stack. Set root as root’s left child. 3. Pop an item from the stack and set it as root. If the popped item has a right child and the right child is at top of the stack, then remove the right child from the stack, push the root back, and set the root as root’s right child. Else print root’s data and set root as NULL. 4. Repeat steps 2 and 3 while the stack is not empty. Below is the implementation of the above approach: Java // Java program for iterative postorder// traversal using stack import java.util.ArrayList;import java.util.Stack; // A binary tree nodeclass Node { int data; Node left, right; Node(int item) { data = item; left = right; }} class BinaryTree { Node root; // An iterative function to do postorder traversal // of a given binary tree void postOrder(Node node) { Stack<Node> S = new Stack<Node>(); // Check for empty tree if (node == null) return; S.push(node); Node prev = null; while (!S.isEmpty()) { Node current = S.peek(); // go down the tree in search of a leaf an if so // process it and pop stack otherwise move down if (prev == null || prev.left == current || prev.right == current) { if (current.left != null) S.push(current.left); else if (current.right != null) S.push(current.right); else { S.pop(); System.out.print(current.data + " "); } // go up the tree from left node, if the // child is right push it onto stack // otherwise process parent and pop } else if (current.left == prev) { if (current.right != null) S.push(current.right); else { S.pop(); System.out.print(current.data + " "); } // go up the tree from right node and after // coming back from right node process parent // and pop stack } else if (current.right == prev) { S.pop(); System.out.print(current.data + " "); } prev = current; } } // Driver program to test above functions public static void main(String args[]) { BinaryTree tree = new BinaryTree(); // Let us create trees shown in above diagram tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.postOrder(tree.root); }} 4 5 2 3 1 Time Complexity: O(n) Space Complexity: O(n) Picked Technical Scripter 2020 Java Java Programs Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n04 Jan, 2021" }, { "code": null, "e": 405, "s": 54, "text": "Data structures of two types of Linear Data Structure and the second is Non-linear Data Structure the main difference between these Data structures is the way of transverse the elements of these data structures. Linear Data Structure Transverse all elements in a single run whereas Non-Linear Data structure Transverse all elements in Hierarchy way. " }, { "code": null, "e": 563, "s": 405, "text": "In this article, we will implement different types of Depth First Traversals in the Binary Tree of Non-Linear Data structure using the stack data structure. " }, { "code": null, "e": 583, "s": 563, "text": " Input Binary Tree:" }, { "code": null, "e": 607, "s": 583, "text": "Depth First Traversals:" }, { "code": null, "e": 728, "s": 607, "text": "Inorder (Left, Root, Right) : 4 2 5 1 3Preorder (Root, Left, Right) : 1 2 4 5 3Postorder (Left, Right, Root) : 4 5 2 3 1" }, { "code": null, "e": 768, "s": 728, "text": "Inorder (Left, Root, Right) : 4 2 5 1 3" }, { "code": null, "e": 809, "s": 768, "text": "Preorder (Root, Left, Right) : 1 2 4 5 3" }, { "code": null, "e": 851, "s": 809, "text": "Postorder (Left, Right, Root) : 4 5 2 3 1" }, { "code": null, "e": 879, "s": 851, "text": "1. Create an empty stack S." }, { "code": null, "e": 919, "s": 879, "text": "2. Initialize the current node as root." }, { "code": null, "e": 1008, "s": 919, "text": "3. Push the current node to S and set current = current->left until the current is NULL." }, { "code": null, "e": 1067, "s": 1008, "text": "4. If the current is NULL and the stack is not empty then " }, { "code": null, "e": 1100, "s": 1067, "text": "Pop the top item from the stack." }, { "code": null, "e": 1157, "s": 1100, "text": "Print the popped item, set current = popped_item->right " }, { "code": null, "e": 1171, "s": 1157, "text": "Go to step 3." }, { "code": null, "e": 1238, "s": 1171, "text": "5. If the current is NULL and the stack is empty then we are done." }, { "code": null, "e": 1289, "s": 1238, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 1294, "s": 1289, "text": "Java" }, { "code": "// Non-Recursive Java program for inorder traversalimport java.util.Stack; // Class containing left and right child of// current node and key valueclass Node { int data; Node left, right; public Node(int item) { data = item; left = right = null; }} // Class to print the inorder traversalclass BinaryTree { Node root; void inorder() { if (root == null) return; Stack<Node> s = new Stack<Node>(); Node curr = root; // traverse the tree while (curr != null || s.size() > 0) { // Reach the left most // Node of the current Node while (curr != null) { // place pointer to a tree node on // the stack before traversing // the node's left subtree s.push(curr); curr = curr.left; } // Current must be NULL at this point curr = s.pop(); System.out.print(curr.data + \" \"); // we have visited the node and its // left subtree. Now, it's right // subtree's turn curr = curr.right; } } public static void main(String args[]) { // Creating a binary tree and // entering the nodes BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.inorder(); }}", "e": 2855, "s": 1294, "text": null }, { "code": null, "e": 2865, "s": 2855, "text": "4 2 5 1 3" }, { "code": null, "e": 2886, "s": 2865, "text": "TimeComplexity: O(n)" }, { "code": null, "e": 2908, "s": 2886, "text": "SpaceComplexity: O(n)" }, { "code": null, "e": 3005, "s": 2908, "text": "There are two approaches for Preorder Transversal of Binary Tree using the Stack data structure:" }, { "code": null, "e": 3093, "s": 3005, "text": "Approach 1: This approach is totally the same which discussed in the above Transversal." }, { "code": null, "e": 3480, "s": 3093, "text": "Create an empty stack S.Initialize the current node as root.Push the current node to S and set current = current->left print the peek element in the stack until the current is NULL.If current is NULL and stack is not empty then a) Pop the top item from stack. b) set current = popped_item->right. c) Go to step 3.If the current is NULL and the stack is empty then we are done." }, { "code": null, "e": 3505, "s": 3480, "text": "Create an empty stack S." }, { "code": null, "e": 3542, "s": 3505, "text": "Initialize the current node as root." }, { "code": null, "e": 3664, "s": 3542, "text": "Push the current node to S and set current = current->left print the peek element in the stack until the current is NULL." }, { "code": null, "e": 3807, "s": 3664, "text": "If current is NULL and stack is not empty then a) Pop the top item from stack. b) set current = popped_item->right. c) Go to step 3." }, { "code": null, "e": 3871, "s": 3807, "text": "If the current is NULL and the stack is empty then we are done." }, { "code": null, "e": 3922, "s": 3871, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 3927, "s": 3922, "text": "Java" }, { "code": "// Java Program for Pre order Traversalimport java.util.*;import java.io.*;class Node { int data; Node left, right; public Node(int item) { data = item; left = right = null; }} // Class to print the preorder traversalclass BinaryTree { Node root; void preorder() { if (root == null) return; Stack<Node> s = new Stack<Node>(); Node curr = root; // traverse the tree while (curr != null || s.size() > 0) { // Reach the left most // Node of the curr Node while (curr != null) { // place pointer to a tree node on // the stack before traversing // the node's left subtree s.push(curr); // print the peak element System.out.print(s.peek().data + \" \"); curr = curr.left; } // Current must be NULL at this point curr = s.pop(); // we have visited the node and its // left subtree. Now, it's right // subtree's turn curr = curr.right; } } public static void main(String args[]) { // creating a binary tree and // entering the nodes BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.preorder(); }}", "e": 5464, "s": 3927, "text": null }, { "code": null, "e": 5474, "s": 5464, "text": "1 2 4 5 3" }, { "code": null, "e": 5496, "s": 5474, "text": "Time Complexity: O(n)" }, { "code": null, "e": 5519, "s": 5496, "text": "Space Complexity: O(n)" }, { "code": null, "e": 6106, "s": 5519, "text": "Approach 2: In Preorder Transversal, First print the root element first then the left subtree, and then the right subtree. We know that Stack data structure follows LIFO(Last in First Out), So we take the advantage of this feature of this stack we first push the right part of the current tree and after the left part of the current tree, and in every iteration, we pop the peak element from stack and print and then again push right part of the pop element and left part of the pop element till the size of the stack is not equal to 1 because we have already printed the first element." }, { "code": null, "e": 6117, "s": 6106, "text": "Algorithm:" }, { "code": null, "e": 6142, "s": 6117, "text": "Create an empty stack S." }, { "code": null, "e": 6166, "s": 6142, "text": "Print the root element." }, { "code": null, "e": 6203, "s": 6166, "text": "Push the right subtree to the stack." }, { "code": null, "e": 6239, "s": 6203, "text": "Push the left subtree to the stack." }, { "code": null, "e": 6414, "s": 6239, "text": "If the stack size is not 1 thenPop the top item from the stack.print the elementPush right Subtree of pop element to the stack.Push left Subtree of pop element to the stack." }, { "code": null, "e": 6447, "s": 6414, "text": "Pop the top item from the stack." }, { "code": null, "e": 6465, "s": 6447, "text": "print the element" }, { "code": null, "e": 6513, "s": 6465, "text": "Push right Subtree of pop element to the stack." }, { "code": null, "e": 6561, "s": 6513, "text": "Push left Subtree of pop element to the stack." }, { "code": null, "e": 6617, "s": 6561, "text": "If the Size of the stack is 1 return to the main method" }, { "code": null, "e": 6668, "s": 6617, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 6673, "s": 6668, "text": "Java" }, { "code": "// Non-Recursive Java Program for preorder traversalimport java.util.Stack;// Class containing left and right child of// current node and key valueclass Node { int data; Node left, right; public Node(int item) { data = item; left = right = null; }} // Class to print the preorder traversalclass BinaryTree { Node root; void preorder() { if (root == null) { return; } Stack<Node> S = new Stack<>(); // Push root element in the stack S.add(root); // print the root element System.out.print(root.data + \" \"); // Push right subtree to the stack if (root.right != null) { S.add(root.right); } // Push left subtree to the stack if (root.left != null) { S.add(root.left); } // Iterate till Size of the Stack not equal to 1 while (S.size() != 1) { // Peek element of the stack Node temp = S.peek(); // pop the element from the stack S.pop(); if (temp != null) { // print the pop element System.out.print(temp.data + \" \"); // Push right subtree of the pop element if (temp.right != null) { S.add(temp.right); } // Push left subtree of the pop element if (temp.left != null) { S.add(temp.left); } } } } public static void main(String args[]) { // creating a binary tree and // entering the nodes BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.preorder(); }}", "e": 8571, "s": 6673, "text": null }, { "code": null, "e": 8581, "s": 8571, "text": "1 2 4 5 3" }, { "code": null, "e": 8602, "s": 8581, "text": "TimeComplexity: O(n)" }, { "code": null, "e": 8624, "s": 8602, "text": "SpaceComplexity: O(n)" }, { "code": null, "e": 8649, "s": 8624, "text": "1. Create an empty stack" }, { "code": null, "e": 8696, "s": 8649, "text": "2. Do the following while the root is not NULL" }, { "code": null, "e": 8748, "s": 8696, "text": "Push root’s right child and then the root to stack." }, { "code": null, "e": 8779, "s": 8748, "text": "Set root as root’s left child." }, { "code": null, "e": 8829, "s": 8779, "text": "3. Pop an item from the stack and set it as root." }, { "code": null, "e": 9014, "s": 8829, "text": "If the popped item has a right child and the right child is at top of the stack, then remove the right child from the stack, push the root back, and set the root as root’s right child." }, { "code": null, "e": 9059, "s": 9014, "text": "Else print root’s data and set root as NULL." }, { "code": null, "e": 9113, "s": 9059, "text": "4. Repeat steps 2 and 3 while the stack is not empty." }, { "code": null, "e": 9164, "s": 9113, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 9169, "s": 9164, "text": "Java" }, { "code": "// Java program for iterative postorder// traversal using stack import java.util.ArrayList;import java.util.Stack; // A binary tree nodeclass Node { int data; Node left, right; Node(int item) { data = item; left = right; }} class BinaryTree { Node root; // An iterative function to do postorder traversal // of a given binary tree void postOrder(Node node) { Stack<Node> S = new Stack<Node>(); // Check for empty tree if (node == null) return; S.push(node); Node prev = null; while (!S.isEmpty()) { Node current = S.peek(); // go down the tree in search of a leaf an if so // process it and pop stack otherwise move down if (prev == null || prev.left == current || prev.right == current) { if (current.left != null) S.push(current.left); else if (current.right != null) S.push(current.right); else { S.pop(); System.out.print(current.data + \" \"); } // go up the tree from left node, if the // child is right push it onto stack // otherwise process parent and pop } else if (current.left == prev) { if (current.right != null) S.push(current.right); else { S.pop(); System.out.print(current.data + \" \"); } // go up the tree from right node and after // coming back from right node process parent // and pop stack } else if (current.right == prev) { S.pop(); System.out.print(current.data + \" \"); } prev = current; } } // Driver program to test above functions public static void main(String args[]) { BinaryTree tree = new BinaryTree(); // Let us create trees shown in above diagram tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.postOrder(tree.root); }}", "e": 11518, "s": 9169, "text": null }, { "code": null, "e": 11528, "s": 11518, "text": "4 5 2 3 1" }, { "code": null, "e": 11550, "s": 11528, "text": "Time Complexity: O(n)" }, { "code": null, "e": 11573, "s": 11550, "text": "Space Complexity: O(n)" }, { "code": null, "e": 11580, "s": 11573, "text": "Picked" }, { "code": null, "e": 11604, "s": 11580, "text": "Technical Scripter 2020" }, { "code": null, "e": 11609, "s": 11604, "text": "Java" }, { "code": null, "e": 11623, "s": 11609, "text": "Java Programs" }, { "code": null, "e": 11642, "s": 11623, "text": "Technical Scripter" }, { "code": null, "e": 11647, "s": 11642, "text": "Java" } ]
Commonly Asked C++ Interview Questions | Set 1
13 Sep, 2021 What are the differences between C and C++? 1) C++ is a kind of superset of C, most of C programs except few exceptions (See this and this) work in C++ as well. 2) C is a procedural programming language, but C++ supports both procedural and Object Oriented programming. 3) Since C++ supports object oriented programming, it supports features like function overloading, templates, inheritance, virtual functions, friend functions. These features are absent in C. 4) C++ supports exception handling at a language level, in C exception handling, is done in the traditional if-else style. 5) C++ supports references, C doesn’t. 6) In C, scanf() and printf() are mainly used input/output. C++ mainly uses streams to perform input and output operations. cin is standard input stream and cout is standard output stream. There are many more differences, above is a list of main differences. What are the differences between references and pointers? Both references and pointers can be used to change the local variables of one function inside another function. Both of them can also be used to save copying of big objects when passed as arguments to functions or returned from functions, to get efficiency gain. Despite the above similarities, there are the following differences between references and pointers. References are less powerful than pointers 1) Once a reference is created, it cannot be later made to reference another object; it cannot be reseated. This is often done with pointers. 2) References cannot be NULL. Pointers are often made NULL to indicate that they are not pointing to any valid thing. 3) A reference must be initialized when declared. There is no such restriction with pointers Due to the above limitations, references in C++ cannot be used for implementing data structures like Linked List, Tree, etc. In Java, references don’t have the above restrictions and can be used to implement all data structures. References being more powerful in Java is the main reason Java doesn’t need pointers.References are safer and easier to use: 1) Safer: Since references must be initialized, wild references like wild pointers are unlikely to exist. It is still possible to have references that don’t refer to a valid location (See questions 5 and 6 in the below exercise ) 2) Easier to use: References don’t need dereferencing operator to access the value. They can be used like normal variables. ‘&’ operator is needed only at the time of declaration. Also, members of an object reference can be accessed with dot operator (‘.’), unlike pointers where arrow operator (->) is needed to access members. What are virtual functions – Write an example? Virtual functions are used with inheritance, they are called according to the type of the object pointed or referred to, not according to the type of pointer or reference. In other words, virtual functions are resolved late, at runtime. The virtual keyword is used to make a function virtual. Following things are necessary to write a C++ program with runtime polymorphism (use of virtual functions) 1) A base class and a derived class. 2) A function with the same name in a base class and derived class. 3) A pointer or reference of base class type pointing or referring to an object of a derived class. For example, in the following program bp is a pointer of type Base, but a call to bp->show() calls show() function of Derived class, because bp points to an object of Derived class. C++ #include<iostream>using namespace std; class Base {public: virtual void show() { cout<<" In Base \n"; }}; class Derived: public Base {public: void show() { cout<<"In Derived \n"; }}; int main(void) { Base *bp = new Derived; bp->show(); // RUN-TIME POLYMORPHISM return 0;} Output: In Derived What is this pointer? The ‘this’ pointer is passed as a hidden argument to all nonstatic member function calls and is available as a local variable within the body of all nonstatic functions. ‘this’ pointer is a constant pointer that holds the memory address of the current object. ‘this’ pointer is not available in static member functions as static member functions can be called without any object (with class name). Can we do “delete this”? See https://www.geeksforgeeks.org/delete-this-in-c/ What are VTABLE and VPTR? the vtable is a table of function pointers. It is maintained per class. vptr is a pointer to vtable. It is maintained per object (See this for an example). The compiler adds additional code at two places to maintain and use vtable and vptr. 1) Code in every constructor. This code sets vptr of the object being created. This code sets vptr to point to vtable of the class. 2) Code with polymorphic function call (e.g. bp->show() in above code). Wherever a polymorphic call is made, the compiler inserts code to first look for vptr using a base class pointer or reference (In the above example, since the pointed or referred object is of the derived type, vptr of a derived class is accessed). Once vptr is fetched, vtable of derived class can be accessed. Using vtable, the address of the derived class function show() is accessed and called. You may also like: Practice Quizzes on C++ C/C++ Articles We will soon be covering more C++. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. sg4ipiafwot258z3lh6xa2mjq2qtxd89f49zgt7g interview-preparation placement preparation C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Bitwise Operators in C/C++ Set in C++ Standard Template Library (STL) vector erase() and clear() in C++ Priority Queue in C++ Standard Template Library (STL) Sorting a vector in C++ unordered_map in C++ STL Inheritance in C++ The C++ Standard Template Library (STL) C++ Classes and Objects Object Oriented Programming in C++
[ { "code": null, "e": 52, "s": 24, "text": "\n13 Sep, 2021" }, { "code": null, "e": 865, "s": 52, "text": "What are the differences between C and C++? 1) C++ is a kind of superset of C, most of C programs except few exceptions (See this and this) work in C++ as well. 2) C is a procedural programming language, but C++ supports both procedural and Object Oriented programming. 3) Since C++ supports object oriented programming, it supports features like function overloading, templates, inheritance, virtual functions, friend functions. These features are absent in C. 4) C++ supports exception handling at a language level, in C exception handling, is done in the traditional if-else style. 5) C++ supports references, C doesn’t. 6) In C, scanf() and printf() are mainly used input/output. C++ mainly uses streams to perform input and output operations. cin is standard input stream and cout is standard output stream." }, { "code": null, "e": 936, "s": 865, "text": "There are many more differences, above is a list of main differences. " }, { "code": null, "e": 1358, "s": 936, "text": "What are the differences between references and pointers? Both references and pointers can be used to change the local variables of one function inside another function. Both of them can also be used to save copying of big objects when passed as arguments to functions or returned from functions, to get efficiency gain. Despite the above similarities, there are the following differences between references and pointers." }, { "code": null, "e": 1754, "s": 1358, "text": "References are less powerful than pointers 1) Once a reference is created, it cannot be later made to reference another object; it cannot be reseated. This is often done with pointers. 2) References cannot be NULL. Pointers are often made NULL to indicate that they are not pointing to any valid thing. 3) A reference must be initialized when declared. There is no such restriction with pointers" }, { "code": null, "e": 2667, "s": 1754, "text": "Due to the above limitations, references in C++ cannot be used for implementing data structures like Linked List, Tree, etc. In Java, references don’t have the above restrictions and can be used to implement all data structures. References being more powerful in Java is the main reason Java doesn’t need pointers.References are safer and easier to use: 1) Safer: Since references must be initialized, wild references like wild pointers are unlikely to exist. It is still possible to have references that don’t refer to a valid location (See questions 5 and 6 in the below exercise ) 2) Easier to use: References don’t need dereferencing operator to access the value. They can be used like normal variables. ‘&’ operator is needed only at the time of declaration. Also, members of an object reference can be accessed with dot operator (‘.’), unlike pointers where arrow operator (->) is needed to access members." }, { "code": null, "e": 3007, "s": 2667, "text": "What are virtual functions – Write an example? Virtual functions are used with inheritance, they are called according to the type of the object pointed or referred to, not according to the type of pointer or reference. In other words, virtual functions are resolved late, at runtime. The virtual keyword is used to make a function virtual." }, { "code": null, "e": 3319, "s": 3007, "text": "Following things are necessary to write a C++ program with runtime polymorphism (use of virtual functions) 1) A base class and a derived class. 2) A function with the same name in a base class and derived class. 3) A pointer or reference of base class type pointing or referring to an object of a derived class." }, { "code": null, "e": 3501, "s": 3319, "text": "For example, in the following program bp is a pointer of type Base, but a call to bp->show() calls show() function of Derived class, because bp points to an object of Derived class." }, { "code": null, "e": 3505, "s": 3501, "text": "C++" }, { "code": "#include<iostream>using namespace std; class Base {public: virtual void show() { cout<<\" In Base \\n\"; }}; class Derived: public Base {public: void show() { cout<<\"In Derived \\n\"; }}; int main(void) { Base *bp = new Derived; bp->show(); // RUN-TIME POLYMORPHISM return 0;}", "e": 3799, "s": 3505, "text": null }, { "code": null, "e": 3808, "s": 3799, "text": "Output: " }, { "code": null, "e": 3819, "s": 3808, "text": "In Derived" }, { "code": null, "e": 4239, "s": 3819, "text": "What is this pointer? The ‘this’ pointer is passed as a hidden argument to all nonstatic member function calls and is available as a local variable within the body of all nonstatic functions. ‘this’ pointer is a constant pointer that holds the memory address of the current object. ‘this’ pointer is not available in static member functions as static member functions can be called without any object (with class name)." }, { "code": null, "e": 4316, "s": 4239, "text": "Can we do “delete this”? See https://www.geeksforgeeks.org/delete-this-in-c/" }, { "code": null, "e": 5185, "s": 4316, "text": "What are VTABLE and VPTR? the vtable is a table of function pointers. It is maintained per class. vptr is a pointer to vtable. It is maintained per object (See this for an example). The compiler adds additional code at two places to maintain and use vtable and vptr. 1) Code in every constructor. This code sets vptr of the object being created. This code sets vptr to point to vtable of the class. 2) Code with polymorphic function call (e.g. bp->show() in above code). Wherever a polymorphic call is made, the compiler inserts code to first look for vptr using a base class pointer or reference (In the above example, since the pointed or referred object is of the derived type, vptr of a derived class is accessed). Once vptr is fetched, vtable of derived class can be accessed. Using vtable, the address of the derived class function show() is accessed and called." }, { "code": null, "e": 5206, "s": 5185, "text": "You may also like: " }, { "code": null, "e": 5230, "s": 5206, "text": "Practice Quizzes on C++" }, { "code": null, "e": 5245, "s": 5230, "text": "C/C++ Articles" }, { "code": null, "e": 5406, "s": 5245, "text": "We will soon be covering more C++. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 5447, "s": 5406, "text": "sg4ipiafwot258z3lh6xa2mjq2qtxd89f49zgt7g" }, { "code": null, "e": 5469, "s": 5447, "text": "interview-preparation" }, { "code": null, "e": 5491, "s": 5469, "text": "placement preparation" }, { "code": null, "e": 5495, "s": 5491, "text": "C++" }, { "code": null, "e": 5499, "s": 5495, "text": "CPP" }, { "code": null, "e": 5597, "s": 5499, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5624, "s": 5597, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 5667, "s": 5624, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 5701, "s": 5667, "text": "vector erase() and clear() in C++" }, { "code": null, "e": 5755, "s": 5701, "text": "Priority Queue in C++ Standard Template Library (STL)" }, { "code": null, "e": 5779, "s": 5755, "text": "Sorting a vector in C++" }, { "code": null, "e": 5804, "s": 5779, "text": "unordered_map in C++ STL" }, { "code": null, "e": 5823, "s": 5804, "text": "Inheritance in C++" }, { "code": null, "e": 5863, "s": 5823, "text": "The C++ Standard Template Library (STL)" }, { "code": null, "e": 5887, "s": 5863, "text": "C++ Classes and Objects" } ]
Print all leaf nodes of an n-ary tree using DFS
05 Aug, 2021 Given an array edge[][2] where (edge[i][0], edge[i][1]) defines an edge in the n-ary tree, the task is to print all the leaf nodes of the given tree using. Examples: Input: edge[][] = {{1, 2}, {1, 3}, {2, 4}, {2, 5}, {3, 6}} Output: 4 5 6 1 / \ 2 3 / \ \ 4 5 6 Input: edge[][] = {{1, 5}, {1, 7}, {5, 6}} Output: 6 7 Approach: DFS can be used to traverse the complete tree. We will keep track of parent while traversing to avoid the visited node array. Initially for every node we can set a flag and if the node have at least one child (i.e. non-leaf node) then we will reset the flag. The nodes with no children are the leaf nodes. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to perform DFS on the treevoid dfs(list<int> t[], int node, int parent){ int flag = 1; // Iterating the children of current node for (auto ir : t[node]) { // There is at least a child // of the current node if (ir != parent) { flag = 0; dfs(t, ir, node); } } // Current node is connected to only // its parent i.e. it is a leaf node if (flag == 1) cout << node << " ";} // Driver codeint main(){ // Adjacency list list<int> t[1005]; // List of all edges pair<int, int> edges[] = { { 1, 2 }, { 1, 3 }, { 2, 4 }, { 3, 5 }, { 3, 6 }, { 3, 7 }, { 6, 8 } }; // Count of edges int cnt = sizeof(edges) / sizeof(edges[0]); // Number of nodes int node = cnt + 1; // Create the tree for (int i = 0; i < cnt; i++) { t[edges[i].first].push_back(edges[i].second); t[edges[i].second].push_back(edges[i].first); } // Function call dfs(t, 1, 0); return 0;} // Java implementation of the approachimport java.util.*; class GFG{ // Pair classstatic class pair{ int first,second; pair(int a, int b) { first = a; second = b; }} // Function to perform DFS on the treestatic void dfs(Vector t, int node, int parent){ int flag = 1; // Iterating the children of current node for (int i = 0; i < ((Vector)t.get(node)).size(); i++) { int ir = (int)((Vector)t.get(node)).get(i); // There is at least a child // of the current node if (ir != parent) { flag = 0; dfs(t, ir, node); } } // Current node is connected to only // its parent i.e. it is a leaf node if (flag == 1) System.out.print( node + " ");} // Driver codepublic static void main(String args[]){ // Adjacency list Vector t = new Vector(); // List of all edges pair edges[] = { new pair( 1, 2 ), new pair( 1, 3 ), new pair( 2, 4 ), new pair( 3, 5 ), new pair( 3, 6 ), new pair( 3, 7 ), new pair( 6, 8 ) }; // Count of edges int cnt = edges.length; // Number of nodes int node = cnt + 1; for(int i = 0; i < 1005; i++) { t.add(new Vector()); } // Create the tree for (int i = 0; i < cnt; i++) { ((Vector)t.get(edges[i].first)).add(edges[i].second); ((Vector)t.get(edges[i].second)).add(edges[i].first); } // Function call dfs(t, 1, 0);}} // This code is contributed by Arnab Kundu # Python3 implementation of the approacht = [[] for i in range(1005)] # Function to perform DFS on the treedef dfs(node, parent): flag = 1 # Iterating the children of current node for ir in t[node]: # There is at least a child # of the current node if (ir != parent): flag = 0 dfs(ir, node) # Current node is connected to only # its parent i.e. it is a leaf node if (flag == 1): print(node, end = " ") # Driver code # List of all edgesedges = [[ 1, 2 ], [ 1, 3 ], [ 2, 4 ], [ 3, 5 ], [ 3, 6 ], [ 3, 7 ], [ 6, 8 ]] # Count of edgescnt = len(edges) # Number of nodesnode = cnt + 1 # Create the treefor i in range(cnt): t[edges[i][0]].append(edges[i][1]) t[edges[i][1]].append(edges[i][0]) # Function calldfs(1, 0) # This code is contributed by Mohit Kumar // C# implementation of the approachusing System.Collections;using System.Collections.Generic;using System; class GFG{ // Pair classclass pair{ public int first, second; public pair(int a, int b) { first = a; second = b; }} // Function to perform DFS on the treestatic void dfs(ArrayList t, int node, int parent){ int flag = 1; // Iterating the children of current node for(int i = 0; i < ((ArrayList)t[node]).Count; i++) { int ir = (int)((ArrayList)t[node])[i]; // There is at least a child // of the current node if (ir != parent) { flag = 0; dfs(t, ir, node); } } // Current node is connected to only // its parent i.e. it is a leaf node if (flag == 1) Console.Write( node + " ");} // Driver codepublic static void Main(string []args){ // Adjacency list ArrayList t = new ArrayList(); // List of all edges pair []edges = { new pair(1, 2), new pair(1, 3), new pair(2, 4), new pair(3, 5), new pair(3, 6), new pair(3, 7), new pair(6, 8) }; // Count of edges int cnt = edges.Length; for(int i = 0; i < 1005; i++) { t.Add(new ArrayList()); } // Create the tree for(int i = 0; i < cnt; i++) { ((ArrayList)t[edges[i].first]).Add( edges[i].second); ((ArrayList)t[edges[i].second]).Add( edges[i].first); } // Function call dfs(t, 1, 0);}} // This code is contributed by rutvik_56 <script> // Javascript implementation of the approach // Function to perform DFS on the treefunction dfs(t, node, parent){ let flag = 1; // Iterating the children of current node for(let i = 0; i < t[node].length; i++) { let ir = t[node][i]; // There is at least a child // of the current node if (ir != parent) { flag = 0; dfs(t, ir, node); } } // Current node is connected to only // its parent i.e. it is a leaf node if (flag == 1) document.write( node + " ");} // Driver code // Adjacency listlet t = [] // List of all edgeslet edges = [ [ 1, 2 ], [ 1, 3 ], [ 2, 4 ], [ 3, 5 ], [ 3, 6 ], [ 3, 7 ], [ 6, 8 ] ]; // Count of edgeslet cnt = edges.length; // Number of nodeslet node = cnt + 1; for(let i = 0; i < 1005; i++){ t.push([]);} // Create the treefor(let i = 0; i < cnt; i++){ t[edges[i][0]].push(edges[i][1]) t[edges[i][1]].push(edges[i][0])} // Function calldfs(t, 1, 0); // This code is contributed by patel2127 </script> 4 5 8 7 Time Complexity: O(N), where N is the number of nodes in the graph.Auxiliary Space: O(N) mohit kumar 29 andrew1234 rutvik_56 patel2127 pankajsharmagfg DFS n-ary-tree Algorithms Tree DFS Tree Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n05 Aug, 2021" }, { "code": null, "e": 209, "s": 53, "text": "Given an array edge[][2] where (edge[i][0], edge[i][1]) defines an edge in the n-ary tree, the task is to print all the leaf nodes of the given tree using." }, { "code": null, "e": 221, "s": 209, "text": "Examples: " }, { "code": null, "e": 390, "s": 221, "text": "Input: edge[][] = {{1, 2}, {1, 3}, {2, 4}, {2, 5}, {3, 6}}\nOutput: 4 5 6\n 1\n / \\\n 2 3\n / \\ \\\n4 5 6\n\nInput: edge[][] = {{1, 5}, {1, 7}, {5, 6}}\nOutput: 6 7" }, { "code": null, "e": 706, "s": 390, "text": "Approach: DFS can be used to traverse the complete tree. We will keep track of parent while traversing to avoid the visited node array. Initially for every node we can set a flag and if the node have at least one child (i.e. non-leaf node) then we will reset the flag. The nodes with no children are the leaf nodes." }, { "code": null, "e": 759, "s": 706, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 763, "s": 759, "text": "C++" }, { "code": null, "e": 768, "s": 763, "text": "Java" }, { "code": null, "e": 776, "s": 768, "text": "Python3" }, { "code": null, "e": 779, "s": 776, "text": "C#" }, { "code": null, "e": 790, "s": 779, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to perform DFS on the treevoid dfs(list<int> t[], int node, int parent){ int flag = 1; // Iterating the children of current node for (auto ir : t[node]) { // There is at least a child // of the current node if (ir != parent) { flag = 0; dfs(t, ir, node); } } // Current node is connected to only // its parent i.e. it is a leaf node if (flag == 1) cout << node << \" \";} // Driver codeint main(){ // Adjacency list list<int> t[1005]; // List of all edges pair<int, int> edges[] = { { 1, 2 }, { 1, 3 }, { 2, 4 }, { 3, 5 }, { 3, 6 }, { 3, 7 }, { 6, 8 } }; // Count of edges int cnt = sizeof(edges) / sizeof(edges[0]); // Number of nodes int node = cnt + 1; // Create the tree for (int i = 0; i < cnt; i++) { t[edges[i].first].push_back(edges[i].second); t[edges[i].second].push_back(edges[i].first); } // Function call dfs(t, 1, 0); return 0;}", "e": 2048, "s": 790, "text": null }, { "code": "// Java implementation of the approachimport java.util.*; class GFG{ // Pair classstatic class pair{ int first,second; pair(int a, int b) { first = a; second = b; }} // Function to perform DFS on the treestatic void dfs(Vector t, int node, int parent){ int flag = 1; // Iterating the children of current node for (int i = 0; i < ((Vector)t.get(node)).size(); i++) { int ir = (int)((Vector)t.get(node)).get(i); // There is at least a child // of the current node if (ir != parent) { flag = 0; dfs(t, ir, node); } } // Current node is connected to only // its parent i.e. it is a leaf node if (flag == 1) System.out.print( node + \" \");} // Driver codepublic static void main(String args[]){ // Adjacency list Vector t = new Vector(); // List of all edges pair edges[] = { new pair( 1, 2 ), new pair( 1, 3 ), new pair( 2, 4 ), new pair( 3, 5 ), new pair( 3, 6 ), new pair( 3, 7 ), new pair( 6, 8 ) }; // Count of edges int cnt = edges.length; // Number of nodes int node = cnt + 1; for(int i = 0; i < 1005; i++) { t.add(new Vector()); } // Create the tree for (int i = 0; i < cnt; i++) { ((Vector)t.get(edges[i].first)).add(edges[i].second); ((Vector)t.get(edges[i].second)).add(edges[i].first); } // Function call dfs(t, 1, 0);}} // This code is contributed by Arnab Kundu", "e": 3655, "s": 2048, "text": null }, { "code": "# Python3 implementation of the approacht = [[] for i in range(1005)] # Function to perform DFS on the treedef dfs(node, parent): flag = 1 # Iterating the children of current node for ir in t[node]: # There is at least a child # of the current node if (ir != parent): flag = 0 dfs(ir, node) # Current node is connected to only # its parent i.e. it is a leaf node if (flag == 1): print(node, end = \" \") # Driver code # List of all edgesedges = [[ 1, 2 ], [ 1, 3 ], [ 2, 4 ], [ 3, 5 ], [ 3, 6 ], [ 3, 7 ], [ 6, 8 ]] # Count of edgescnt = len(edges) # Number of nodesnode = cnt + 1 # Create the treefor i in range(cnt): t[edges[i][0]].append(edges[i][1]) t[edges[i][1]].append(edges[i][0]) # Function calldfs(1, 0) # This code is contributed by Mohit Kumar", "e": 4534, "s": 3655, "text": null }, { "code": "// C# implementation of the approachusing System.Collections;using System.Collections.Generic;using System; class GFG{ // Pair classclass pair{ public int first, second; public pair(int a, int b) { first = a; second = b; }} // Function to perform DFS on the treestatic void dfs(ArrayList t, int node, int parent){ int flag = 1; // Iterating the children of current node for(int i = 0; i < ((ArrayList)t[node]).Count; i++) { int ir = (int)((ArrayList)t[node])[i]; // There is at least a child // of the current node if (ir != parent) { flag = 0; dfs(t, ir, node); } } // Current node is connected to only // its parent i.e. it is a leaf node if (flag == 1) Console.Write( node + \" \");} // Driver codepublic static void Main(string []args){ // Adjacency list ArrayList t = new ArrayList(); // List of all edges pair []edges = { new pair(1, 2), new pair(1, 3), new pair(2, 4), new pair(3, 5), new pair(3, 6), new pair(3, 7), new pair(6, 8) }; // Count of edges int cnt = edges.Length; for(int i = 0; i < 1005; i++) { t.Add(new ArrayList()); } // Create the tree for(int i = 0; i < cnt; i++) { ((ArrayList)t[edges[i].first]).Add( edges[i].second); ((ArrayList)t[edges[i].second]).Add( edges[i].first); } // Function call dfs(t, 1, 0);}} // This code is contributed by rutvik_56", "e": 6220, "s": 4534, "text": null }, { "code": "<script> // Javascript implementation of the approach // Function to perform DFS on the treefunction dfs(t, node, parent){ let flag = 1; // Iterating the children of current node for(let i = 0; i < t[node].length; i++) { let ir = t[node][i]; // There is at least a child // of the current node if (ir != parent) { flag = 0; dfs(t, ir, node); } } // Current node is connected to only // its parent i.e. it is a leaf node if (flag == 1) document.write( node + \" \");} // Driver code // Adjacency listlet t = [] // List of all edgeslet edges = [ [ 1, 2 ], [ 1, 3 ], [ 2, 4 ], [ 3, 5 ], [ 3, 6 ], [ 3, 7 ], [ 6, 8 ] ]; // Count of edgeslet cnt = edges.length; // Number of nodeslet node = cnt + 1; for(let i = 0; i < 1005; i++){ t.push([]);} // Create the treefor(let i = 0; i < cnt; i++){ t[edges[i][0]].push(edges[i][1]) t[edges[i][1]].push(edges[i][0])} // Function calldfs(t, 1, 0); // This code is contributed by patel2127 </script>", "e": 7315, "s": 6220, "text": null }, { "code": null, "e": 7323, "s": 7315, "text": "4 5 8 7" }, { "code": null, "e": 7414, "s": 7325, "text": "Time Complexity: O(N), where N is the number of nodes in the graph.Auxiliary Space: O(N)" }, { "code": null, "e": 7429, "s": 7414, "text": "mohit kumar 29" }, { "code": null, "e": 7440, "s": 7429, "text": "andrew1234" }, { "code": null, "e": 7450, "s": 7440, "text": "rutvik_56" }, { "code": null, "e": 7460, "s": 7450, "text": "patel2127" }, { "code": null, "e": 7476, "s": 7460, "text": "pankajsharmagfg" }, { "code": null, "e": 7480, "s": 7476, "text": "DFS" }, { "code": null, "e": 7491, "s": 7480, "text": "n-ary-tree" }, { "code": null, "e": 7502, "s": 7491, "text": "Algorithms" }, { "code": null, "e": 7507, "s": 7502, "text": "Tree" }, { "code": null, "e": 7511, "s": 7507, "text": "DFS" }, { "code": null, "e": 7516, "s": 7511, "text": "Tree" }, { "code": null, "e": 7527, "s": 7516, "text": "Algorithms" } ]
How to show Page Loading div until the page has finished loading?
27 Sep, 2019 There are a lot of ways in which we can show a loading div but we have figured out the most optimal solution for you and that too in pure vanilla JavaScript. We will use the document.readyState property. When the value of this property changes, a readystatechange event fires on the document object. The document.readyState property can return these three string values: loading: when the document is still loading. interactive: when the document has finished loading but sub-resources such as stylesheets, images and frames are still loading. complete: when the document and all sub-resources have finished loading. Let’s have a look at the JavaScript code: document.onreadystatechange = function() { if (document.readyState !== "complete") { document.querySelector("body").style.visibility = "hidden"; document.querySelector("#loader").style.visibility = "visible"; } else { document.querySelector("#loader").style.display = "none"; document.querySelector("body").style.visibility = "visible"; }}; When document.readyState changes, readystatechange event fires and our function executes. If the document is not yet loaded then the body should remain hidden from the user, only the loader should be visible. Once the page has completely loaded we set loader’s display to none and we make the body visible. Example: <!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title>Loader Demo</title> <style> #loader { border: 12px solid #f3f3f3; border-radius: 50%; border-top: 12px solid #444444; width: 70px; height: 70px; animation: spin 1s linear infinite; } @keyframes spin { 100% { transform: rotate(360deg); } } .center { position: absolute; top: 0; bottom: 0; left: 0; right: 0; margin: auto; } </style></head> <body> <div id="loader" class="center"></div> <h1>GeeksforGeeks</h1> <h2>A computer science portal for geeks</h2> <img src="https://i.imgur.com/KsQJA8I.png" alt="GeeksforGeeks logo" /> <script> document.onreadystatechange = function() { if (document.readyState !== "complete") { document.querySelector( "body").style.visibility = "hidden"; document.querySelector( "#loader").style.visibility = "visible"; } else { document.querySelector( "#loader").style.display = "none"; document.querySelector( "body").style.visibility = "visible"; } }; </script></body> </html> To see the code in action, you need to follow these simple steps:Step 1: Copy and paste the example code from above in a text editor and save it with .html extension. Step 2: Open the .html file you saved then open your browser’s developer tool, go to the networks tab and set throttling to Slow 3G. Here’s a GIF to show you how to do it: Setting network throttling to slow 3G in developer’s tool Step 3: Reload the page using ctrl + f5. Here’s how the final output looks like: Final output JavaScript-Misc Picked JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n27 Sep, 2019" }, { "code": null, "e": 328, "s": 28, "text": "There are a lot of ways in which we can show a loading div but we have figured out the most optimal solution for you and that too in pure vanilla JavaScript. We will use the document.readyState property. When the value of this property changes, a readystatechange event fires on the document object." }, { "code": null, "e": 399, "s": 328, "text": "The document.readyState property can return these three string values:" }, { "code": null, "e": 444, "s": 399, "text": "loading: when the document is still loading." }, { "code": null, "e": 572, "s": 444, "text": "interactive: when the document has finished loading but sub-resources such as stylesheets, images and frames are still loading." }, { "code": null, "e": 645, "s": 572, "text": "complete: when the document and all sub-resources have finished loading." }, { "code": null, "e": 687, "s": 645, "text": "Let’s have a look at the JavaScript code:" }, { "code": "document.onreadystatechange = function() { if (document.readyState !== \"complete\") { document.querySelector(\"body\").style.visibility = \"hidden\"; document.querySelector(\"#loader\").style.visibility = \"visible\"; } else { document.querySelector(\"#loader\").style.display = \"none\"; document.querySelector(\"body\").style.visibility = \"visible\"; }};", "e": 1065, "s": 687, "text": null }, { "code": null, "e": 1372, "s": 1065, "text": "When document.readyState changes, readystatechange event fires and our function executes. If the document is not yet loaded then the body should remain hidden from the user, only the loader should be visible. Once the page has completely loaded we set loader’s display to none and we make the body visible." }, { "code": null, "e": 1381, "s": 1372, "text": "Example:" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> <meta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\" /> <title>Loader Demo</title> <style> #loader { border: 12px solid #f3f3f3; border-radius: 50%; border-top: 12px solid #444444; width: 70px; height: 70px; animation: spin 1s linear infinite; } @keyframes spin { 100% { transform: rotate(360deg); } } .center { position: absolute; top: 0; bottom: 0; left: 0; right: 0; margin: auto; } </style></head> <body> <div id=\"loader\" class=\"center\"></div> <h1>GeeksforGeeks</h1> <h2>A computer science portal for geeks</h2> <img src=\"https://i.imgur.com/KsQJA8I.png\" alt=\"GeeksforGeeks logo\" /> <script> document.onreadystatechange = function() { if (document.readyState !== \"complete\") { document.querySelector( \"body\").style.visibility = \"hidden\"; document.querySelector( \"#loader\").style.visibility = \"visible\"; } else { document.querySelector( \"#loader\").style.display = \"none\"; document.querySelector( \"body\").style.visibility = \"visible\"; } }; </script></body> </html>", "e": 2947, "s": 1381, "text": null }, { "code": null, "e": 3114, "s": 2947, "text": "To see the code in action, you need to follow these simple steps:Step 1: Copy and paste the example code from above in a text editor and save it with .html extension." }, { "code": null, "e": 3286, "s": 3114, "text": "Step 2: Open the .html file you saved then open your browser’s developer tool, go to the networks tab and set throttling to Slow 3G. Here’s a GIF to show you how to do it:" }, { "code": null, "e": 3344, "s": 3286, "text": "Setting network throttling to slow 3G in developer’s tool" }, { "code": null, "e": 3425, "s": 3344, "text": "Step 3: Reload the page using ctrl + f5. Here’s how the final output looks like:" }, { "code": null, "e": 3438, "s": 3425, "text": "Final output" }, { "code": null, "e": 3454, "s": 3438, "text": "JavaScript-Misc" }, { "code": null, "e": 3461, "s": 3454, "text": "Picked" }, { "code": null, "e": 3472, "s": 3461, "text": "JavaScript" }, { "code": null, "e": 3489, "s": 3472, "text": "Web Technologies" }, { "code": null, "e": 3516, "s": 3489, "text": "Web technologies Questions" } ]
Asyncio Is Not Parallelism. You may have heard that Python asyncio... | by Peter Xie | Towards Data Science
Let’s start with a perfect concurrent example #1. Async function say_after is an example from Python official documentation. It prints something ‘what’ after sleeping ‘delay’ seconds. In the main function, we create two tasks of say_after, one says ‘hello’ after 1 second and the other say ‘world’ after 2 seconds. Run it and we see it takes 2 seconds in total because both tasks run concurrently. Perfect! But are they parallel? Let’s play around with more examples to understand the difference between concurrency and parallelism. Example #2: We replace the main function as follows. As you can see, we add a print after creating tasks to check if tasks start immediately after creation, and add an async sleep 0.5 seconds after that in the main function. Note that main itself is a task (coroutine exactly). Below is the output: First, it still takes 2 seconds in total, no change. It runs main and other two say_after tasks concurrently. The async sleep in the main is not blocking. Second, “Before delay — after creating tasks” is printed before starting say_after tasks. Yes! Created tasks do not start immediately after creation, instead, it is scheduled to run in a so-called event loop. They start only when the main task is waiting, i.e. await asyncio.sleep(0.5) in this case. And to my understanding, you cannot control the sequence of execution, i.e. priorities, of the tasks. Example #3: In this example, we replace the asyncio.sleep with time.sleep which waits with blocking in main, and see when say_after tasks start. See that the total is now 2.5 seconds. And task1 starts 0.5 second after it is created. It is clear that tasks are not parallel, i.e. execute at the same time. Example #4: You may argue that asyncio.sleep should be used instead of time.sleep with asyncio programming. How about the main task is doing something and causes the delay? In this example we replace time.sleep with a loop to add about 1 second delay in the main task. You see that we got a similar result. say_after tasks are delayed to start and the total time becomes 3 seconds. Example #5: If a task starts, does it guarantee it ends in expected time? No!Let’s see this example below. We have asyncio.sleep(0.1) in line #7 to allow task1 and task2 to start, but add time.sleep(3) in line #8 to block for 3 seconds afterwards.Here is the output: You see both tasks start immediately in line #3 and #4, but do not ‘say’ after the expected 1 seconds or 2 seconds, instead ‘say’ (end) after 3 seconds. The reason is that when say_after is awaiting for 1 / 2 seconds, the event loop goes back to main task and blocks there for 3 seconds before it can loop back to say_after tasks to continue. You can find the full demo file here. Asynicio tries the best to be concurrent but it is not parallel. You cannot control the start nor the end of a task. You may control the start if you await the task immediately after it is created as follows, but it becomes synchronous programming then, which makes no sense for asynchronous purpose. Note even that is not 100 percent guaranteed and think yourself. task1 = asyncio.create_task(say_after(1, ‘hello’))await task1 So if you are developing a timing-sensitive app, avoid using asyncio (coroutine event loop broadly). The cause of this limitation is that the event loop uses only one thread to schedule multiple tasks. So what’s the solution for parallelism? Threading. This is the equivalent code for example #5 which has 3 seconds blocking sleep in the main function. And the output is as follows. See that both task1 and task2 start immediately and ends in expected 1 and 2 seconds. You can use multiprocessing as well to make use of multiple CPU cores. Lastly, I am not saying you should not use the event loop, which is great in handling network volumes. But it depends on your need.
[ { "code": null, "e": 222, "s": 172, "text": "Let’s start with a perfect concurrent example #1." }, { "code": null, "e": 356, "s": 222, "text": "Async function say_after is an example from Python official documentation. It prints something ‘what’ after sleeping ‘delay’ seconds." }, { "code": null, "e": 579, "s": 356, "text": "In the main function, we create two tasks of say_after, one says ‘hello’ after 1 second and the other say ‘world’ after 2 seconds. Run it and we see it takes 2 seconds in total because both tasks run concurrently. Perfect!" }, { "code": null, "e": 705, "s": 579, "text": "But are they parallel? Let’s play around with more examples to understand the difference between concurrency and parallelism." }, { "code": null, "e": 717, "s": 705, "text": "Example #2:" }, { "code": null, "e": 758, "s": 717, "text": "We replace the main function as follows." }, { "code": null, "e": 983, "s": 758, "text": "As you can see, we add a print after creating tasks to check if tasks start immediately after creation, and add an async sleep 0.5 seconds after that in the main function. Note that main itself is a task (coroutine exactly)." }, { "code": null, "e": 1004, "s": 983, "text": "Below is the output:" }, { "code": null, "e": 1159, "s": 1004, "text": "First, it still takes 2 seconds in total, no change. It runs main and other two say_after tasks concurrently. The async sleep in the main is not blocking." }, { "code": null, "e": 1561, "s": 1159, "text": "Second, “Before delay — after creating tasks” is printed before starting say_after tasks. Yes! Created tasks do not start immediately after creation, instead, it is scheduled to run in a so-called event loop. They start only when the main task is waiting, i.e. await asyncio.sleep(0.5) in this case. And to my understanding, you cannot control the sequence of execution, i.e. priorities, of the tasks." }, { "code": null, "e": 1573, "s": 1561, "text": "Example #3:" }, { "code": null, "e": 1706, "s": 1573, "text": "In this example, we replace the asyncio.sleep with time.sleep which waits with blocking in main, and see when say_after tasks start." }, { "code": null, "e": 1866, "s": 1706, "text": "See that the total is now 2.5 seconds. And task1 starts 0.5 second after it is created. It is clear that tasks are not parallel, i.e. execute at the same time." }, { "code": null, "e": 1878, "s": 1866, "text": "Example #4:" }, { "code": null, "e": 2039, "s": 1878, "text": "You may argue that asyncio.sleep should be used instead of time.sleep with asyncio programming. How about the main task is doing something and causes the delay?" }, { "code": null, "e": 2135, "s": 2039, "text": "In this example we replace time.sleep with a loop to add about 1 second delay in the main task." }, { "code": null, "e": 2248, "s": 2135, "text": "You see that we got a similar result. say_after tasks are delayed to start and the total time becomes 3 seconds." }, { "code": null, "e": 2260, "s": 2248, "text": "Example #5:" }, { "code": null, "e": 2355, "s": 2260, "text": "If a task starts, does it guarantee it ends in expected time? No!Let’s see this example below." }, { "code": null, "e": 2515, "s": 2355, "text": "We have asyncio.sleep(0.1) in line #7 to allow task1 and task2 to start, but add time.sleep(3) in line #8 to block for 3 seconds afterwards.Here is the output:" }, { "code": null, "e": 2668, "s": 2515, "text": "You see both tasks start immediately in line #3 and #4, but do not ‘say’ after the expected 1 seconds or 2 seconds, instead ‘say’ (end) after 3 seconds." }, { "code": null, "e": 2858, "s": 2668, "text": "The reason is that when say_after is awaiting for 1 / 2 seconds, the event loop goes back to main task and blocks there for 3 seconds before it can loop back to say_after tasks to continue." }, { "code": null, "e": 2896, "s": 2858, "text": "You can find the full demo file here." }, { "code": null, "e": 2961, "s": 2896, "text": "Asynicio tries the best to be concurrent but it is not parallel." }, { "code": null, "e": 3013, "s": 2961, "text": "You cannot control the start nor the end of a task." }, { "code": null, "e": 3262, "s": 3013, "text": "You may control the start if you await the task immediately after it is created as follows, but it becomes synchronous programming then, which makes no sense for asynchronous purpose. Note even that is not 100 percent guaranteed and think yourself." }, { "code": null, "e": 3324, "s": 3262, "text": "task1 = asyncio.create_task(say_after(1, ‘hello’))await task1" }, { "code": null, "e": 3526, "s": 3324, "text": "So if you are developing a timing-sensitive app, avoid using asyncio (coroutine event loop broadly). The cause of this limitation is that the event loop uses only one thread to schedule multiple tasks." }, { "code": null, "e": 3577, "s": 3526, "text": "So what’s the solution for parallelism? Threading." }, { "code": null, "e": 3677, "s": 3577, "text": "This is the equivalent code for example #5 which has 3 seconds blocking sleep in the main function." }, { "code": null, "e": 3707, "s": 3677, "text": "And the output is as follows." }, { "code": null, "e": 3793, "s": 3707, "text": "See that both task1 and task2 start immediately and ends in expected 1 and 2 seconds." }, { "code": null, "e": 3864, "s": 3793, "text": "You can use multiprocessing as well to make use of multiple CPU cores." } ]
How to play videos in Android TextureView using Kotlin?
This example demonstrates how to play videos in Android TextureView using Kotlin. 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:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="8dp" tools:context=".MainActivity"> <TextureView android:id="@+id/textureView" android:layout_width="match_parent" android:layout_height="match_parent"/> </LinearLayout> Step 3 − Create an asset folder and copy-paste the video into the asset folder. Step 4 − Add the following code to MainActivity.kt import android.content.res.AssetFileDescriptor import android.graphics.SurfaceTexture import android.media.MediaPlayer import android.media.MediaPlayer.OnVideoSizeChangedListener import android.os.Build import android.os.Bundle import android.view.Surface import android.view.TextureView import android.view.TextureView.SurfaceTextureListener import androidx.appcompat.app.AppCompatActivity import java.io.IOException class MainActivity : AppCompatActivity(), SurfaceTextureListener, OnVideoSizeChangedListener { private lateinit var textureView: TextureView private lateinit var mediaPlayer: MediaPlayer private lateinit var fileDescriptor: AssetFileDescriptor override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) title = "KotlinApp" textureView = findViewById(R.id.textureView) textureView.surfaceTextureListener = this mediaPlayer = MediaPlayer() try { fileDescriptor = assets.openFd("videoplay.mp4") } catch (e: IOException) { e.printStackTrace() } } override fun onSurfaceTextureAvailable(surfaceTexture: SurfaceTexture, width: Int, height: Int) { val surface = Surface(surfaceTexture) try { mediaPlayer.setSurface(surface) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { mediaPlayer.setDataSource(fileDescriptor) mediaPlayer.prepareAsync() mediaPlayer.setOnPreparedListener { mediaPlayer.start() } } } catch (e: IOException) { e.printStackTrace() } } override fun onSurfaceTextureSizeChanged(surface: SurfaceTexture, width: Int, height: Int) {} override fun onSurfaceTextureDestroyed(surface: SurfaceTexture): Boolean { return false } override fun onSurfaceTextureUpdated(surface: SurfaceTexture) {} override fun onVideoSizeChanged(mp: MediaPlayer, width: Int, height: Int) {} } 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.kotlipapp"> <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 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 − Click here to download the project code.
[ { "code": null, "e": 1144, "s": 1062, "text": "This example demonstrates how to play videos in Android TextureView using Kotlin." }, { "code": null, "e": 1272, "s": 1144, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒New Project and fill all required details to create a new project." }, { "code": null, "e": 1337, "s": 1272, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 1826, "s": 1337, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout 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 android:orientation=\"vertical\"\n android:padding=\"8dp\"\n tools:context=\".MainActivity\">\n <TextureView\n android:id=\"@+id/textureView\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"/>\n</LinearLayout>" }, { "code": null, "e": 1906, "s": 1826, "text": "Step 3 − Create an asset folder and copy-paste the video into the asset folder." }, { "code": null, "e": 1957, "s": 1906, "text": "Step 4 − Add the following code to MainActivity.kt" }, { "code": null, "e": 3944, "s": 1957, "text": "import android.content.res.AssetFileDescriptor\nimport android.graphics.SurfaceTexture\nimport android.media.MediaPlayer\nimport android.media.MediaPlayer.OnVideoSizeChangedListener\nimport android.os.Build\nimport android.os.Bundle\nimport android.view.Surface\nimport android.view.TextureView\nimport android.view.TextureView.SurfaceTextureListener\nimport androidx.appcompat.app.AppCompatActivity\nimport java.io.IOException\nclass MainActivity : AppCompatActivity(), SurfaceTextureListener, OnVideoSizeChangedListener {\n private lateinit var textureView: TextureView\n private lateinit var mediaPlayer: MediaPlayer\n private lateinit var fileDescriptor: AssetFileDescriptor\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n textureView = findViewById(R.id.textureView)\n textureView.surfaceTextureListener = this\n mediaPlayer = MediaPlayer()\n try {\n fileDescriptor = assets.openFd(\"videoplay.mp4\")\n }\n catch (e: IOException) {\n e.printStackTrace()\n }\n }\n override fun onSurfaceTextureAvailable(surfaceTexture: SurfaceTexture, width: Int, height: Int) {\n val surface = Surface(surfaceTexture)\n try {\n mediaPlayer.setSurface(surface)\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {\n mediaPlayer.setDataSource(fileDescriptor)\n mediaPlayer.prepareAsync()\n mediaPlayer.setOnPreparedListener { mediaPlayer.start() }\n }\n }\n catch (e: IOException) {\n e.printStackTrace()\n }\n }\n override fun onSurfaceTextureSizeChanged(surface: SurfaceTexture, width: Int, height: Int) {}\n override fun onSurfaceTextureDestroyed(surface: SurfaceTexture): Boolean {\n return false\n }\n override fun onSurfaceTextureUpdated(surface: SurfaceTexture) {}\n override fun onVideoSizeChanged(mp: MediaPlayer, width: Int, height: Int) {}\n}" }, { "code": null, "e": 3999, "s": 3944, "text": "Step 5 − Add the following code to androidManifest.xml" }, { "code": null, "e": 4675, "s": 3999, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"app.com.kotlipapp\">\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": 5026, "s": 4675, "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 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": 5067, "s": 5026, "text": "Click here to download the project code." } ]
CakePHP - Controllers
The controller as the name indicates controls the application. It acts like a bridge between models and views. Controllers handle request data, makes sure that correct models are called and right response or view is rendered. Methods in the controllers’ class are called actions. Each controller follows naming conventions. The Controller class names are in plural form, Camel Cased, and end in Controller — PostsController. The AppConttroller class is the parent class of all applications’ controllers. This class extends the Controller class of CakePHP. AppController is defined at src/Controller/AppController.php. The file contains the following code. <?php declare(strict_types=1); namespace App\Controller; use Cake\Controller\Controller; class AppController extends Controller { public function initialize(): void { parent::initialize(); $this->loadComponent('RequestHandler'); $this->loadComponent('Flash'); } } AppController can be used to load components that will be used in every controller of your application. The attributes and methods created in AppController will be available in all controllers that extend it. The initialize() method will be invoked at the end of controller’s constructor to load components. The methods in the controller class are called Actions. These actions are responsible for sending appropriate response for browser/user making the request. View is rendered by the name of action, i.e., the name of method in controller. class RecipesController extends AppController { public function view($id) { // Action logic goes here. } public function share($customerId, $recipeId) { // Action logic goes here. } public function search($query) { // Action logic goes here. } } As you can see in the above example, the RecipesController has 3 actions − View, Share, and Search. For redirecting a user to another action of the same controller, we can use the setAction() method. The following is the syntax for the setAction() method. Cake\Controller\Controller::setAction($action, $args...) The following code will redirect the user to index action of the same controller. $this->setAction('index'); The following example shows the usage of the above method. Make changes in the config/routes.php file as shown in the following program. config/routes.php <?php use Cake\Http\Middleware\CsrfProtectionMiddleware; use Cake\Routing\Route\DashedRoute; use Cake\Routing\RouteBuilder; $routes->setRouteClass(DashedRoute::class); $routes->scope('/', function (RouteBuilder $builder) { // Register scoped middleware for in scopes. $builder->registerMiddleware('csrf', new CsrfProtectionMiddleware([ 'httpOnly' => true, ])); $builder->applyMiddleware('csrf'); $builder->connect('/redirect-controller',['controller'=>'Redirects','action'=>'action1']); $builder->connect('/redirect-controller2',['controller'=>'Redirects','action'=>'action2']); $builder->fallbacks(); }); Create a RedirectsController.php file at src/Controller/RedirectsController.php. Copy the following code in the controller file. src/Controller/RedirectsController.php <?php declare(strict_types=1); namespace App\Controller; use Cake\Core\Configure; use Cake\Http\Exception\ForbiddenException; use Cake\Http\Exception\NotFoundException; use Cake\Http\Response; use Cake\View\Exception\MissingTemplateException; class RedirectsController extends AppController { public function action1() { } public function action2(){ echo "redirecting from action2"; $this->setAction('action1'); } } Create a directory Redirects at src/Template and under that directory create a View file called action1.php. Copy the following code in that file. src/Template/Redirects/action1.php <h1>This is an example of how to redirect within controller.</h1> Execute the above example by visiting the following URL. http://localhost/cakephp4/redirect-controller Upon execution, you will receive the following output. Now, visit the following URL: http://localhost/cakephp4/redirect-controller2 The above URL will give you the following output. In CakePHP, a model can be loaded using the loadModel() method. The following is the syntax for the loadModel() method − Cake\Controller\Controller::loadModel(string $modelClass, string $type) There are two arguments to the above function as follows − The first argument is the name of model class. The first argument is the name of model class. The second argument is the type of repository to load. The second argument is the type of repository to load. If you want to load Articles model in a controller, then it can be loaded by writing the following line in controller’s action. $this->loadModel('Articles'); Print Add Notes Bookmark this page
[ { "code": null, "e": 2468, "s": 2242, "text": "The controller as the name indicates controls the application. It acts like a bridge between models and views. Controllers handle request data, makes sure that correct models are called and right response or view is rendered." }, { "code": null, "e": 2667, "s": 2468, "text": "Methods in the controllers’ class are called actions. Each controller follows naming conventions. The Controller class names are in plural form, Camel Cased, and end in Controller — PostsController." }, { "code": null, "e": 2898, "s": 2667, "text": "The AppConttroller class is the parent class of all applications’ controllers. This class extends the Controller class of CakePHP. AppController is defined at src/Controller/AppController.php. The file contains the following code." }, { "code": null, "e": 3186, "s": 2898, "text": "<?php\ndeclare(strict_types=1);\nnamespace App\\Controller;\nuse Cake\\Controller\\Controller;\nclass AppController extends Controller {\n public function initialize(): void {\n parent::initialize();\n $this->loadComponent('RequestHandler');\n $this->loadComponent('Flash');\n }\n}" }, { "code": null, "e": 3494, "s": 3186, "text": "AppController can be used to load components that will be used in every controller of your application. The attributes and methods created in AppController will be available in all controllers that extend it. The initialize() method will be invoked at the end of controller’s constructor to load components." }, { "code": null, "e": 3730, "s": 3494, "text": "The methods in the controller class are called Actions. These actions are responsible for sending appropriate response for browser/user making the request. View is rendered by the name of action, i.e., the name of method in controller." }, { "code": null, "e": 4012, "s": 3730, "text": "class RecipesController extends AppController {\n public function view($id) {\n // Action logic goes here.\n }\n public function share($customerId, $recipeId) {\n // Action logic goes here.\n }\n public function search($query) {\n // Action logic goes here.\n }\n}" }, { "code": null, "e": 4112, "s": 4012, "text": "As you can see in the above example, the RecipesController has 3 actions − View, Share, and Search." }, { "code": null, "e": 4268, "s": 4112, "text": "For redirecting a user to another action of the same controller, we can use the setAction() method. The following is the syntax for the setAction() method." }, { "code": null, "e": 4326, "s": 4268, "text": "Cake\\Controller\\Controller::setAction($action, $args...)\n" }, { "code": null, "e": 4408, "s": 4326, "text": "The following code will redirect the user to index action of the same controller." }, { "code": null, "e": 4436, "s": 4408, "text": "$this->setAction('index');\n" }, { "code": null, "e": 4495, "s": 4436, "text": "The following example shows the usage of the above method." }, { "code": null, "e": 4573, "s": 4495, "text": "Make changes in the config/routes.php file as shown in the following program." }, { "code": null, "e": 4591, "s": 4573, "text": "config/routes.php" }, { "code": null, "e": 5225, "s": 4591, "text": "<?php\nuse Cake\\Http\\Middleware\\CsrfProtectionMiddleware;\nuse Cake\\Routing\\Route\\DashedRoute;\nuse Cake\\Routing\\RouteBuilder;\n$routes->setRouteClass(DashedRoute::class);\n$routes->scope('/', function (RouteBuilder $builder) {\n // Register scoped middleware for in scopes.\n $builder->registerMiddleware('csrf', new CsrfProtectionMiddleware([\n 'httpOnly' => true,\n ]));\n $builder->applyMiddleware('csrf'); \n $builder->connect('/redirect-controller',['controller'=>'Redirects','action'=>'action1']);\n $builder->connect('/redirect-controller2',['controller'=>'Redirects','action'=>'action2']);\n $builder->fallbacks();\n});" }, { "code": null, "e": 5354, "s": 5225, "text": "Create a RedirectsController.php file at src/Controller/RedirectsController.php. Copy the following code in the controller file." }, { "code": null, "e": 5393, "s": 5354, "text": "src/Controller/RedirectsController.php" }, { "code": null, "e": 5833, "s": 5393, "text": "<?php\ndeclare(strict_types=1);\nnamespace App\\Controller;\nuse Cake\\Core\\Configure;\nuse Cake\\Http\\Exception\\ForbiddenException;\nuse Cake\\Http\\Exception\\NotFoundException;\nuse Cake\\Http\\Response;\nuse Cake\\View\\Exception\\MissingTemplateException;\nclass RedirectsController extends AppController {\n public function action1() {\n }\n public function action2(){\n echo \"redirecting from action2\";\n $this->setAction('action1');\n }\n}" }, { "code": null, "e": 5980, "s": 5833, "text": "Create a directory Redirects at src/Template and under that directory create a View file called action1.php. Copy the following code in that file." }, { "code": null, "e": 6015, "s": 5980, "text": "src/Template/Redirects/action1.php" }, { "code": null, "e": 6082, "s": 6015, "text": "<h1>This is an example of how to redirect within controller.</h1>\n" }, { "code": null, "e": 6139, "s": 6082, "text": "Execute the above example by visiting the following URL." }, { "code": null, "e": 6185, "s": 6139, "text": "http://localhost/cakephp4/redirect-controller" }, { "code": null, "e": 6240, "s": 6185, "text": "Upon execution, you will receive the following output." }, { "code": null, "e": 6317, "s": 6240, "text": "Now, visit the following URL: http://localhost/cakephp4/redirect-controller2" }, { "code": null, "e": 6367, "s": 6317, "text": "The above URL will give you the following output." }, { "code": null, "e": 6488, "s": 6367, "text": "In CakePHP, a model can be loaded using the loadModel() method. The following is the syntax for the loadModel() method −" }, { "code": null, "e": 6561, "s": 6488, "text": "Cake\\Controller\\Controller::loadModel(string $modelClass, string $type)\n" }, { "code": null, "e": 6620, "s": 6561, "text": "There are two arguments to the above function as follows −" }, { "code": null, "e": 6667, "s": 6620, "text": "The first argument is the name of model class." }, { "code": null, "e": 6714, "s": 6667, "text": "The first argument is the name of model class." }, { "code": null, "e": 6769, "s": 6714, "text": "The second argument is the type of repository to load." }, { "code": null, "e": 6824, "s": 6769, "text": "The second argument is the type of repository to load." }, { "code": null, "e": 6952, "s": 6824, "text": "If you want to load Articles model in a controller, then it can be loaded by writing the following line in controller’s action." }, { "code": null, "e": 6983, "s": 6952, "text": "$this->loadModel('Articles');\n" }, { "code": null, "e": 6990, "s": 6983, "text": " Print" }, { "code": null, "e": 7001, "s": 6990, "text": " Add Notes" } ]
How to stop the Azure VM using Azure CLI in PowerShell?
To stop the azure VM using Azure CLI we can use the az vm stop command. Before running this command make sure that you are connected to the Azure account and the proper Azure subscription. When we run this command, we need to provide the Azure VM name (-n) and the resource group name (-g). PS C:\> az vm stop -n Win2k16VM1 -g TESTVMRG --verbose The above command will stop the Azure VM Win2k16VM1 from the resource group TestVMRG. Alternatively, you can also use the full parameter name as shown below. PS C:\> az vm stop --name win2k16vm1 --resource-group testvmrg This command will wait until the Azure VM stops. To stop the Azure VM without waiting for the VM to stop and move the execution to the next step, we can use -- no-wait parameter. PS C:\> az vm stop --name win2k16vm1 --resource-group testvmrg --no-wait
[ { "code": null, "e": 1251, "s": 1062, "text": "To stop the azure VM using Azure CLI we can use the az vm stop command. Before running this command make sure that you are connected to the Azure account and the proper Azure subscription." }, { "code": null, "e": 1353, "s": 1251, "text": "When we run this command, we need to provide the Azure VM name (-n) and the resource group name (-g)." }, { "code": null, "e": 1408, "s": 1353, "text": "PS C:\\> az vm stop -n Win2k16VM1 -g TESTVMRG --verbose" }, { "code": null, "e": 1566, "s": 1408, "text": "The above command will stop the Azure VM Win2k16VM1 from the resource group TestVMRG. Alternatively, you can also use the full parameter name as shown below." }, { "code": null, "e": 1629, "s": 1566, "text": "PS C:\\> az vm stop --name win2k16vm1 --resource-group testvmrg" }, { "code": null, "e": 1808, "s": 1629, "text": "This command will wait until the Azure VM stops. To stop the Azure VM without waiting for the VM to stop and move the execution to the next step, we can use -- no-wait parameter." }, { "code": null, "e": 1881, "s": 1808, "text": "PS C:\\> az vm stop --name win2k16vm1 --resource-group testvmrg --no-wait" } ]
Hibernate - One-to-Many Mappings
A One-to-Many mapping can be implemented using a Set java collection that does not contain any duplicate element. We already have seen how to map Set collection in hibernate, so if you already learned Set mapping then you are all set to go with one-to-many mapping. A Set is mapped with a <set> element in the mapping table and initialized with java.util.HashSet. You can use Set collection in your class when there is no duplicate element required in the collection. Consider a situation where we need to store our employee records in EMPLOYEE table, which will have the following structure − create table EMPLOYEE ( id INT NOT NULL auto_increment, first_name VARCHAR(20) default NULL, last_name VARCHAR(20) default NULL, salary INT default NULL, PRIMARY KEY (id) ); Further, assume each employee can have one or more certificate associated with him/her. So, we will store certificate related information in a separate table having the following structure − create table CERTIFICATE ( id INT NOT NULL auto_increment, certificate_name VARCHAR(30) default NULL, employee_id INT default NULL, PRIMARY KEY (id) ); There will be one-to-many relationship between EMPLOYEE and CERTIFICATE objects − Let us implement our POJO class Employee, which will be used to persist the objects related to EMPLOYEE table and having a collection of certificates in a Set variable. import java.util.*; public class Employee { private int id; private String firstName; private String lastName; private int salary; private Set certificates; public Employee() {} public Employee(String fname, String lname, int salary) { this.firstName = fname; this.lastName = lname; this.salary = salary; } public int getId() { return id; } public void setId( int id ) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName( String first_name ) { this.firstName = first_name; } public String getLastName() { return lastName; } public void setLastName( String last_name ) { this.lastName = last_name; } public int getSalary() { return salary; } public void setSalary( int salary ) { this.salary = salary; } public Set getCertificates() { return certificates; } public void setCertificates( Set certificates ) { this.certificates = certificates; } } Now, let us define another POJO class corresponding to CERTIFICATE table so that certificate objects can be stored and retrieved into the CERTIFICATE table. This class should also implement both the equals() and hashCode() methods so that Java can determine whether any two elements/objects are identical. public class Certificate { private int id; private String name; public Certificate() {} public Certificate(String name) { this.name = name; } public int getId() { return id; } public void setId( int id ) { this.id = id; } public String getName() { return name; } public void setName( String name ) { this.name = name; } public boolean equals(Object obj) { if (obj == null) return false; if (!this.getClass().equals(obj.getClass())) return false; Certificate obj2 = (Certificate)obj; if((this.id == obj2.getId()) && (this.name.equals(obj2.getName()))) { return true; } return false; } public int hashCode() { int tmp = 0; tmp = ( id + name ).hashCode(); return tmp; } } Let us develop our mapping file, which instructs Hibernate how to map the defined classes to the database tables. <?xml version = "1.0" encoding = "utf-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name = "Employee" table = "EMPLOYEE"> <meta attribute = "class-description"> This class contains the employee detail. </meta> <id name = "id" type = "int" column = "id"> <generator class="native"/> </id> <set name = "certificates" cascade="all"> <key column = "employee_id"/> <one-to-many class="Certificate"/> </set> <property name = "firstName" column = "first_name" type = "string"/> <property name = "lastName" column = "last_name" type = "string"/> <property name = "salary" column = "salary" type = "int"/> </class> <class name = "Certificate" table = "CERTIFICATE"> <meta attribute = "class-description"> This class contains the certificate records. </meta> <id name = "id" type = "int" column = "id"> <generator class="native"/> </id> <property name = "name" column = "certificate_name" type = "string"/> </class> </hibernate-mapping> You should save the mapping document in a file with the format <classname>.hbm.xml. We saved our mapping document in the file Employee.hbm.xml. You are already familiar with most of the mapping detail, but let us see all the elements of mapping file once again − The mapping document is an XML document having <hibernate-mapping> as the root element, which contains two <class> elements corresponding to each class. The mapping document is an XML document having <hibernate-mapping> as the root element, which contains two <class> elements corresponding to each class. The <class> elements are used to define specific mappings from a Java classes to the database tables. The Java class name is specified using the name attribute of the class element and the database table name is specified using the table attribute. The <class> elements are used to define specific mappings from a Java classes to the database tables. The Java class name is specified using the name attribute of the class element and the database table name is specified using the table attribute. The <meta> element is optional element and can be used to create the class description. The <meta> element is optional element and can be used to create the class description. The <id> element maps the unique ID attribute in class to the primary key of the database table. The name attribute of the id element refers to the property in the class and the column attribute refers to the column in the database table. The type attribute holds the hibernate mapping type, this mapping types will convert from Java to SQL data type. The <id> element maps the unique ID attribute in class to the primary key of the database table. The name attribute of the id element refers to the property in the class and the column attribute refers to the column in the database table. The type attribute holds the hibernate mapping type, this mapping types will convert from Java to SQL data type. The <generator> element within the id element is used to generate the primary key values automatically. The class attribute of the generator element is set to native to let hibernate pick up either identity, sequence or hilo algorithm to create primary key depending upon the capabilities of the underlying database. The <generator> element within the id element is used to generate the primary key values automatically. The class attribute of the generator element is set to native to let hibernate pick up either identity, sequence or hilo algorithm to create primary key depending upon the capabilities of the underlying database. The <property> element is used to map a Java class property to a column in the database table. The name attribute of the element refers to the property in the class and the column attribute refers to the column in the database table. The type attribute holds the hibernate mapping type, this mapping types will convert from Java to SQL data type. The <property> element is used to map a Java class property to a column in the database table. The name attribute of the element refers to the property in the class and the column attribute refers to the column in the database table. The type attribute holds the hibernate mapping type, this mapping types will convert from Java to SQL data type. The <set> element sets the relationship between Certificate and Employee classes. We used the cascade attribute in the <set> element to tell Hibernate to persist the Certificate objects at the same time as the Employee objects. The name attribute is set to the defined Set variable in the parent class, in our case it is certificates. For each set variable, we need to define a separate set element in the mapping file. The <set> element sets the relationship between Certificate and Employee classes. We used the cascade attribute in the <set> element to tell Hibernate to persist the Certificate objects at the same time as the Employee objects. The name attribute is set to the defined Set variable in the parent class, in our case it is certificates. For each set variable, we need to define a separate set element in the mapping file. The <key> element is the column in the CERTIFICATE table that holds the foreign key to the parent object i.e. table EMPLOYEE. The <key> element is the column in the CERTIFICATE table that holds the foreign key to the parent object i.e. table EMPLOYEE. The <one-to-many> element indicates that one Employee object relates to many Certificate objects. The <one-to-many> element indicates that one Employee object relates to many Certificate objects. Finally, we will create our application class with the main() method to run the application. We will use this application to save few Employee's records along with their certificates and then we will apply CRUD operations on those records. import java.util.*; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class ManageEmployee { private static SessionFactory factory; public static void main(String[] args) { try { factory = new Configuration().configure().buildSessionFactory(); } catch (Throwable ex) { System.err.println("Failed to create sessionFactory object." + ex); throw new ExceptionInInitializerError(ex); } ManageEmployee ME = new ManageEmployee(); /* Let us have a set of certificates for the first employee */ HashSet set1 = new HashSet(); set1.add(new Certificate("MCA")); set1.add(new Certificate("MBA")); set1.add(new Certificate("PMP")); /* Add employee records in the database */ Integer empID1 = ME.addEmployee("Manoj", "Kumar", 4000, set1); /* Another set of certificates for the second employee */ HashSet set2 = new HashSet(); set2.add(new Certificate("BCA")); set2.add(new Certificate("BA")); /* Add another employee record in the database */ Integer empID2 = ME.addEmployee("Dilip", "Kumar", 3000, set2); /* List down all the employees */ ME.listEmployees(); /* Update employee's salary records */ ME.updateEmployee(empID1, 5000); /* Delete an employee from the database */ ME.deleteEmployee(empID2); /* List down all the employees */ ME.listEmployees(); } /* Method to add an employee record in the database */ public Integer addEmployee(String fname, String lname, int salary, Set cert){ Session session = factory.openSession(); Transaction tx = null; Integer employeeID = null; try { tx = session.beginTransaction(); Employee employee = new Employee(fname, lname, salary); employee.setCertificates(cert); employeeID = (Integer) session.save(employee); tx.commit(); } catch (HibernateException e) { if (tx!=null) tx.rollback(); e.printStackTrace(); } finally { session.close(); } return employeeID; } /* Method to list all the employees detail */ public void listEmployees( ){ Session session = factory.openSession(); Transaction tx = null; try { tx = session.beginTransaction(); List employees = session.createQuery("FROM Employee").list(); for (Iterator iterator1 = employees.iterator(); iterator1.hasNext();){ Employee employee = (Employee) iterator1.next(); System.out.print("First Name: " + employee.getFirstName()); System.out.print(" Last Name: " + employee.getLastName()); System.out.println(" Salary: " + employee.getSalary()); Set certificates = employee.getCertificates(); for (Iterator iterator2 = certificates.iterator(); iterator2.hasNext();){ Certificate certName = (Certificate) iterator2.next(); System.out.println("Certificate: " + certName.getName()); } } tx.commit(); } catch (HibernateException e) { if (tx!=null) tx.rollback(); e.printStackTrace(); } finally { session.close(); } } /* Method to update salary for an employee */ public void updateEmployee(Integer EmployeeID, int salary ){ Session session = factory.openSession(); Transaction tx = null; try { tx = session.beginTransaction(); Employee employee = (Employee)session.get(Employee.class, EmployeeID); employee.setSalary( salary ); session.update(employee); tx.commit(); } catch (HibernateException e) { if (tx!=null) tx.rollback(); e.printStackTrace(); } finally { session.close(); } } /* Method to delete an employee from the records */ public void deleteEmployee(Integer EmployeeID){ Session session = factory.openSession(); Transaction tx = null; try { tx = session.beginTransaction(); Employee employee = (Employee)session.get(Employee.class, EmployeeID); session.delete(employee); tx.commit(); } catch (HibernateException e) { if (tx!=null) tx.rollback(); e.printStackTrace(); } finally { session.close(); } } } Here are the steps to compile and run the above mentioned application. Make sure you have set PATH and CLASSPATH appropriately before proceeding for the compilation and execution. Create hibernate.cfg.xml configuration file as explained in configuration chapter. Create hibernate.cfg.xml configuration file as explained in configuration chapter. Create Employee.hbm.xml mapping file as shown above. Create Employee.hbm.xml mapping file as shown above. Create Employee.java source file as shown above and compile it. Create Employee.java source file as shown above and compile it. Create Certificate.java source file as shown above and compile it. Create Certificate.java source file as shown above and compile it. Create ManageEmployee.java source file as shown above and compile it. Create ManageEmployee.java source file as shown above and compile it. Execute ManageEmployee binary to run the program. Execute ManageEmployee binary to run the program. You would get the following result on the screen, and same time records would be created in EMPLOYEE and CERTIFICATE tables. $java ManageEmployee .......VARIOUS LOG MESSAGES WILL DISPLAY HERE........ First Name: Manoj Last Name: Kumar Salary: 4000 Certificate: MBA Certificate: PMP Certificate: MCA First Name: Dilip Last Name: Kumar Salary: 3000 Certificate: BCA Certificate: BA First Name: Manoj Last Name: Kumar Salary: 5000 Certificate: MBA Certificate: PMP Certificate: MCA If you check your EMPLOYEE and CERTIFICATE tables, they should have following records − mysql> select * from employee; +----+------------+-----------+--------+ | id | first_name | last_name | salary | +----+------------+-----------+--------+ | 1 | Manoj | Kumar | 5000 | +----+------------+-----------+--------+ 1 row in set (0.00 sec) mysql> select * from certificate; +----+------------------+-------------+ | id | certificate_name | employee_id | +----+------------------+-------------+ | 1 | MBA | 1 | | 2 | PMP | 1 | | 3 | MCA | 1 | +----+------------------+-------------+ 3 rows in set (0.00 sec) mysql> 108 Lectures 11 hours Chaand Sheikh 65 Lectures 5 hours Karthikeya T 39 Lectures 4.5 hours TELCOMA Global Print Add Notes Bookmark this page
[ { "code": null, "e": 2329, "s": 2063, "text": "A One-to-Many mapping can be implemented using a Set java collection that does not contain any duplicate element. We already have seen how to map Set collection in hibernate, so if you already learned Set mapping then you are all set to go with one-to-many mapping." }, { "code": null, "e": 2531, "s": 2329, "text": "A Set is mapped with a <set> element in the mapping table and initialized with java.util.HashSet. You can use Set collection in your class when there is no duplicate element required in the collection." }, { "code": null, "e": 2657, "s": 2531, "text": "Consider a situation where we need to store our employee records in EMPLOYEE table, which will have the following structure −" }, { "code": null, "e": 2852, "s": 2657, "text": "create table EMPLOYEE (\n id INT NOT NULL auto_increment,\n first_name VARCHAR(20) default NULL,\n last_name VARCHAR(20) default NULL,\n salary INT default NULL,\n PRIMARY KEY (id)\n);" }, { "code": null, "e": 3043, "s": 2852, "text": "Further, assume each employee can have one or more certificate associated with him/her. So, we will store certificate related information in a separate table having the following structure −" }, { "code": null, "e": 3207, "s": 3043, "text": "create table CERTIFICATE (\n id INT NOT NULL auto_increment,\n certificate_name VARCHAR(30) default NULL,\n employee_id INT default NULL,\n PRIMARY KEY (id)\n);" }, { "code": null, "e": 3289, "s": 3207, "text": "There will be one-to-many relationship between EMPLOYEE and CERTIFICATE objects −" }, { "code": null, "e": 3458, "s": 3289, "text": "Let us implement our POJO class Employee, which will be used to persist the objects related to EMPLOYEE table and having a collection of certificates in a Set variable." }, { "code": null, "e": 4558, "s": 3458, "text": "import java.util.*;\n\npublic class Employee {\n private int id;\n private String firstName; \n private String lastName; \n private int salary;\n private Set certificates;\n\n public Employee() {}\n \n public Employee(String fname, String lname, int salary) {\n this.firstName = fname;\n this.lastName = lname;\n this.salary = salary;\n }\n \n public int getId() {\n return id;\n }\n \n public void setId( int id ) {\n this.id = id;\n }\n \n public String getFirstName() {\n return firstName;\n }\n \n public void setFirstName( String first_name ) {\n this.firstName = first_name;\n }\n \n public String getLastName() {\n return lastName;\n }\n \n public void setLastName( String last_name ) {\n this.lastName = last_name;\n }\n \n public int getSalary() {\n return salary;\n }\n \n public void setSalary( int salary ) {\n this.salary = salary;\n }\n\n \n public Set getCertificates() {\n return certificates;\n }\n \n public void setCertificates( Set certificates ) {\n this.certificates = certificates;\n }\n}" }, { "code": null, "e": 4864, "s": 4558, "text": "Now, let us define another POJO class corresponding to CERTIFICATE table so that certificate objects can be stored and retrieved into the CERTIFICATE table. This class should also implement both the equals() and hashCode() methods so that Java can determine whether any two elements/objects are identical." }, { "code": null, "e": 5708, "s": 4864, "text": "public class Certificate {\n private int id;\n private String name; \n\n public Certificate() {}\n \n public Certificate(String name) {\n this.name = name;\n }\n \n public int getId() {\n return id;\n }\n \n public void setId( int id ) {\n this.id = id;\n }\n \n public String getName() {\n return name;\n }\n \n public void setName( String name ) {\n this.name = name;\n }\n \n public boolean equals(Object obj) {\n if (obj == null) return false;\n if (!this.getClass().equals(obj.getClass())) return false;\n\n Certificate obj2 = (Certificate)obj;\n if((this.id == obj2.getId()) && (this.name.equals(obj2.getName()))) {\n return true;\n }\n return false;\n }\n \n public int hashCode() {\n int tmp = 0;\n tmp = ( id + name ).hashCode();\n return tmp;\n }\n}" }, { "code": null, "e": 5822, "s": 5708, "text": "Let us develop our mapping file, which instructs Hibernate how to map the defined classes to the database tables." }, { "code": null, "e": 7089, "s": 5822, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<!DOCTYPE hibernate-mapping PUBLIC \n\"-//Hibernate/Hibernate Mapping DTD//EN\"\n\"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd\"> \n\n<hibernate-mapping>\n <class name = \"Employee\" table = \"EMPLOYEE\">\n \n <meta attribute = \"class-description\">\n This class contains the employee detail. \n </meta>\n \n <id name = \"id\" type = \"int\" column = \"id\">\n <generator class=\"native\"/>\n </id>\n \n <set name = \"certificates\" cascade=\"all\">\n <key column = \"employee_id\"/>\n <one-to-many class=\"Certificate\"/>\n </set>\n \n <property name = \"firstName\" column = \"first_name\" type = \"string\"/>\n <property name = \"lastName\" column = \"last_name\" type = \"string\"/>\n <property name = \"salary\" column = \"salary\" type = \"int\"/>\n \n </class>\n\n <class name = \"Certificate\" table = \"CERTIFICATE\">\n \n <meta attribute = \"class-description\">\n This class contains the certificate records. \n </meta>\n \n <id name = \"id\" type = \"int\" column = \"id\">\n <generator class=\"native\"/>\n </id>\n \n <property name = \"name\" column = \"certificate_name\" type = \"string\"/>\n \n </class>\n\n</hibernate-mapping>" }, { "code": null, "e": 7352, "s": 7089, "text": "You should save the mapping document in a file with the format <classname>.hbm.xml. We saved our mapping document in the file Employee.hbm.xml. You are already familiar with most of the mapping detail, but let us see all the elements of mapping file once again −" }, { "code": null, "e": 7505, "s": 7352, "text": "The mapping document is an XML document having <hibernate-mapping> as the root element, which contains two <class> elements corresponding to each class." }, { "code": null, "e": 7658, "s": 7505, "text": "The mapping document is an XML document having <hibernate-mapping> as the root element, which contains two <class> elements corresponding to each class." }, { "code": null, "e": 7907, "s": 7658, "text": "The <class> elements are used to define specific mappings from a Java classes to the database tables. The Java class name is specified using the name attribute of the class element and the database table name is specified using the table attribute." }, { "code": null, "e": 8156, "s": 7907, "text": "The <class> elements are used to define specific mappings from a Java classes to the database tables. The Java class name is specified using the name attribute of the class element and the database table name is specified using the table attribute." }, { "code": null, "e": 8245, "s": 8156, "text": "The <meta> element is optional element and can be used to create the class description." }, { "code": null, "e": 8334, "s": 8245, "text": "The <meta> element is optional element and can be used to create the class description." }, { "code": null, "e": 8686, "s": 8334, "text": "The <id> element maps the unique ID attribute in class to the primary key of the database table. The name attribute of the id element refers to the property in the class and the column attribute refers to the column in the database table. The type attribute holds the hibernate mapping type, this mapping types will convert from Java to SQL data type." }, { "code": null, "e": 9038, "s": 8686, "text": "The <id> element maps the unique ID attribute in class to the primary key of the database table. The name attribute of the id element refers to the property in the class and the column attribute refers to the column in the database table. The type attribute holds the hibernate mapping type, this mapping types will convert from Java to SQL data type." }, { "code": null, "e": 9355, "s": 9038, "text": "The <generator> element within the id element is used to generate the primary key values automatically. The class attribute of the generator element is set to native to let hibernate pick up either identity, sequence or hilo algorithm to create primary key depending upon the capabilities of the underlying database." }, { "code": null, "e": 9672, "s": 9355, "text": "The <generator> element within the id element is used to generate the primary key values automatically. The class attribute of the generator element is set to native to let hibernate pick up either identity, sequence or hilo algorithm to create primary key depending upon the capabilities of the underlying database." }, { "code": null, "e": 10019, "s": 9672, "text": "The <property> element is used to map a Java class property to a column in the database table. The name attribute of the element refers to the property in the class and the column attribute refers to the column in the database table. The type attribute holds the hibernate mapping type, this mapping types will convert from Java to SQL data type." }, { "code": null, "e": 10366, "s": 10019, "text": "The <property> element is used to map a Java class property to a column in the database table. The name attribute of the element refers to the property in the class and the column attribute refers to the column in the database table. The type attribute holds the hibernate mapping type, this mapping types will convert from Java to SQL data type." }, { "code": null, "e": 10786, "s": 10366, "text": "The <set> element sets the relationship between Certificate and Employee classes. We used the cascade attribute in the <set> element to tell Hibernate to persist the Certificate objects at the same time as the Employee objects. The name attribute is set to the defined Set variable in the parent class, in our case it is certificates. For each set variable, we need to define a separate set element in the mapping file." }, { "code": null, "e": 11206, "s": 10786, "text": "The <set> element sets the relationship between Certificate and Employee classes. We used the cascade attribute in the <set> element to tell Hibernate to persist the Certificate objects at the same time as the Employee objects. The name attribute is set to the defined Set variable in the parent class, in our case it is certificates. For each set variable, we need to define a separate set element in the mapping file." }, { "code": null, "e": 11332, "s": 11206, "text": "The <key> element is the column in the CERTIFICATE table that holds the foreign key to the parent object i.e. table EMPLOYEE." }, { "code": null, "e": 11458, "s": 11332, "text": "The <key> element is the column in the CERTIFICATE table that holds the foreign key to the parent object i.e. table EMPLOYEE." }, { "code": null, "e": 11556, "s": 11458, "text": "The <one-to-many> element indicates that one Employee object relates to many Certificate objects." }, { "code": null, "e": 11654, "s": 11556, "text": "The <one-to-many> element indicates that one Employee object relates to many Certificate objects." }, { "code": null, "e": 11894, "s": 11654, "text": "Finally, we will create our application class with the main() method to run the application. We will use this application to save few Employee's records along with their certificates and then we will apply CRUD operations on those records." }, { "code": null, "e": 16483, "s": 11894, "text": "import java.util.*;\n \nimport org.hibernate.HibernateException; \nimport org.hibernate.Session; \nimport org.hibernate.Transaction;\nimport org.hibernate.SessionFactory;\nimport org.hibernate.cfg.Configuration;\n\npublic class ManageEmployee {\n private static SessionFactory factory; \n public static void main(String[] args) {\n \n try {\n factory = new Configuration().configure().buildSessionFactory();\n } catch (Throwable ex) { \n System.err.println(\"Failed to create sessionFactory object.\" + ex);\n throw new ExceptionInInitializerError(ex); \n }\n \n ManageEmployee ME = new ManageEmployee();\n /* Let us have a set of certificates for the first employee */\n HashSet set1 = new HashSet();\n set1.add(new Certificate(\"MCA\"));\n set1.add(new Certificate(\"MBA\"));\n set1.add(new Certificate(\"PMP\"));\n \n /* Add employee records in the database */\n Integer empID1 = ME.addEmployee(\"Manoj\", \"Kumar\", 4000, set1);\n\n /* Another set of certificates for the second employee */\n HashSet set2 = new HashSet();\n set2.add(new Certificate(\"BCA\"));\n set2.add(new Certificate(\"BA\"));\n\n /* Add another employee record in the database */\n Integer empID2 = ME.addEmployee(\"Dilip\", \"Kumar\", 3000, set2);\n\n /* List down all the employees */\n ME.listEmployees();\n\n /* Update employee's salary records */\n ME.updateEmployee(empID1, 5000);\n\n /* Delete an employee from the database */\n ME.deleteEmployee(empID2);\n\n /* List down all the employees */\n ME.listEmployees();\n\n }\n\n /* Method to add an employee record in the database */\n public Integer addEmployee(String fname, String lname, int salary, Set cert){\n Session session = factory.openSession();\n Transaction tx = null;\n Integer employeeID = null;\n \n try {\n tx = session.beginTransaction();\n Employee employee = new Employee(fname, lname, salary);\n employee.setCertificates(cert);\n employeeID = (Integer) session.save(employee); \n tx.commit();\n } catch (HibernateException e) {\n if (tx!=null) tx.rollback();\n e.printStackTrace(); \n } finally {\n session.close(); \n }\n return employeeID;\n }\n\n /* Method to list all the employees detail */\n public void listEmployees( ){\n Session session = factory.openSession();\n Transaction tx = null;\n \n try {\n tx = session.beginTransaction();\n List employees = session.createQuery(\"FROM Employee\").list(); \n for (Iterator iterator1 = employees.iterator(); iterator1.hasNext();){\n Employee employee = (Employee) iterator1.next(); \n System.out.print(\"First Name: \" + employee.getFirstName()); \n System.out.print(\" Last Name: \" + employee.getLastName()); \n System.out.println(\" Salary: \" + employee.getSalary());\n Set certificates = employee.getCertificates();\n for (Iterator iterator2 = certificates.iterator(); iterator2.hasNext();){\n Certificate certName = (Certificate) iterator2.next(); \n System.out.println(\"Certificate: \" + certName.getName()); \n }\n }\n tx.commit();\n } catch (HibernateException e) {\n if (tx!=null) tx.rollback();\n e.printStackTrace(); \n } finally {\n session.close(); \n }\n }\n \n /* Method to update salary for an employee */\n public void updateEmployee(Integer EmployeeID, int salary ){\n Session session = factory.openSession();\n Transaction tx = null;\n try {\n tx = session.beginTransaction();\n Employee employee = (Employee)session.get(Employee.class, EmployeeID); \n employee.setSalary( salary );\n session.update(employee);\n tx.commit();\n } catch (HibernateException e) {\n if (tx!=null) tx.rollback();\n e.printStackTrace(); \n } finally {\n session.close(); \n }\n }\n \n /* Method to delete an employee from the records */\n public void deleteEmployee(Integer EmployeeID){\n Session session = factory.openSession();\n Transaction tx = null;\n \n try {\n tx = session.beginTransaction();\n Employee employee = (Employee)session.get(Employee.class, EmployeeID); \n session.delete(employee); \n tx.commit();\n } catch (HibernateException e) {\n if (tx!=null) tx.rollback();\n e.printStackTrace(); \n } finally {\n session.close(); \n }\n }\n}" }, { "code": null, "e": 16663, "s": 16483, "text": "Here are the steps to compile and run the above mentioned application. Make sure you have set PATH and CLASSPATH appropriately before proceeding for the compilation and execution." }, { "code": null, "e": 16746, "s": 16663, "text": "Create hibernate.cfg.xml configuration file as explained in configuration chapter." }, { "code": null, "e": 16829, "s": 16746, "text": "Create hibernate.cfg.xml configuration file as explained in configuration chapter." }, { "code": null, "e": 16882, "s": 16829, "text": "Create Employee.hbm.xml mapping file as shown above." }, { "code": null, "e": 16935, "s": 16882, "text": "Create Employee.hbm.xml mapping file as shown above." }, { "code": null, "e": 16999, "s": 16935, "text": "Create Employee.java source file as shown above and compile it." }, { "code": null, "e": 17063, "s": 16999, "text": "Create Employee.java source file as shown above and compile it." }, { "code": null, "e": 17130, "s": 17063, "text": "Create Certificate.java source file as shown above and compile it." }, { "code": null, "e": 17197, "s": 17130, "text": "Create Certificate.java source file as shown above and compile it." }, { "code": null, "e": 17267, "s": 17197, "text": "Create ManageEmployee.java source file as shown above and compile it." }, { "code": null, "e": 17337, "s": 17267, "text": "Create ManageEmployee.java source file as shown above and compile it." }, { "code": null, "e": 17387, "s": 17337, "text": "Execute ManageEmployee binary to run the program." }, { "code": null, "e": 17437, "s": 17387, "text": "Execute ManageEmployee binary to run the program." }, { "code": null, "e": 17562, "s": 17437, "text": "You would get the following result on the screen, and same time records would be created in EMPLOYEE and CERTIFICATE tables." }, { "code": null, "e": 17923, "s": 17562, "text": "$java ManageEmployee\n.......VARIOUS LOG MESSAGES WILL DISPLAY HERE........\n\nFirst Name: Manoj Last Name: Kumar Salary: 4000\nCertificate: MBA\nCertificate: PMP\nCertificate: MCA\nFirst Name: Dilip Last Name: Kumar Salary: 3000\nCertificate: BCA\nCertificate: BA\nFirst Name: Manoj Last Name: Kumar Salary: 5000\nCertificate: MBA\nCertificate: PMP\nCertificate: MCA" }, { "code": null, "e": 18011, "s": 17923, "text": "If you check your EMPLOYEE and CERTIFICATE tables, they should have following records −" }, { "code": null, "e": 18619, "s": 18011, "text": "mysql> select * from employee;\n+----+------------+-----------+--------+\n| id | first_name | last_name | salary |\n+----+------------+-----------+--------+\n| 1 | Manoj | Kumar | 5000 |\n+----+------------+-----------+--------+\n1 row in set (0.00 sec)\n\nmysql> select * from certificate;\n+----+------------------+-------------+\n| id | certificate_name | employee_id |\n+----+------------------+-------------+\n| 1 | MBA | 1 |\n| 2 | PMP | 1 |\n| 3 | MCA | 1 |\n+----+------------------+-------------+\n3 rows in set (0.00 sec)\n\nmysql>" }, { "code": null, "e": 18654, "s": 18619, "text": "\n 108 Lectures \n 11 hours \n" }, { "code": null, "e": 18669, "s": 18654, "text": " Chaand Sheikh" }, { "code": null, "e": 18702, "s": 18669, "text": "\n 65 Lectures \n 5 hours \n" }, { "code": null, "e": 18716, "s": 18702, "text": " Karthikeya T" }, { "code": null, "e": 18751, "s": 18716, "text": "\n 39 Lectures \n 4.5 hours \n" }, { "code": null, "e": 18767, "s": 18751, "text": " TELCOMA Global" }, { "code": null, "e": 18774, "s": 18767, "text": " Print" }, { "code": null, "e": 18785, "s": 18774, "text": " Add Notes" } ]
DeepPiCar — Part 2: Raspberry Pi Setup and PiCar Assembly | by David Tian | Towards Data Science
Welcome back! In this guide, we will first go over what hardware to purchase and why we need them. Next, we will set them up so that we will have a PiCar running in our living room by the end of this article. 1 x Raspberry Pi 3 Model B+ kit with 2.5A Power Supply ($50) This is the brain of your DeepPiCar. This latest model of Raspberry Pi features a 1.4Ghz 64-bit Quad-Core processor, dual band wifi, Bluetooth, 4 USB ports, and an HDMI port. I recommend this kit (over just the Raspberry Pi board) because it comes with a power adapter, which you need to plug in while doing your non-driving coding and testing, and two chip heat sinks, which will prevent your Raspberry Pi CPU from overheating. 1 x 64 GB micro SD Card ($8) This is where your Raspberry Pi’s operating system and all of our software will be stored. Any brand of micro SD card should work fine. You may just have one lying around your house. 32GB should be fine as well. I choose 64 GB because I plan to record lots of videos of while my car is driving so that I can analyze its behavior later, and use the videos to do deep learning training in later projects. 1 x SunFounder PiCar-V kit ($115) This is the main body of DeepPiCar. Make sure you get the Model V as shown above(a.k.a. Version 2.0). It comes with everything you need in a robotics car, except for the Raspberry Pi and the batteries. There are a number of Raspberry Pi car kits on the market, I chose this car kit because it comes with an open source python API to control the car, whereas other vendors have its proprietary API or C based API. As we know, python is now the language of choice for machine learning and deep learning. Also, open source is important as we may tinker with the internals of the car API ourselves if we find bugs in the API without having to wait for the manufacturer to provide software updates. 4 x 18650 batteries and 1 x battery charger ($20) You may get any 18650 batteries and compatible chargers. These batteries are for high drain applications, such as driving the Raspberry Pi board and the PiCar. PiCar takes only two batteries, but you always want to have another freshly charged pair around, so that you can keep your car running on the tracks at all times. I recommend charging both sets at night, so you won’t have to worry about dead batteries during testing. 1 x Google Edge TPU USB Accelerator ($75) Every hero needs a sidekick. Google’s Edge TPU (Edge means it's for mobile and embedded devices and TPU stands Tensor Processing Unit) is a wonderful add-on to the Raspberry Pi board. While the Pi CPU packs a lot of computing power in a tiny bundle, it is NOT designed to do deep learning. Google’s newly released Edge TPU(March 2019), on the other hand, is specifically designed to run deep learning models written in TensorFlow. In Part 6 of this series, we will build a real-time traffic sign detection model in TensorFlow. This model is 200+ layers deep! Running this model on Raspberry Pi’s CPU alone can only process 1 Frame per Second (FPS) which is hardly real-time. Plus it consumes 100% of the CPU and makes all the other programs non-responsive. But with the help of Edge TPU, we can now process 12 FPS, which is adequate for real-time work. And our CPU stays cool and can be utilized to do other processing tasks, like controlling the car. 1 x Set of Miniature Traffic Signs ($15) and a few Lego figurines. You may not need to buy them if your younger ones have some of these toy signs and Lego figurines in the playroom. You can use whatever signs you find to train the model, just make sure they are not TOO BIG! (Optional) 1 x 170 degree Wide Angle USB Camera ($40). This is an optional accessory. I bought it to replace the stock camera that came with the SunFounder PiCar so that the car can have a wide field of vision. The stock camera is great, but not as wide angle as I like and it can’t see lane lines that are 3–4 inches in front of the front wheels. I wrote the lane following code in Part 4 with the stock camera initially. After trying a few lens, I found that the lane following accuracy and stability greatly increased with this wide angle camera. It is nice to have control of both your hardware and software (vs running a car in car simulator), because you may resort to a hardware fix if a problem can’t be easily solved via software alone. USB Keyboard/Mouse and Monitor that takes HDMI input. You only need these during the initial setup stage of the Pi. Afterward, we can remote control the Pi via VNC or Putty. A desktop or laptop computer running Windows/Mac or Linux, which I will refer to as “PC” here onwards. We will use this PC to remote access and deploy code to the Pi computer. Sometimes, it surprises me that Raspberry Pi, the brain of our car is only about $30 and cheaper than many of our other accessories. Indeed, the hardware is getting cheaper and more powerful over time, and software is completely free and abundant. Don’t we live in a GREAT era?! This is the end product when the assembly is done. I am using a wide-angle camera here. Follow this excellent step-by-step guide to install the NOOBS Raspbian Operating System (a variate of Linux) onto a micro SD card. It would take about 20 min and about 4GB of disk space. After installation and reboot, you should see a full GUI desktop like below. This feels like you are in a Windows or Mac GUI environment, doesn’t it? During installation, Pi will ask you to change the password for the default user pi. Let’s set the password to rasp, for example. After the initial installation, Pi may need to upgrade to the latest software. This may take another 10–15 minutes. Setting up remote access allows Pi computer to run headless (i.e. without a monitor/keyboard/mouse) which saves us from having to connect a monitor and keyboard/mouse to it all the time. This video gives a very good tutorial on how to set up SSH and VNC Remote Access. Here are the steps, anyways. Open the Terminal application, as shown below. The Terminal app is a very important program, as most of our command in later articles will be entered from Terminal. Find the IP address of the Pi by running ifconfig. In this case, my Pi’s IP address is 192.168.1.120. pi@raspberrypi:~ $ ifconfig | grep wlan0 -A1wlan0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500 inet 192.168.1.120 netmask 255.255.255.0 broadcast 192.168.1.255 Run sudo raspi-config in Terminal to start the “Raspberry Pi Software Configuration Tool”. You may be prompted to type in the password for user pi Enable SSH Server: Choose 5. Interface Options -> SSH -> Enable Enable VNC Server: Choose 5. Interface Options -> VNC -> Enable Download and install RealVNC Viewer onto your PC. Connect to Pi’s IP address using Real VNC Viewer. You will see the same desktop as the one Pi is running. At this point, you can safely disconnect the monitor/keyboard/mouse from the Pi computer, leaving just the power adapter plugged in. Since our Pi will be running headless, we want to be able to access Pi’s file system from a remote computer so that we can transfer files to/from Pi computer easily. We will install Samba File Server on Pi. pi@raspberrypi:~ $ sudo apt-get update && sudo apt-get upgrade -yGet:1 http://archive.raspberrypi.org/debian stretch InRelease [25.4 kB]Packages [45.0 kB][omitted...]Unpacking lxplug-ptbatt (0.5) over (0.4) ...Setting up lxplug-ptbatt (0.5) ...pi@raspberrypi:~ $ sudo apt-get install samba samba-common-bin -yReading package lists... DoneBuilding dependency tree [omitted...]Processing triggers for libc-bin (2.24-11+deb9u4) ...Processing triggers for systemd (232-25+deb9u11) ...pi@raspberrypi:~ $ sudo rm /etc/samba/smb.confpi@raspberrypi:~ $ sudo nano /etc/samba/smb.conf Then paste in the following lines into the nano editor [global]netbios name = Piserver string = The PiCar File Systemworkgroup = WORKGROUP[HOMEPI]path = /home/picomment = No commentbrowsable = yeswritable = Yescreate mask = 0777directory mask = 0777public = no Save and exit nano by Ctrl-X, and Yes to save changes. Then set up a Samba Server password. For simplicity, we will use the same rasp as the Samba server password. After the password is set, restart the Samba server. # create samba passwordpi@raspberrypi:~ $ sudo smbpasswd -a piNew SMB password:Retype new SMB password:Added user pi.# restart samba serverpi@raspberrypi:~ $ sudo service smbd restart At this point, you should be able to connect to the Pi computer from your PC via Pi’s IP address (My Pi’s IP is 192.168.1.120). Go to your PC (Windows), open a Command Prompt (cmd.exe) and type: # mount the Pi home directory to R: drive on PCC:\>net use r: \\192.168.1.120\homepiThe command completed successfully.C:\Users\dctia>r:C:\>dir r: Volume in drive R is HOMEPI Volume Serial Number is 61E3-70FFDirectory of R:\05/02/2019 03:57 PM <DIR> .04/08/2019 04:48 AM <DIR> ..04/08/2019 05:43 AM <DIR> Desktop04/08/2019 05:43 AM <DIR> Documents04/08/2019 05:43 AM <DIR> Downloads04/08/2019 05:15 AM <DIR> MagPi04/08/2019 05:43 AM <DIR> Music05/02/2019 03:43 PM <DIR> Pictures04/08/2019 05:43 AM <DIR> Public04/08/2019 05:43 AM <DIR> Templates04/08/2019 05:43 AM <DIR> Videos 0 File(s) 0 bytes 11 Dir(s) 22,864,379,904 bytes free Indeed this is our Pi Computer’s file system that we can see from its file manager. This will be very useful since we can edit files that reside on Pi directly from our PC. For example, we can use PyCharm IDE to edit Python programs on Pi first, and then just use Pi’s terminal (via VNC) to run these programs. If you have a Mac, here is how to connect to the Pi’s file server. Hit Command-K to bring up the “Connect to Server” window. Enter the network drive path (replace with your Pi’s IP address), i.e. smb://192.168.1.120/homepi, and click Connect. Enter the login/password, i.e. pi/rasp and click OK to mount the network drive. Then the drive will now appear on your desktop and in the Finder Window sidebar. For more in-depth network connectivity instructions on Mac, check out this excellent article. The device driver for the USB camera should already come with Raspian OS. We will install a Video Camera Viewer so we can see live videos. Take the USB Camera out of PiCar kit and plug into Pi computer’s USB port Run sudo apt-get install cheese from the terminal to install “Cheese”, the camera viewer. pi@raspberrypi:~ $ sudo apt-get install cheese -yReading package lists... DoneBuilding dependency tree Reading state information... Done....cheese is the newest version (3.22.1-1). Launch Cheese app by Raspberry Pi button(Top Left Corner)-> Sound & Video -> Cheese You should see a live video feed displayed like the picture above. Before assembling PiCar, we need to install PiCar’s python API. SunFounder release a server version and client version of its Python API. The Client API code, which is intended to remote control your PiCar, runs on your PC, and it uses Python version 3. The Server API code runs on PiCar, unfortunately, it uses Python version 2, which is an outdated version. Since the self-driving programs that we write will exclusively run on PiCar, the PiCar Server API must run in Python 3 also. Fortunately, all of SunFounder’s API code are open source on Github, I made a fork and updated the entire repo (both server and client) to Python 3. (I will submit my changes to SunFounder soon, so it can be merged back to the main repo, once approved by SunFounder.) For the time being, run the following commands (in bold) instead of the software commands in the SunFounder manual. You shouldn’t have to run commands on Pages 20–26 of the manual. # route all calls to python (version 2) to python3, # pip (version 2) to pip3, even in sudo mode # note: `sudo abcd` runs `abcd` command in administrator modealias python=python3alias pip=pip3alias sudo='sudo '# Download patched PiCar-V driver API, and run its set uppi@raspberrypi:~ $ cdpi@raspberrypi:~ $ git clone https://github.com/dctian/SunFounder_PiCar.gitCloning into 'SunFounder_PiCar'...remote: Enumerating objects: 9, done.remote: Counting objects: 100% (9/9), done.remote: Compressing objects: 100% (9/9), done.remote: Total 276 (delta 0), reused 2 (delta 0), pack-reused 267Receiving objects: 100% (276/276), 53.33 KiB | 0 bytes/s, done.Resolving deltas: 100% (171/171), done.pi@raspberrypi:~ $ cd ~/SunFounder_PiCar/picar/pi@raspberrypi:~/SunFounder_PiCar/picar $ git clone https://github.com/dctian/SunFounder_PCA9685.gitCloning into 'SunFounder_PCA9685'...remote: Enumerating objects: 7, done.remote: Counting objects: 100% (7/7), done.remote: Compressing objects: 100% (5/5), done.remote: Total 87 (delta 2), reused 6 (delta 2), pack-reused 80Unpacking objects: 100% (87/87), done.pi@raspberrypi:~/SunFounder_PiCar/picar $ cd ~/SunFounder_PiCar/pi@raspberrypi:~/SunFounder_PiCar $ sudo python setup.py installAdding SunFounder-PiCar 1.0.1 to easy-install.pth fileInstalling picar script to /usr/local/bin[omitted....]# Download patched PiCar-V applications# and install depedent softwarepi@raspberrypi:~/SunFounder_PiCar/picar $ cdpi@raspberrypi:~ $ git clone https://github.com/dctian/SunFounder_PiCar-V.gitCloning into 'SunFounder_PiCar-V'...remote: Enumerating objects: 969, done.remote: Total 969 (delta 0), reused 0 (delta 0), pack-reused 969Receiving objects: 100% (969/969), 9.46 MiB | 849.00 KiB/s, done.Resolving deltas: 100% (432/432), done.pi@raspberrypi:~ $ cd SunFounder_PiCar-Vpi@raspberrypi:~/SunFounder_PiCar-V $ sudo ./install_dependenciesAdding SunFounder-PiCar 1.0.1 to easy-install.pth fileInstalling picar script to /usr/local/binInstalled /usr/local/lib/python2.7/dist-packages/SunFounder_PiCar-1.0.1-py2.7.eggProcessing dependencies for SunFounder-PiCar==1.0.1Finished processing dependencies for SunFounder-PiCar==1.0.1completeCopy MJPG-Streamer to an Alternate Location. completeEnalbe I2C. completeInstallation result:django Successpython-smbus Successpython-opencv Successlibjpeg8-dev SuccessThe stuff you have change may need reboot to take effect.Do you want to reboot immediately? (yes/no)yes Answer Yes, when prompted to reboot. After reboot, all required hardware drivers should be installed. We will test them after the car assembly. The assembly process closely reassembles building a complex Lego set, and the whole process takes about 2 hours, a lot of hand-eye coordination and is loads of fun. (You may even involve your younger ones during the construction phase.) PiCar Kit comes with a printed step-by-step instructional manual. But I recommend these two additional resources. PDF version of the instructional manual. The print manual is small, and diagrams may not be printed very clearly, whereas the PDF version is crystal clear, can be searched and zoomed in for more details. I found it very helpful with the PDF on my laptop during the assembly phase. YouTube 4-part instructional videos published by SunFounder. Unfortunately, these videos are for an older version of PiCar, so some parts (like the servo motor assembly) are different. But most parts and assembling techniques are the same. So if you are scratching your head at a particular diagram in the assembly manual, you may want to take a look at the relevant parts of the videos. I wish SunFounder would publish a new set of videos for the new PiCar-V kit. Now that all the basic hardware and software for the PiCar is in place, let’s try to run it! Connect to PiCar via VNC from PC Make sure fresh batteries are in, toggle the switch to ON position and unplug the micro USB charging cable. Note that your VNC remote session should still be alive. In a Pi Terminal, run the following commands (in bold). You should: see the car going faster, and then slow down when you issue picar.back_wheel.test()see the front wheels steer left, center and right when you issuepicar.front_wheel.test(). To stop these tests, press Ctrl-C. To exit the python program, press Ctrl-D. see the car going faster, and then slow down when you issue picar.back_wheel.test() see the front wheels steer left, center and right when you issuepicar.front_wheel.test(). To stop these tests, press Ctrl-C. To exit the python program, press Ctrl-D. pi@raspberrypi:~/SunFounder_PiCar/picar $ python3 Python 3.5.3 (default, Sep 27 2018, 17:25:39) [GCC 6.3.0 20170516] on linuxType "help", "copyright", "credits" or "license" for more information.>>> import picar>>> picar.setup()>>> picar.front_wheels.test()DEBUG "front_wheels.py": Set debug offDEBUG "front_wheels.py": Set wheel debug offDEBUG "Servo.py": Set debug offturn_leftturn_straightturn_right>>> picar.back_wheels.test()DEBUG "back_wheels.py": Set debug offDEBUG "TB6612.py": Set debug offDEBUG "TB6612.py": Set debug offDEBUG "PCA9685.py": Set debug offForward, speed = 0Forward, speed = 1Forward, speed = 2Forward, speed = 3Forward, speed = 4Forward, speed = 5Forward, speed = 6Forward, speed = 7Forward, speed = 8Forward, speed = 9Forward, speed = 10Forward, speed = 11 If you run into errors or don’t see the wheels moving, then either something is wrong with your hardware connection or software set up. For the former, please double check your wires connections, make sure the batteries are fully charged. For the latter, please post a message in the comment section with detailed steps you followed and the error messages, and I will try to help. Congratulations, you should now have a PiCar that can see (via Cheese), and run (via python 3 code)! It is not quite a Deep Learning car yet, but we are well on our way to that. Whenever you are ready, head on over to Part 3, where we will give PiCar the superpower of computer vision and deep learning. Here are the links to the whole guide: Part 1: Overview Part 2: Raspberry Pi Setup and PiCar Assembly (This article) Part 3: Make PiCar See and Think Part 4: Autonomous Lane Navigation via OpenCV Part 5: Autonomous Lane Navigation via Deep Learning Part 6: Traffic Sign and Pedestrian Detection and Handling
[ { "code": null, "e": 380, "s": 171, "text": "Welcome back! In this guide, we will first go over what hardware to purchase and why we need them. Next, we will set them up so that we will have a PiCar running in our living room by the end of this article." }, { "code": null, "e": 870, "s": 380, "text": "1 x Raspberry Pi 3 Model B+ kit with 2.5A Power Supply ($50) This is the brain of your DeepPiCar. This latest model of Raspberry Pi features a 1.4Ghz 64-bit Quad-Core processor, dual band wifi, Bluetooth, 4 USB ports, and an HDMI port. I recommend this kit (over just the Raspberry Pi board) because it comes with a power adapter, which you need to plug in while doing your non-driving coding and testing, and two chip heat sinks, which will prevent your Raspberry Pi CPU from overheating." }, { "code": null, "e": 1302, "s": 870, "text": "1 x 64 GB micro SD Card ($8) This is where your Raspberry Pi’s operating system and all of our software will be stored. Any brand of micro SD card should work fine. You may just have one lying around your house. 32GB should be fine as well. I choose 64 GB because I plan to record lots of videos of while my car is driving so that I can analyze its behavior later, and use the videos to do deep learning training in later projects." }, { "code": null, "e": 2030, "s": 1302, "text": "1 x SunFounder PiCar-V kit ($115) This is the main body of DeepPiCar. Make sure you get the Model V as shown above(a.k.a. Version 2.0). It comes with everything you need in a robotics car, except for the Raspberry Pi and the batteries. There are a number of Raspberry Pi car kits on the market, I chose this car kit because it comes with an open source python API to control the car, whereas other vendors have its proprietary API or C based API. As we know, python is now the language of choice for machine learning and deep learning. Also, open source is important as we may tinker with the internals of the car API ourselves if we find bugs in the API without having to wait for the manufacturer to provide software updates." }, { "code": null, "e": 2508, "s": 2030, "text": "4 x 18650 batteries and 1 x battery charger ($20) You may get any 18650 batteries and compatible chargers. These batteries are for high drain applications, such as driving the Raspberry Pi board and the PiCar. PiCar takes only two batteries, but you always want to have another freshly charged pair around, so that you can keep your car running on the tracks at all times. I recommend charging both sets at night, so you won’t have to worry about dead batteries during testing." }, { "code": null, "e": 3502, "s": 2508, "text": "1 x Google Edge TPU USB Accelerator ($75) Every hero needs a sidekick. Google’s Edge TPU (Edge means it's for mobile and embedded devices and TPU stands Tensor Processing Unit) is a wonderful add-on to the Raspberry Pi board. While the Pi CPU packs a lot of computing power in a tiny bundle, it is NOT designed to do deep learning. Google’s newly released Edge TPU(March 2019), on the other hand, is specifically designed to run deep learning models written in TensorFlow. In Part 6 of this series, we will build a real-time traffic sign detection model in TensorFlow. This model is 200+ layers deep! Running this model on Raspberry Pi’s CPU alone can only process 1 Frame per Second (FPS) which is hardly real-time. Plus it consumes 100% of the CPU and makes all the other programs non-responsive. But with the help of Edge TPU, we can now process 12 FPS, which is adequate for real-time work. And our CPU stays cool and can be utilized to do other processing tasks, like controlling the car." }, { "code": null, "e": 3777, "s": 3502, "text": "1 x Set of Miniature Traffic Signs ($15) and a few Lego figurines. You may not need to buy them if your younger ones have some of these toy signs and Lego figurines in the playroom. You can use whatever signs you find to train the model, just make sure they are not TOO BIG!" }, { "code": null, "e": 4523, "s": 3777, "text": "(Optional) 1 x 170 degree Wide Angle USB Camera ($40). This is an optional accessory. I bought it to replace the stock camera that came with the SunFounder PiCar so that the car can have a wide field of vision. The stock camera is great, but not as wide angle as I like and it can’t see lane lines that are 3–4 inches in front of the front wheels. I wrote the lane following code in Part 4 with the stock camera initially. After trying a few lens, I found that the lane following accuracy and stability greatly increased with this wide angle camera. It is nice to have control of both your hardware and software (vs running a car in car simulator), because you may resort to a hardware fix if a problem can’t be easily solved via software alone." }, { "code": null, "e": 4697, "s": 4523, "text": "USB Keyboard/Mouse and Monitor that takes HDMI input. You only need these during the initial setup stage of the Pi. Afterward, we can remote control the Pi via VNC or Putty." }, { "code": null, "e": 4873, "s": 4697, "text": "A desktop or laptop computer running Windows/Mac or Linux, which I will refer to as “PC” here onwards. We will use this PC to remote access and deploy code to the Pi computer." }, { "code": null, "e": 5152, "s": 4873, "text": "Sometimes, it surprises me that Raspberry Pi, the brain of our car is only about $30 and cheaper than many of our other accessories. Indeed, the hardware is getting cheaper and more powerful over time, and software is completely free and abundant. Don’t we live in a GREAT era?!" }, { "code": null, "e": 5240, "s": 5152, "text": "This is the end product when the assembly is done. I am using a wide-angle camera here." }, { "code": null, "e": 5577, "s": 5240, "text": "Follow this excellent step-by-step guide to install the NOOBS Raspbian Operating System (a variate of Linux) onto a micro SD card. It would take about 20 min and about 4GB of disk space. After installation and reboot, you should see a full GUI desktop like below. This feels like you are in a Windows or Mac GUI environment, doesn’t it?" }, { "code": null, "e": 5707, "s": 5577, "text": "During installation, Pi will ask you to change the password for the default user pi. Let’s set the password to rasp, for example." }, { "code": null, "e": 5823, "s": 5707, "text": "After the initial installation, Pi may need to upgrade to the latest software. This may take another 10–15 minutes." }, { "code": null, "e": 6121, "s": 5823, "text": "Setting up remote access allows Pi computer to run headless (i.e. without a monitor/keyboard/mouse) which saves us from having to connect a monitor and keyboard/mouse to it all the time. This video gives a very good tutorial on how to set up SSH and VNC Remote Access. Here are the steps, anyways." }, { "code": null, "e": 6286, "s": 6121, "text": "Open the Terminal application, as shown below. The Terminal app is a very important program, as most of our command in later articles will be entered from Terminal." }, { "code": null, "e": 6388, "s": 6286, "text": "Find the IP address of the Pi by running ifconfig. In this case, my Pi’s IP address is 192.168.1.120." }, { "code": null, "e": 6566, "s": 6388, "text": "pi@raspberrypi:~ $ ifconfig | grep wlan0 -A1wlan0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500 inet 192.168.1.120 netmask 255.255.255.0 broadcast 192.168.1.255" }, { "code": null, "e": 6713, "s": 6566, "text": "Run sudo raspi-config in Terminal to start the “Raspberry Pi Software Configuration Tool”. You may be prompted to type in the password for user pi" }, { "code": null, "e": 6777, "s": 6713, "text": "Enable SSH Server: Choose 5. Interface Options -> SSH -> Enable" }, { "code": null, "e": 6841, "s": 6777, "text": "Enable VNC Server: Choose 5. Interface Options -> VNC -> Enable" }, { "code": null, "e": 6891, "s": 6841, "text": "Download and install RealVNC Viewer onto your PC." }, { "code": null, "e": 6997, "s": 6891, "text": "Connect to Pi’s IP address using Real VNC Viewer. You will see the same desktop as the one Pi is running." }, { "code": null, "e": 7130, "s": 6997, "text": "At this point, you can safely disconnect the monitor/keyboard/mouse from the Pi computer, leaving just the power adapter plugged in." }, { "code": null, "e": 7337, "s": 7130, "text": "Since our Pi will be running headless, we want to be able to access Pi’s file system from a remote computer so that we can transfer files to/from Pi computer easily. We will install Samba File Server on Pi." }, { "code": null, "e": 7918, "s": 7337, "text": "pi@raspberrypi:~ $ sudo apt-get update && sudo apt-get upgrade -yGet:1 http://archive.raspberrypi.org/debian stretch InRelease [25.4 kB]Packages [45.0 kB][omitted...]Unpacking lxplug-ptbatt (0.5) over (0.4) ...Setting up lxplug-ptbatt (0.5) ...pi@raspberrypi:~ $ sudo apt-get install samba samba-common-bin -yReading package lists... DoneBuilding dependency tree [omitted...]Processing triggers for libc-bin (2.24-11+deb9u4) ...Processing triggers for systemd (232-25+deb9u11) ...pi@raspberrypi:~ $ sudo rm /etc/samba/smb.confpi@raspberrypi:~ $ sudo nano /etc/samba/smb.conf" }, { "code": null, "e": 7973, "s": 7918, "text": "Then paste in the following lines into the nano editor" }, { "code": null, "e": 8179, "s": 7973, "text": "[global]netbios name = Piserver string = The PiCar File Systemworkgroup = WORKGROUP[HOMEPI]path = /home/picomment = No commentbrowsable = yeswritable = Yescreate mask = 0777directory mask = 0777public = no" }, { "code": null, "e": 8234, "s": 8179, "text": "Save and exit nano by Ctrl-X, and Yes to save changes." }, { "code": null, "e": 8396, "s": 8234, "text": "Then set up a Samba Server password. For simplicity, we will use the same rasp as the Samba server password. After the password is set, restart the Samba server." }, { "code": null, "e": 8580, "s": 8396, "text": "# create samba passwordpi@raspberrypi:~ $ sudo smbpasswd -a piNew SMB password:Retype new SMB password:Added user pi.# restart samba serverpi@raspberrypi:~ $ sudo service smbd restart" }, { "code": null, "e": 8775, "s": 8580, "text": "At this point, you should be able to connect to the Pi computer from your PC via Pi’s IP address (My Pi’s IP is 192.168.1.120). Go to your PC (Windows), open a Command Prompt (cmd.exe) and type:" }, { "code": null, "e": 9591, "s": 8775, "text": "# mount the Pi home directory to R: drive on PCC:\\>net use r: \\\\192.168.1.120\\homepiThe command completed successfully.C:\\Users\\dctia>r:C:\\>dir r: Volume in drive R is HOMEPI Volume Serial Number is 61E3-70FFDirectory of R:\\05/02/2019 03:57 PM <DIR> .04/08/2019 04:48 AM <DIR> ..04/08/2019 05:43 AM <DIR> Desktop04/08/2019 05:43 AM <DIR> Documents04/08/2019 05:43 AM <DIR> Downloads04/08/2019 05:15 AM <DIR> MagPi04/08/2019 05:43 AM <DIR> Music05/02/2019 03:43 PM <DIR> Pictures04/08/2019 05:43 AM <DIR> Public04/08/2019 05:43 AM <DIR> Templates04/08/2019 05:43 AM <DIR> Videos 0 File(s) 0 bytes 11 Dir(s) 22,864,379,904 bytes free" }, { "code": null, "e": 9902, "s": 9591, "text": "Indeed this is our Pi Computer’s file system that we can see from its file manager. This will be very useful since we can edit files that reside on Pi directly from our PC. For example, we can use PyCharm IDE to edit Python programs on Pi first, and then just use Pi’s terminal (via VNC) to run these programs." }, { "code": null, "e": 10400, "s": 9902, "text": "If you have a Mac, here is how to connect to the Pi’s file server. Hit Command-K to bring up the “Connect to Server” window. Enter the network drive path (replace with your Pi’s IP address), i.e. smb://192.168.1.120/homepi, and click Connect. Enter the login/password, i.e. pi/rasp and click OK to mount the network drive. Then the drive will now appear on your desktop and in the Finder Window sidebar. For more in-depth network connectivity instructions on Mac, check out this excellent article." }, { "code": null, "e": 10539, "s": 10400, "text": "The device driver for the USB camera should already come with Raspian OS. We will install a Video Camera Viewer so we can see live videos." }, { "code": null, "e": 10613, "s": 10539, "text": "Take the USB Camera out of PiCar kit and plug into Pi computer’s USB port" }, { "code": null, "e": 10703, "s": 10613, "text": "Run sudo apt-get install cheese from the terminal to install “Cheese”, the camera viewer." }, { "code": null, "e": 10890, "s": 10703, "text": "pi@raspberrypi:~ $ sudo apt-get install cheese -yReading package lists... DoneBuilding dependency tree Reading state information... Done....cheese is the newest version (3.22.1-1)." }, { "code": null, "e": 11041, "s": 10890, "text": "Launch Cheese app by Raspberry Pi button(Top Left Corner)-> Sound & Video -> Cheese You should see a live video feed displayed like the picture above." }, { "code": null, "e": 11794, "s": 11041, "text": "Before assembling PiCar, we need to install PiCar’s python API. SunFounder release a server version and client version of its Python API. The Client API code, which is intended to remote control your PiCar, runs on your PC, and it uses Python version 3. The Server API code runs on PiCar, unfortunately, it uses Python version 2, which is an outdated version. Since the self-driving programs that we write will exclusively run on PiCar, the PiCar Server API must run in Python 3 also. Fortunately, all of SunFounder’s API code are open source on Github, I made a fork and updated the entire repo (both server and client) to Python 3. (I will submit my changes to SunFounder soon, so it can be merged back to the main repo, once approved by SunFounder.)" }, { "code": null, "e": 11975, "s": 11794, "text": "For the time being, run the following commands (in bold) instead of the software commands in the SunFounder manual. You shouldn’t have to run commands on Pages 20–26 of the manual." }, { "code": null, "e": 14421, "s": 11975, "text": "# route all calls to python (version 2) to python3, # pip (version 2) to pip3, even in sudo mode # note: `sudo abcd` runs `abcd` command in administrator modealias python=python3alias pip=pip3alias sudo='sudo '# Download patched PiCar-V driver API, and run its set uppi@raspberrypi:~ $ cdpi@raspberrypi:~ $ git clone https://github.com/dctian/SunFounder_PiCar.gitCloning into 'SunFounder_PiCar'...remote: Enumerating objects: 9, done.remote: Counting objects: 100% (9/9), done.remote: Compressing objects: 100% (9/9), done.remote: Total 276 (delta 0), reused 2 (delta 0), pack-reused 267Receiving objects: 100% (276/276), 53.33 KiB | 0 bytes/s, done.Resolving deltas: 100% (171/171), done.pi@raspberrypi:~ $ cd ~/SunFounder_PiCar/picar/pi@raspberrypi:~/SunFounder_PiCar/picar $ git clone https://github.com/dctian/SunFounder_PCA9685.gitCloning into 'SunFounder_PCA9685'...remote: Enumerating objects: 7, done.remote: Counting objects: 100% (7/7), done.remote: Compressing objects: 100% (5/5), done.remote: Total 87 (delta 2), reused 6 (delta 2), pack-reused 80Unpacking objects: 100% (87/87), done.pi@raspberrypi:~/SunFounder_PiCar/picar $ cd ~/SunFounder_PiCar/pi@raspberrypi:~/SunFounder_PiCar $ sudo python setup.py installAdding SunFounder-PiCar 1.0.1 to easy-install.pth fileInstalling picar script to /usr/local/bin[omitted....]# Download patched PiCar-V applications# and install depedent softwarepi@raspberrypi:~/SunFounder_PiCar/picar $ cdpi@raspberrypi:~ $ git clone https://github.com/dctian/SunFounder_PiCar-V.gitCloning into 'SunFounder_PiCar-V'...remote: Enumerating objects: 969, done.remote: Total 969 (delta 0), reused 0 (delta 0), pack-reused 969Receiving objects: 100% (969/969), 9.46 MiB | 849.00 KiB/s, done.Resolving deltas: 100% (432/432), done.pi@raspberrypi:~ $ cd SunFounder_PiCar-Vpi@raspberrypi:~/SunFounder_PiCar-V $ sudo ./install_dependenciesAdding SunFounder-PiCar 1.0.1 to easy-install.pth fileInstalling picar script to /usr/local/binInstalled /usr/local/lib/python2.7/dist-packages/SunFounder_PiCar-1.0.1-py2.7.eggProcessing dependencies for SunFounder-PiCar==1.0.1Finished processing dependencies for SunFounder-PiCar==1.0.1completeCopy MJPG-Streamer to an Alternate Location. completeEnalbe I2C. completeInstallation result:django Successpython-smbus Successpython-opencv Successlibjpeg8-dev SuccessThe stuff you have change may need reboot to take effect.Do you want to reboot immediately? (yes/no)yes" }, { "code": null, "e": 14565, "s": 14421, "text": "Answer Yes, when prompted to reboot. After reboot, all required hardware drivers should be installed. We will test them after the car assembly." }, { "code": null, "e": 14916, "s": 14565, "text": "The assembly process closely reassembles building a complex Lego set, and the whole process takes about 2 hours, a lot of hand-eye coordination and is loads of fun. (You may even involve your younger ones during the construction phase.) PiCar Kit comes with a printed step-by-step instructional manual. But I recommend these two additional resources." }, { "code": null, "e": 15197, "s": 14916, "text": "PDF version of the instructional manual. The print manual is small, and diagrams may not be printed very clearly, whereas the PDF version is crystal clear, can be searched and zoomed in for more details. I found it very helpful with the PDF on my laptop during the assembly phase." }, { "code": null, "e": 15662, "s": 15197, "text": "YouTube 4-part instructional videos published by SunFounder. Unfortunately, these videos are for an older version of PiCar, so some parts (like the servo motor assembly) are different. But most parts and assembling techniques are the same. So if you are scratching your head at a particular diagram in the assembly manual, you may want to take a look at the relevant parts of the videos. I wish SunFounder would publish a new set of videos for the new PiCar-V kit." }, { "code": null, "e": 15755, "s": 15662, "text": "Now that all the basic hardware and software for the PiCar is in place, let’s try to run it!" }, { "code": null, "e": 15788, "s": 15755, "text": "Connect to PiCar via VNC from PC" }, { "code": null, "e": 15953, "s": 15788, "text": "Make sure fresh batteries are in, toggle the switch to ON position and unplug the micro USB charging cable. Note that your VNC remote session should still be alive." }, { "code": null, "e": 16021, "s": 15953, "text": "In a Pi Terminal, run the following commands (in bold). You should:" }, { "code": null, "e": 16271, "s": 16021, "text": "see the car going faster, and then slow down when you issue picar.back_wheel.test()see the front wheels steer left, center and right when you issuepicar.front_wheel.test(). To stop these tests, press Ctrl-C. To exit the python program, press Ctrl-D." }, { "code": null, "e": 16355, "s": 16271, "text": "see the car going faster, and then slow down when you issue picar.back_wheel.test()" }, { "code": null, "e": 16522, "s": 16355, "text": "see the front wheels steer left, center and right when you issuepicar.front_wheel.test(). To stop these tests, press Ctrl-C. To exit the python program, press Ctrl-D." }, { "code": null, "e": 17305, "s": 16522, "text": "pi@raspberrypi:~/SunFounder_PiCar/picar $ python3 Python 3.5.3 (default, Sep 27 2018, 17:25:39) [GCC 6.3.0 20170516] on linuxType \"help\", \"copyright\", \"credits\" or \"license\" for more information.>>> import picar>>> picar.setup()>>> picar.front_wheels.test()DEBUG \"front_wheels.py\": Set debug offDEBUG \"front_wheels.py\": Set wheel debug offDEBUG \"Servo.py\": Set debug offturn_leftturn_straightturn_right>>> picar.back_wheels.test()DEBUG \"back_wheels.py\": Set debug offDEBUG \"TB6612.py\": Set debug offDEBUG \"TB6612.py\": Set debug offDEBUG \"PCA9685.py\": Set debug offForward, speed = 0Forward, speed = 1Forward, speed = 2Forward, speed = 3Forward, speed = 4Forward, speed = 5Forward, speed = 6Forward, speed = 7Forward, speed = 8Forward, speed = 9Forward, speed = 10Forward, speed = 11" }, { "code": null, "e": 17686, "s": 17305, "text": "If you run into errors or don’t see the wheels moving, then either something is wrong with your hardware connection or software set up. For the former, please double check your wires connections, make sure the batteries are fully charged. For the latter, please post a message in the comment section with detailed steps you followed and the error messages, and I will try to help." }, { "code": null, "e": 17990, "s": 17686, "text": "Congratulations, you should now have a PiCar that can see (via Cheese), and run (via python 3 code)! It is not quite a Deep Learning car yet, but we are well on our way to that. Whenever you are ready, head on over to Part 3, where we will give PiCar the superpower of computer vision and deep learning." }, { "code": null, "e": 18029, "s": 17990, "text": "Here are the links to the whole guide:" }, { "code": null, "e": 18046, "s": 18029, "text": "Part 1: Overview" }, { "code": null, "e": 18107, "s": 18046, "text": "Part 2: Raspberry Pi Setup and PiCar Assembly (This article)" }, { "code": null, "e": 18140, "s": 18107, "text": "Part 3: Make PiCar See and Think" }, { "code": null, "e": 18186, "s": 18140, "text": "Part 4: Autonomous Lane Navigation via OpenCV" }, { "code": null, "e": 18239, "s": 18186, "text": "Part 5: Autonomous Lane Navigation via Deep Learning" } ]
Python | sympy.solve() method
12 Jun, 2019 With the help of sympy.solve(expression) method, we can solve the mathematical equations easily and it will return the roots of the equation that is provided as parameter using sympy.solve() method. Syntax : sympy.solve(expression)Return : Return the roots of the equation. Example #1 :In this example we can see that by using sympy.solve() method, we can solve the mathematical expressions and this will return the roots of that equation. # import sympyfrom sympy import * x, y = symbols('x y')gfg_exp = x**2 - 4 print("Before Integration : {}".format(gfg_exp)) # Use sympy.integrate() methodintr = solve(gfg_exp, x) print("After Integration : {}".format(intr)) Output : Before Integration : x**2 – 4 After Integration : [-2, 2] Example #2 : # import sympyfrom sympy import * x, y = symbols('x y')gfg_exp = x**2 + 36 print("Before Integration : {}".format(gfg_exp)) # Use sympy.integrate() methodintr = solve(gfg_exp, x) print("After Integration : {}".format(intr)) Output : Before Integration : x**2 + 36 After Integration : [-6*I, 6*I] SymPy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Iterate over a list in Python Python Classes and Objects Convert integer to string in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n12 Jun, 2019" }, { "code": null, "e": 227, "s": 28, "text": "With the help of sympy.solve(expression) method, we can solve the mathematical equations easily and it will return the roots of the equation that is provided as parameter using sympy.solve() method." }, { "code": null, "e": 302, "s": 227, "text": "Syntax : sympy.solve(expression)Return : Return the roots of the equation." }, { "code": null, "e": 468, "s": 302, "text": "Example #1 :In this example we can see that by using sympy.solve() method, we can solve the mathematical expressions and this will return the roots of that equation." }, { "code": "# import sympyfrom sympy import * x, y = symbols('x y')gfg_exp = x**2 - 4 print(\"Before Integration : {}\".format(gfg_exp)) # Use sympy.integrate() methodintr = solve(gfg_exp, x) print(\"After Integration : {}\".format(intr))", "e": 695, "s": 468, "text": null }, { "code": null, "e": 704, "s": 695, "text": "Output :" }, { "code": null, "e": 734, "s": 704, "text": "Before Integration : x**2 – 4" }, { "code": null, "e": 762, "s": 734, "text": "After Integration : [-2, 2]" }, { "code": null, "e": 777, "s": 764, "text": "Example #2 :" }, { "code": "# import sympyfrom sympy import * x, y = symbols('x y')gfg_exp = x**2 + 36 print(\"Before Integration : {}\".format(gfg_exp)) # Use sympy.integrate() methodintr = solve(gfg_exp, x) print(\"After Integration : {}\".format(intr))", "e": 1006, "s": 777, "text": null }, { "code": null, "e": 1015, "s": 1006, "text": "Output :" }, { "code": null, "e": 1046, "s": 1015, "text": "Before Integration : x**2 + 36" }, { "code": null, "e": 1078, "s": 1046, "text": "After Integration : [-6*I, 6*I]" }, { "code": null, "e": 1084, "s": 1078, "text": "SymPy" }, { "code": null, "e": 1091, "s": 1084, "text": "Python" }, { "code": null, "e": 1189, "s": 1091, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1207, "s": 1189, "text": "Python Dictionary" }, { "code": null, "e": 1249, "s": 1207, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1271, "s": 1249, "text": "Enumerate() in Python" }, { "code": null, "e": 1306, "s": 1271, "text": "Read a file line by line in Python" }, { "code": null, "e": 1332, "s": 1306, "text": "Python String | replace()" }, { "code": null, "e": 1364, "s": 1332, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1393, "s": 1364, "text": "*args and **kwargs in Python" }, { "code": null, "e": 1423, "s": 1393, "text": "Iterate over a list in Python" }, { "code": null, "e": 1450, "s": 1423, "text": "Python Classes and Objects" } ]
Collectors partitioningBy() method in Java
06 Dec, 2018 Collectors partitioningBy() method is a predefined method of java.util.stream.Collectors class which is used to partition a stream of objects(or a set of elements) based on a given predicate. There are two overloaded variants of the method that are present. One takes only a predicate as a parameter whereas the other takes both predicate and a collector instance as parameters. Syntax: public static <T> Collector<T, ?, Map<Boolean, List<T>>> partitioningBy(Predicate<? super T> predicate) where, Interface Collector<T, A, R>: A mutable reduction operation that accumulates input elements into a mutable result container, optionally transforming the accumulated result into a final representation after all input elements have been processed. Reduction operations can be performed either sequentially or in parallel.T: The type of input elements to the reduction operation.A: The mutable accumulation type of the reduction operation.R: The result type of the reduction operation. T: The type of input elements to the reduction operation. A: The mutable accumulation type of the reduction operation. R: The result type of the reduction operation. Map<Boolean, List<T>>: The map containing the output.Keys are boolean values(true or false) and the corresponding values are lists containing elements of type T. Parameters: This method takes a mandatory parameter predicate which an instance of a Predicate Interface of type T. Return Value: This method returns a Collector implementing the partitioning operation. Below is an example to illustrate partitioningBy() method: Program: // Java code to show the implementation of// Collectors partitioningBy() function import java.util.List;import java.util.Map;import java.util.stream.Collectors;import java.util.stream.Stream; class Gfg { // Driver code public static void main(String[] args) { // creating an Integer stream Stream<Integer> s = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); // using Collectors partitioningBy() // method to split the stream of elements into // 2 parts, greater than 3 and less than 3. Map<Boolean, List<Integer> > map = s.collect( Collectors.partitioningBy(num -> num > 3)); // Displaying the result as a map // true if greater than 3, false otherwise System.out.println("Elements in stream " + "partitioned by " + "less than equal to 3: \n" + map); }} Elements in stream partitioned by less than equal to 3: {false=[1, 2, 3], true=[4, 5, 6, 7, 8, 9, 10]} Syntax: public static <T> Collector<T, ?, Map<Boolean, List<T>>> partitioningBy(Predicate<? super T>predicate, Collector<? super T, A, D> downstream) where, Interface Collector<T, A, R>: A mutable reduction operation that accumulates input elements into a mutable result container, optionally transforming the accumulated result into a final representation after all input elements have been processed. Reduction operations can be performed either sequentially or in parallel.T: The type of input elements to the reduction operation.A: The mutable accumulation type of the reduction operation.R: The result type of the reduction operation. T: The type of input elements to the reduction operation. A: The mutable accumulation type of the reduction operation. R: The result type of the reduction operation. Map<Boolean, List<T>>: The map containing the output.Keys are boolean values(true or false) and the corresponding values are lists containing elements of type T. Parameters: This method takes two parameters a predicate which an instance of a Predicate Interface of type T, and a collector which is used for implementing “downstream reduction” and producing the output. Return Value: This method returns a Collector implementing the partitioning operation. Below is an example to illustrate type 2 of partitioningBy() method: // Java code to show the implementation of// Collectors partitioningBy() function import java.util.List;import java.util.Map;import java.util.stream.Collectors;import java.util.stream.Stream; class ArraytoArrayList { // Driver code public static void main(String[] args) { // creating an Integer stream Stream<Integer> s = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); // Using Collectors.counting() method // to count the number of elements in // the 2 partitions Map<Boolean, Long> map = s.collect( Collectors.partitioningBy( num -> (num > 3), Collectors.counting())); // Displaying the result as a map // true if greater than 3, false otherwise System.out.println("Elements in stream " + "partitioned by " + "less than equal to 3: \n" + map); }} Elements in stream partitioned by less than equal to 3: {false=3, true=7} Java - util package Java 8 Java-Collectors Java-Functions java-stream Java-Stream-Collectors Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Dec, 2018" }, { "code": null, "e": 407, "s": 28, "text": "Collectors partitioningBy() method is a predefined method of java.util.stream.Collectors class which is used to partition a stream of objects(or a set of elements) based on a given predicate. There are two overloaded variants of the method that are present. One takes only a predicate as a parameter whereas the other takes both predicate and a collector instance as parameters." }, { "code": null, "e": 415, "s": 407, "text": "Syntax:" }, { "code": null, "e": 519, "s": 415, "text": "public static <T> Collector<T, ?, Map<Boolean, List<T>>> partitioningBy(Predicate<? super T> predicate)" }, { "code": null, "e": 526, "s": 519, "text": "where," }, { "code": null, "e": 1009, "s": 526, "text": "Interface Collector<T, A, R>: A mutable reduction operation that accumulates input elements into a mutable result container, optionally transforming the accumulated result into a final representation after all input elements have been processed. Reduction operations can be performed either sequentially or in parallel.T: The type of input elements to the reduction operation.A: The mutable accumulation type of the reduction operation.R: The result type of the reduction operation." }, { "code": null, "e": 1067, "s": 1009, "text": "T: The type of input elements to the reduction operation." }, { "code": null, "e": 1128, "s": 1067, "text": "A: The mutable accumulation type of the reduction operation." }, { "code": null, "e": 1175, "s": 1128, "text": "R: The result type of the reduction operation." }, { "code": null, "e": 1337, "s": 1175, "text": "Map<Boolean, List<T>>: The map containing the output.Keys are boolean values(true or false) and the corresponding values are lists containing elements of type T." }, { "code": null, "e": 1453, "s": 1337, "text": "Parameters: This method takes a mandatory parameter predicate which an instance of a Predicate Interface of type T." }, { "code": null, "e": 1540, "s": 1453, "text": "Return Value: This method returns a Collector implementing the partitioning operation." }, { "code": null, "e": 1599, "s": 1540, "text": "Below is an example to illustrate partitioningBy() method:" }, { "code": null, "e": 1608, "s": 1599, "text": "Program:" }, { "code": "// Java code to show the implementation of// Collectors partitioningBy() function import java.util.List;import java.util.Map;import java.util.stream.Collectors;import java.util.stream.Stream; class Gfg { // Driver code public static void main(String[] args) { // creating an Integer stream Stream<Integer> s = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); // using Collectors partitioningBy() // method to split the stream of elements into // 2 parts, greater than 3 and less than 3. Map<Boolean, List<Integer> > map = s.collect( Collectors.partitioningBy(num -> num > 3)); // Displaying the result as a map // true if greater than 3, false otherwise System.out.println(\"Elements in stream \" + \"partitioned by \" + \"less than equal to 3: \\n\" + map); }}", "e": 2554, "s": 1608, "text": null }, { "code": null, "e": 2659, "s": 2554, "text": "Elements in stream partitioned by less than equal to 3: \n{false=[1, 2, 3], true=[4, 5, 6, 7, 8, 9, 10]}\n" }, { "code": null, "e": 2667, "s": 2659, "text": "Syntax:" }, { "code": null, "e": 2809, "s": 2667, "text": "public static <T> Collector<T, ?, Map<Boolean, List<T>>> partitioningBy(Predicate<? super T>predicate, Collector<? super T, A, D> downstream)" }, { "code": null, "e": 2816, "s": 2809, "text": "where," }, { "code": null, "e": 3299, "s": 2816, "text": "Interface Collector<T, A, R>: A mutable reduction operation that accumulates input elements into a mutable result container, optionally transforming the accumulated result into a final representation after all input elements have been processed. Reduction operations can be performed either sequentially or in parallel.T: The type of input elements to the reduction operation.A: The mutable accumulation type of the reduction operation.R: The result type of the reduction operation." }, { "code": null, "e": 3357, "s": 3299, "text": "T: The type of input elements to the reduction operation." }, { "code": null, "e": 3418, "s": 3357, "text": "A: The mutable accumulation type of the reduction operation." }, { "code": null, "e": 3465, "s": 3418, "text": "R: The result type of the reduction operation." }, { "code": null, "e": 3627, "s": 3465, "text": "Map<Boolean, List<T>>: The map containing the output.Keys are boolean values(true or false) and the corresponding values are lists containing elements of type T." }, { "code": null, "e": 3834, "s": 3627, "text": "Parameters: This method takes two parameters a predicate which an instance of a Predicate Interface of type T, and a collector which is used for implementing “downstream reduction” and producing the output." }, { "code": null, "e": 3921, "s": 3834, "text": "Return Value: This method returns a Collector implementing the partitioning operation." }, { "code": null, "e": 3990, "s": 3921, "text": "Below is an example to illustrate type 2 of partitioningBy() method:" }, { "code": "// Java code to show the implementation of// Collectors partitioningBy() function import java.util.List;import java.util.Map;import java.util.stream.Collectors;import java.util.stream.Stream; class ArraytoArrayList { // Driver code public static void main(String[] args) { // creating an Integer stream Stream<Integer> s = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); // Using Collectors.counting() method // to count the number of elements in // the 2 partitions Map<Boolean, Long> map = s.collect( Collectors.partitioningBy( num -> (num > 3), Collectors.counting())); // Displaying the result as a map // true if greater than 3, false otherwise System.out.println(\"Elements in stream \" + \"partitioned by \" + \"less than equal to 3: \\n\" + map); }}", "e": 4952, "s": 3990, "text": null }, { "code": null, "e": 5028, "s": 4952, "text": "Elements in stream partitioned by less than equal to 3: \n{false=3, true=7}\n" }, { "code": null, "e": 5048, "s": 5028, "text": "Java - util package" }, { "code": null, "e": 5055, "s": 5048, "text": "Java 8" }, { "code": null, "e": 5071, "s": 5055, "text": "Java-Collectors" }, { "code": null, "e": 5086, "s": 5071, "text": "Java-Functions" }, { "code": null, "e": 5098, "s": 5086, "text": "java-stream" }, { "code": null, "e": 5121, "s": 5098, "text": "Java-Stream-Collectors" }, { "code": null, "e": 5126, "s": 5121, "text": "Java" }, { "code": null, "e": 5131, "s": 5126, "text": "Java" } ]
Maximum Length Bitonic Subarray | Set 1 (O(n) time and O(n) space)
12 Jan, 2022 Given an array A[0 ... n-1] containing n positive integers, a subarray A[i ... j] is bitonic if there is a k with i <= k <= j such that A[i] <= A[i + 1] ... = A[k + 1] >= .. A[j – 1] > = A[j]. Write a function that takes an array as argument and returns the length of the maximum length bitonic subarray. Expected time complexity of the solution is O(n)Simple Examples 1) A[] = {12, 4, 78, 90, 45, 23}, the maximum length bitonic subarray is {4, 78, 90, 45, 23} which is of length 5.2) A[] = {20, 4, 1, 2, 3, 4, 2, 10}, the maximum length bitonic subarray is {1, 2, 3, 4, 2} which is of length 5.Extreme Examples 1) A[] = {10}, the single element is bitonic, so output is 1.2) A[] = {10, 20, 30, 40}, the complete array itself is bitonic, so output is 4.3) A[] = {40, 30, 20, 10}, the complete array itself is bitonic, so output is 4. Solution Let us consider the array {12, 4, 78, 90, 45, 23} to understand the solution. 1) Construct an auxiliary array inc[] from left to right such that inc[i] contains length of the nondecreasing subarray ending at arr[i]. For A[] = {12, 4, 78, 90, 45, 23}, inc[] is {1, 1, 2, 3, 1, 1} 2) Construct another array dec[] from right to left such that dec[i] contains length of nonincreasing subarray starting at arr[i]. For A[] = {12, 4, 78, 90, 45, 23}, dec[] is {2, 1, 1, 3, 2, 1}.3) Once we have the inc[] and dec[] arrays, all we need to do is find the maximum value of (inc[i] + dec[i] – 1). For {12, 4, 78, 90, 45, 23}, the max value of (inc[i] + dec[i] – 1) is 5 for i = 3. C++ C Java Python3 C# PHP Javascript // C++ program to find length of// the longest bitonic subarray#include <bits/stdc++.h>using namespace std; int bitonic(int arr[], int n){ // Length of increasing subarray // ending at all indexes int inc[n]; // Length of decreasing subarray // starting at all indexes int dec[n]; int i, max; // length of increasing sequence // ending at first index is 1 inc[0] = 1; // length of increasing sequence // starting at first index is 1 dec[n-1] = 1; // Step 1) Construct increasing sequence array for (i = 1; i < n; i++) inc[i] = (arr[i] >= arr[i-1])? inc[i-1] + 1: 1; // Step 2) Construct decreasing sequence array for (i = n-2; i >= 0; i--) dec[i] = (arr[i] >= arr[i+1])? dec[i+1] + 1: 1; // Step 3) Find the length of // maximum length bitonic sequence max = inc[0] + dec[0] - 1; for (i = 1; i < n; i++) if (inc[i] + dec[i] - 1 > max) max = inc[i] + dec[i] - 1; return max;} /* Driver code */int main(){ int arr[] = {12, 4, 78, 90, 45, 23}; int n = sizeof(arr)/sizeof(arr[0]); cout << "nLength of max length Bitonic Subarray is " << bitonic(arr, n); return 0;} // This is code is contributed by rathbhupendra // C program to find length of the longest bitonic subarray#include<stdio.h>#include<stdlib.h> int bitonic(int arr[], int n){ int inc[n]; // Length of increasing subarray ending at all indexes int dec[n]; // Length of decreasing subarray starting at all indexes int i, max; // length of increasing sequence ending at first index is 1 inc[0] = 1; // length of increasing sequence starting at first index is 1 dec[n-1] = 1; // Step 1) Construct increasing sequence array for (i = 1; i < n; i++) inc[i] = (arr[i] >= arr[i-1])? inc[i-1] + 1: 1; // Step 2) Construct decreasing sequence array for (i = n-2; i >= 0; i--) dec[i] = (arr[i] >= arr[i+1])? dec[i+1] + 1: 1; // Step 3) Find the length of maximum length bitonic sequence max = inc[0] + dec[0] - 1; for (i = 1; i < n; i++) if (inc[i] + dec[i] - 1 > max) max = inc[i] + dec[i] - 1; return max;} /* Driver program to test above function */int main(){ int arr[] = {12, 4, 78, 90, 45, 23}; int n = sizeof(arr)/sizeof(arr[0]); printf("nLength of max length Bitonic Subarray is %d", bitonic(arr, n)); return 0;} // Java program to find length of the longest bitonic subarrayimport java.io.*;import java.util.*; class Bitonic{ static int bitonic(int arr[], int n) { int[] inc = new int[n]; // Length of increasing subarray ending // at all indexes int[] dec = new int[n]; // Length of decreasing subarray starting // at all indexes int max; // Length of increasing sequence ending at first index is 1 inc[0] = 1; // Length of increasing sequence starting at first index is 1 dec[n-1] = 1; // Step 1) Construct increasing sequence array for (int i = 1; i < n; i++) inc[i] = (arr[i] >= arr[i-1])? inc[i-1] + 1: 1; // Step 2) Construct decreasing sequence array for (int i = n-2; i >= 0; i--) dec[i] = (arr[i] >= arr[i+1])? dec[i+1] + 1: 1; // Step 3) Find the length of maximum length bitonic sequence max = inc[0] + dec[0] - 1; for (int i = 1; i < n; i++) if (inc[i] + dec[i] - 1 > max) max = inc[i] + dec[i] - 1; return max; } /*Driver function to check for above function*/ public static void main (String[] args) { int arr[] = {12, 4, 78, 90, 45, 23}; int n = arr.length; System.out.println("Length of max length Bitnoic Subarray is " + bitonic(arr, n)); }}/* This code is contributed by Devesh Agrawal */ # Python program to find length of the longest bitonic subarray def bitonic(arr, n): # Length of increasing subarray ending at all indexes inc = [None] * n # Length of decreasing subarray starting at all indexes dec = [None] * n # length of increasing sequence ending at first index is 1 inc[0] = 1 # length of increasing sequence starting at first index is 1 dec[n-1] = 1 # Step 1) Construct increasing sequence array for i in range(n): if arr[i] >= arr[i-1]: inc[i] = inc[i-1] + 1 else: inc[i] = 1 # Step 2) Construct decreasing sequence array for i in range(n-2,-1,-1): if arr[i] >= arr[i-1]: dec[i] = inc[i-1] + 1 else: dec[i] = 1 # Step 3) Find the length of maximum length bitonic sequence max = inc[0] + dec[0] - 1 for i in range(n): if inc[i] + dec[i] - 1 > max: max = inc[i] + dec[i] - 1 return max # Driver program to test above function arr = [12, 4, 78, 90, 45, 23]n = len(arr)print("nLength of max length Bitonic Subarray is ",bitonic(arr, n)) // C# program to find length of the// longest bitonic subarrayusing System; class GFG{ static int bitonic(int []arr, int n) { // Length of increasing subarray ending // at all indexes int[] inc = new int[n]; // Length of decreasing subarray starting // at all indexes int[] dec = new int[n]; int max; // Length of increasing sequence // ending at first index is 1 inc[0] = 1; // Length of increasing sequence // starting at first index is 1 dec[n - 1] = 1; // Step 1) Construct increasing sequence array for (int i = 1; i < n; i++) inc[i] = (arr[i] >= arr[i - 1]) ? inc[i - 1] + 1: 1; // Step 2) Construct decreasing sequence array for (int i = n - 2; i >= 0; i--) dec[i] = (arr[i] >= arr[i + 1]) ? dec[i + 1] + 1: 1; // Step 3) Find the length of maximum // length bitonic sequence max = inc[0] + dec[0] - 1; for (int i = 1; i < n; i++) if (inc[i] + dec[i] - 1 > max) max = inc[i] + dec[i] - 1; return max; } // Driver function public static void Main () { int []arr = {12, 4, 78, 90, 45, 23}; int n = arr.Length; Console.Write("Length of max length Bitonic Subarray is " + bitonic(arr, n)); }}// This code is contributed by Sam007 <?php// PHP program to find length of// the longest bitonic subarray function bitonic($arr, $n){ $i; $max; // length of increasing sequence // ending at first index is 1 $inc[0] = 1; // length of increasing sequence // starting at first index is 1 $dec[$n - 1] = 1; // Step 1) Construct increasing // sequence array for ($i = 1; $i < $n; $i++) $inc[$i] = ($arr[$i] >= $arr[$i - 1]) ? $inc[$i - 1] + 1: 1; // Step 2) Construct decreasing // sequence array for ($i = $n - 2; $i >= 0; $i--) $dec[$i] = ($arr[$i] >= $arr[$i + 1]) ? $dec[$i + 1] + 1: 1; // Step 3) Find the length of // maximum length bitonic sequence $max = $inc[0] + $dec[0] - 1; for ($i = 1; $i < $n; $i++) if ($inc[$i] + $dec[$i] - 1 > $max) $max = $inc[$i] + $dec[$i] - 1; return $max;} // Driver Code$arr = array(12, 4, 78, 90, 45, 23);$n = sizeof($arr);echo "Length of max length Bitonic " . "Subarray is ", bitonic($arr, $n); // This code is contributed by aj_36?> <script> // Javascript program to find length of the // longest bitonic subarray function bitonic(arr, n) { // Length of increasing subarray ending // at all indexes let inc = new Array(n); // Length of decreasing subarray starting // at all indexes let dec = new Array(n); let max; // Length of increasing sequence // ending at first index is 1 inc[0] = 1; // Length of increasing sequence // starting at first index is 1 dec[n - 1] = 1; // Step 1) Construct increasing sequence array for (let i = 1; i < n; i++) inc[i] = (arr[i] >= arr[i - 1]) ? inc[i - 1] + 1: 1; // Step 2) Construct decreasing sequence array for (let i = n - 2; i >= 0; i--) dec[i] = (arr[i] >= arr[i + 1]) ? dec[i + 1] + 1: 1; // Step 3) Find the length of maximum // length bitonic sequence max = inc[0] + dec[0] - 1; for (let i = 1; i < n; i++) if (inc[i] + dec[i] - 1 > max) max = inc[i] + dec[i] - 1; return max; } let arr = [12, 4, 78, 90, 45, 23]; let n = arr.length; document.write("Length of max length Bitonic Subarray is " + bitonic(arr, n)); </script> nLength of max length Bitonic Subarray is 5 Output : Chapters descriptions off, selected captions settings, opens captions settings dialog captions off, selected English This is a modal window. Beginning of dialog window. Escape will cancel and close the window. End of dialog window. Length of max length Bitnoic Subarray is 5 Time Complexity : O(n) Auxiliary Space : O(n) Maximum Length Bitonic Subarray | GeeksforGeeks - YouTubeGeeksforGeeks530K subscribersMaximum Length Bitonic Subarray | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 13:05•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=k4vMVTp6AuI" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> Maximum Length Bitonic Subarray | Set 2 (O(n) time and O(1) Space)As an exercise, extend the above implementation to print the longest bitonic subarray also. The above implementation only returns the length of such subarray. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. jit_t rathbhupendra ShubhamMaurya3 NishantChahar rameshtravel07 sweetyty rajeev0719singh amartyaghoshgfg Arrays Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n12 Jan, 2022" }, { "code": null, "e": 890, "s": 54, "text": "Given an array A[0 ... n-1] containing n positive integers, a subarray A[i ... j] is bitonic if there is a k with i <= k <= j such that A[i] <= A[i + 1] ... = A[k + 1] >= .. A[j – 1] > = A[j]. Write a function that takes an array as argument and returns the length of the maximum length bitonic subarray. Expected time complexity of the solution is O(n)Simple Examples 1) A[] = {12, 4, 78, 90, 45, 23}, the maximum length bitonic subarray is {4, 78, 90, 45, 23} which is of length 5.2) A[] = {20, 4, 1, 2, 3, 4, 2, 10}, the maximum length bitonic subarray is {1, 2, 3, 4, 2} which is of length 5.Extreme Examples 1) A[] = {10}, the single element is bitonic, so output is 1.2) A[] = {10, 20, 30, 40}, the complete array itself is bitonic, so output is 4.3) A[] = {40, 30, 20, 10}, the complete array itself is bitonic, so output is 4. " }, { "code": null, "e": 1572, "s": 890, "text": "Solution Let us consider the array {12, 4, 78, 90, 45, 23} to understand the solution. 1) Construct an auxiliary array inc[] from left to right such that inc[i] contains length of the nondecreasing subarray ending at arr[i]. For A[] = {12, 4, 78, 90, 45, 23}, inc[] is {1, 1, 2, 3, 1, 1} 2) Construct another array dec[] from right to left such that dec[i] contains length of nonincreasing subarray starting at arr[i]. For A[] = {12, 4, 78, 90, 45, 23}, dec[] is {2, 1, 1, 3, 2, 1}.3) Once we have the inc[] and dec[] arrays, all we need to do is find the maximum value of (inc[i] + dec[i] – 1). For {12, 4, 78, 90, 45, 23}, the max value of (inc[i] + dec[i] – 1) is 5 for i = 3. " }, { "code": null, "e": 1576, "s": 1572, "text": "C++" }, { "code": null, "e": 1578, "s": 1576, "text": "C" }, { "code": null, "e": 1583, "s": 1578, "text": "Java" }, { "code": null, "e": 1591, "s": 1583, "text": "Python3" }, { "code": null, "e": 1594, "s": 1591, "text": "C#" }, { "code": null, "e": 1598, "s": 1594, "text": "PHP" }, { "code": null, "e": 1609, "s": 1598, "text": "Javascript" }, { "code": "// C++ program to find length of// the longest bitonic subarray#include <bits/stdc++.h>using namespace std; int bitonic(int arr[], int n){ // Length of increasing subarray // ending at all indexes int inc[n]; // Length of decreasing subarray // starting at all indexes int dec[n]; int i, max; // length of increasing sequence // ending at first index is 1 inc[0] = 1; // length of increasing sequence // starting at first index is 1 dec[n-1] = 1; // Step 1) Construct increasing sequence array for (i = 1; i < n; i++) inc[i] = (arr[i] >= arr[i-1])? inc[i-1] + 1: 1; // Step 2) Construct decreasing sequence array for (i = n-2; i >= 0; i--) dec[i] = (arr[i] >= arr[i+1])? dec[i+1] + 1: 1; // Step 3) Find the length of // maximum length bitonic sequence max = inc[0] + dec[0] - 1; for (i = 1; i < n; i++) if (inc[i] + dec[i] - 1 > max) max = inc[i] + dec[i] - 1; return max;} /* Driver code */int main(){ int arr[] = {12, 4, 78, 90, 45, 23}; int n = sizeof(arr)/sizeof(arr[0]); cout << \"nLength of max length Bitonic Subarray is \" << bitonic(arr, n); return 0;} // This is code is contributed by rathbhupendra", "e": 2831, "s": 1609, "text": null }, { "code": "// C program to find length of the longest bitonic subarray#include<stdio.h>#include<stdlib.h> int bitonic(int arr[], int n){ int inc[n]; // Length of increasing subarray ending at all indexes int dec[n]; // Length of decreasing subarray starting at all indexes int i, max; // length of increasing sequence ending at first index is 1 inc[0] = 1; // length of increasing sequence starting at first index is 1 dec[n-1] = 1; // Step 1) Construct increasing sequence array for (i = 1; i < n; i++) inc[i] = (arr[i] >= arr[i-1])? inc[i-1] + 1: 1; // Step 2) Construct decreasing sequence array for (i = n-2; i >= 0; i--) dec[i] = (arr[i] >= arr[i+1])? dec[i+1] + 1: 1; // Step 3) Find the length of maximum length bitonic sequence max = inc[0] + dec[0] - 1; for (i = 1; i < n; i++) if (inc[i] + dec[i] - 1 > max) max = inc[i] + dec[i] - 1; return max;} /* Driver program to test above function */int main(){ int arr[] = {12, 4, 78, 90, 45, 23}; int n = sizeof(arr)/sizeof(arr[0]); printf(\"nLength of max length Bitonic Subarray is %d\", bitonic(arr, n)); return 0;}", "e": 3994, "s": 2831, "text": null }, { "code": "// Java program to find length of the longest bitonic subarrayimport java.io.*;import java.util.*; class Bitonic{ static int bitonic(int arr[], int n) { int[] inc = new int[n]; // Length of increasing subarray ending // at all indexes int[] dec = new int[n]; // Length of decreasing subarray starting // at all indexes int max; // Length of increasing sequence ending at first index is 1 inc[0] = 1; // Length of increasing sequence starting at first index is 1 dec[n-1] = 1; // Step 1) Construct increasing sequence array for (int i = 1; i < n; i++) inc[i] = (arr[i] >= arr[i-1])? inc[i-1] + 1: 1; // Step 2) Construct decreasing sequence array for (int i = n-2; i >= 0; i--) dec[i] = (arr[i] >= arr[i+1])? dec[i+1] + 1: 1; // Step 3) Find the length of maximum length bitonic sequence max = inc[0] + dec[0] - 1; for (int i = 1; i < n; i++) if (inc[i] + dec[i] - 1 > max) max = inc[i] + dec[i] - 1; return max; } /*Driver function to check for above function*/ public static void main (String[] args) { int arr[] = {12, 4, 78, 90, 45, 23}; int n = arr.length; System.out.println(\"Length of max length Bitnoic Subarray is \" + bitonic(arr, n)); }}/* This code is contributed by Devesh Agrawal */", "e": 5479, "s": 3994, "text": null }, { "code": "# Python program to find length of the longest bitonic subarray def bitonic(arr, n): # Length of increasing subarray ending at all indexes inc = [None] * n # Length of decreasing subarray starting at all indexes dec = [None] * n # length of increasing sequence ending at first index is 1 inc[0] = 1 # length of increasing sequence starting at first index is 1 dec[n-1] = 1 # Step 1) Construct increasing sequence array for i in range(n): if arr[i] >= arr[i-1]: inc[i] = inc[i-1] + 1 else: inc[i] = 1 # Step 2) Construct decreasing sequence array for i in range(n-2,-1,-1): if arr[i] >= arr[i-1]: dec[i] = inc[i-1] + 1 else: dec[i] = 1 # Step 3) Find the length of maximum length bitonic sequence max = inc[0] + dec[0] - 1 for i in range(n): if inc[i] + dec[i] - 1 > max: max = inc[i] + dec[i] - 1 return max # Driver program to test above function arr = [12, 4, 78, 90, 45, 23]n = len(arr)print(\"nLength of max length Bitonic Subarray is \",bitonic(arr, n))", "e": 6598, "s": 5479, "text": null }, { "code": "// C# program to find length of the// longest bitonic subarrayusing System; class GFG{ static int bitonic(int []arr, int n) { // Length of increasing subarray ending // at all indexes int[] inc = new int[n]; // Length of decreasing subarray starting // at all indexes int[] dec = new int[n]; int max; // Length of increasing sequence // ending at first index is 1 inc[0] = 1; // Length of increasing sequence // starting at first index is 1 dec[n - 1] = 1; // Step 1) Construct increasing sequence array for (int i = 1; i < n; i++) inc[i] = (arr[i] >= arr[i - 1]) ? inc[i - 1] + 1: 1; // Step 2) Construct decreasing sequence array for (int i = n - 2; i >= 0; i--) dec[i] = (arr[i] >= arr[i + 1]) ? dec[i + 1] + 1: 1; // Step 3) Find the length of maximum // length bitonic sequence max = inc[0] + dec[0] - 1; for (int i = 1; i < n; i++) if (inc[i] + dec[i] - 1 > max) max = inc[i] + dec[i] - 1; return max; } // Driver function public static void Main () { int []arr = {12, 4, 78, 90, 45, 23}; int n = arr.Length; Console.Write(\"Length of max length Bitonic Subarray is \" + bitonic(arr, n)); }}// This code is contributed by Sam007", "e": 8053, "s": 6598, "text": null }, { "code": "<?php// PHP program to find length of// the longest bitonic subarray function bitonic($arr, $n){ $i; $max; // length of increasing sequence // ending at first index is 1 $inc[0] = 1; // length of increasing sequence // starting at first index is 1 $dec[$n - 1] = 1; // Step 1) Construct increasing // sequence array for ($i = 1; $i < $n; $i++) $inc[$i] = ($arr[$i] >= $arr[$i - 1]) ? $inc[$i - 1] + 1: 1; // Step 2) Construct decreasing // sequence array for ($i = $n - 2; $i >= 0; $i--) $dec[$i] = ($arr[$i] >= $arr[$i + 1]) ? $dec[$i + 1] + 1: 1; // Step 3) Find the length of // maximum length bitonic sequence $max = $inc[0] + $dec[0] - 1; for ($i = 1; $i < $n; $i++) if ($inc[$i] + $dec[$i] - 1 > $max) $max = $inc[$i] + $dec[$i] - 1; return $max;} // Driver Code$arr = array(12, 4, 78, 90, 45, 23);$n = sizeof($arr);echo \"Length of max length Bitonic \" . \"Subarray is \", bitonic($arr, $n); // This code is contributed by aj_36?>", "e": 9129, "s": 8053, "text": null }, { "code": "<script> // Javascript program to find length of the // longest bitonic subarray function bitonic(arr, n) { // Length of increasing subarray ending // at all indexes let inc = new Array(n); // Length of decreasing subarray starting // at all indexes let dec = new Array(n); let max; // Length of increasing sequence // ending at first index is 1 inc[0] = 1; // Length of increasing sequence // starting at first index is 1 dec[n - 1] = 1; // Step 1) Construct increasing sequence array for (let i = 1; i < n; i++) inc[i] = (arr[i] >= arr[i - 1]) ? inc[i - 1] + 1: 1; // Step 2) Construct decreasing sequence array for (let i = n - 2; i >= 0; i--) dec[i] = (arr[i] >= arr[i + 1]) ? dec[i + 1] + 1: 1; // Step 3) Find the length of maximum // length bitonic sequence max = inc[0] + dec[0] - 1; for (let i = 1; i < n; i++) if (inc[i] + dec[i] - 1 > max) max = inc[i] + dec[i] - 1; return max; } let arr = [12, 4, 78, 90, 45, 23]; let n = arr.length; document.write(\"Length of max length Bitonic Subarray is \" + bitonic(arr, n)); </script>", "e": 10464, "s": 9129, "text": null }, { "code": null, "e": 10508, "s": 10464, "text": "nLength of max length Bitonic Subarray is 5" }, { "code": null, "e": 10519, "s": 10508, "text": "Output : " }, { "code": null, "e": 10528, "s": 10519, "text": "Chapters" }, { "code": null, "e": 10555, "s": 10528, "text": "descriptions off, selected" }, { "code": null, "e": 10605, "s": 10555, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 10628, "s": 10605, "text": "captions off, selected" }, { "code": null, "e": 10636, "s": 10628, "text": "English" }, { "code": null, "e": 10660, "s": 10636, "text": "This is a modal window." }, { "code": null, "e": 10729, "s": 10660, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 10751, "s": 10729, "text": "End of dialog window." }, { "code": null, "e": 10794, "s": 10751, "text": "Length of max length Bitnoic Subarray is 5" }, { "code": null, "e": 10841, "s": 10794, "text": "Time Complexity : O(n) Auxiliary Space : O(n) " }, { "code": null, "e": 11722, "s": 10841, "text": "Maximum Length Bitonic Subarray | GeeksforGeeks - YouTubeGeeksforGeeks530K subscribersMaximum Length Bitonic Subarray | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 13:05•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=k4vMVTp6AuI\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 12073, "s": 11722, "text": "Maximum Length Bitonic Subarray | Set 2 (O(n) time and O(1) Space)As an exercise, extend the above implementation to print the longest bitonic subarray also. The above implementation only returns the length of such subarray. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 12079, "s": 12073, "text": "jit_t" }, { "code": null, "e": 12093, "s": 12079, "text": "rathbhupendra" }, { "code": null, "e": 12108, "s": 12093, "text": "ShubhamMaurya3" }, { "code": null, "e": 12122, "s": 12108, "text": "NishantChahar" }, { "code": null, "e": 12137, "s": 12122, "text": "rameshtravel07" }, { "code": null, "e": 12146, "s": 12137, "text": "sweetyty" }, { "code": null, "e": 12162, "s": 12146, "text": "rajeev0719singh" }, { "code": null, "e": 12178, "s": 12162, "text": "amartyaghoshgfg" }, { "code": null, "e": 12185, "s": 12178, "text": "Arrays" }, { "code": null, "e": 12192, "s": 12185, "text": "Arrays" } ]
Password encryption in Node.js using bcryptjs module
18 Oct, 2021 While submitting a form, there are some sensitive data (like passwords) that must not be visible to anyone, not even to the database admin. To avoid the sensitive data being visible from anyone, Node.js uses “bcryptjs”. This module enables storing of passwords as hashed passwords instead of plaintext. Installation of bcryptjs module: You can visit the link to Install bcryptjs module. You can install this package by using this command. npm install bcryptjs After installing bcryptjs module you can check your request version in the command prompt using the command. npm version bcryptjs After that, you can 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 index.js // Requiring moduleconst bcrypt = require('bcryptjs'); const password = 'pass123';var hashedPassword; // Encryption of the string passwordbcrypt.genSalt(10, function (err, Salt) { // The bcrypt is used for encrypting password. bcrypt.hash(password, Salt, function (err, hash) { if (err) { return console.log('Cannot encrypt'); } hashedPassword = hash; console.log(hash); bcrypt.compare(password, hashedPassword, async function (err, isMatch) { // Comparing the original password to // encrypted password if (isMatch) { console.log('Encrypted password is: ', password); console.log('Decrypted password is: ', hashedPassword); } if (!isMatch) { // If password doesn't match the following // message will be sent console.log(hashedPassword + ' is not encryption of ' + password); } }) })}) Step to run the application: Run the application using the following command: node index.js Output: We will see the following output on the console screen. $2a$10$4DRBPlbjKO7WuL2ndpbisOheLfgVwDlngY7t18/ZZBFNcW3HdWFGmEncrypted password is: pass123Decrypted password is: $2a$10$4DRBPlbjKO7WuL2ndpbisOheLfgVwDlngY7t18/ZZBFNcW3HdWFGm NodeJS-Questions Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Installation of Node.js on Windows JWT Authentication with Node.js Difference between dependencies, devDependencies and peerDependencies Mongoose Populate() Method Mongoose find() Function 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": "\n18 Oct, 2021" }, { "code": null, "e": 248, "s": 28, "text": "While submitting a form, there are some sensitive data (like passwords) that must not be visible to anyone, not even to the database admin. To avoid the sensitive data being visible from anyone, Node.js uses “bcryptjs”." }, { "code": null, "e": 331, "s": 248, "text": "This module enables storing of passwords as hashed passwords instead of plaintext." }, { "code": null, "e": 364, "s": 331, "text": "Installation of bcryptjs module:" }, { "code": null, "e": 467, "s": 364, "text": "You can visit the link to Install bcryptjs module. You can install this package by using this command." }, { "code": null, "e": 488, "s": 467, "text": "npm install bcryptjs" }, { "code": null, "e": 597, "s": 488, "text": "After installing bcryptjs module you can check your request version in the command prompt using the command." }, { "code": null, "e": 618, "s": 597, "text": "npm version bcryptjs" }, { "code": null, "e": 747, "s": 618, "text": "After that, you can create a folder and add a file for example index.js, To run this file you need to run the following command." }, { "code": null, "e": 761, "s": 747, "text": "node index.js" }, { "code": null, "e": 770, "s": 761, "text": "index.js" }, { "code": "// Requiring moduleconst bcrypt = require('bcryptjs'); const password = 'pass123';var hashedPassword; // Encryption of the string passwordbcrypt.genSalt(10, function (err, Salt) { // The bcrypt is used for encrypting password. bcrypt.hash(password, Salt, function (err, hash) { if (err) { return console.log('Cannot encrypt'); } hashedPassword = hash; console.log(hash); bcrypt.compare(password, hashedPassword, async function (err, isMatch) { // Comparing the original password to // encrypted password if (isMatch) { console.log('Encrypted password is: ', password); console.log('Decrypted password is: ', hashedPassword); } if (!isMatch) { // If password doesn't match the following // message will be sent console.log(hashedPassword + ' is not encryption of ' + password); } }) })})", "e": 1819, "s": 770, "text": null }, { "code": null, "e": 1897, "s": 1819, "text": "Step to run the application: Run the application using the following command:" }, { "code": null, "e": 1911, "s": 1897, "text": "node index.js" }, { "code": null, "e": 1975, "s": 1911, "text": "Output: We will see the following output on the console screen." }, { "code": null, "e": 2149, "s": 1975, "text": "$2a$10$4DRBPlbjKO7WuL2ndpbisOheLfgVwDlngY7t18/ZZBFNcW3HdWFGmEncrypted password is: pass123Decrypted password is: $2a$10$4DRBPlbjKO7WuL2ndpbisOheLfgVwDlngY7t18/ZZBFNcW3HdWFGm" }, { "code": null, "e": 2166, "s": 2149, "text": "NodeJS-Questions" }, { "code": null, "e": 2174, "s": 2166, "text": "Node.js" }, { "code": null, "e": 2191, "s": 2174, "text": "Web Technologies" }, { "code": null, "e": 2289, "s": 2191, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2324, "s": 2289, "text": "Installation of Node.js on Windows" }, { "code": null, "e": 2356, "s": 2324, "text": "JWT Authentication with Node.js" }, { "code": null, "e": 2426, "s": 2356, "text": "Difference between dependencies, devDependencies and peerDependencies" }, { "code": null, "e": 2453, "s": 2426, "text": "Mongoose Populate() Method" }, { "code": null, "e": 2478, "s": 2453, "text": "Mongoose find() Function" }, { "code": null, "e": 2540, "s": 2478, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2601, "s": 2540, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2651, "s": 2601, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 2694, "s": 2651, "text": "How to fetch data from an API in ReactJS ?" } ]
WML | Introduction
02 Mar, 2020 WML stands for Wireless Markup Language (WML) which is based on HTML and HDML. It is specified as an XML document type. It is a markup language used to develop websites for mobile phones. While designing with WML, constraints of wireless devices such as small display screens, limited memory, low bandwidth of transmission and small resources have to be considered. WAP (Wireless Application Protocol) sites are different from normal HTML sites in the fact that they are monochromatic (only black and white), concise and has very small screen space, due to which content in the WAP sites will be only the significant matter, much like how telegraph used to work in the olden days. The concept WML follows is that of a deck and card metaphor. A WML document is thought of as made up of many cards. Just like how cards can be grouped to form a deck, a WAP site has many cards. One card will be displayed at a time on the screen, just like how one page is displayed at a time in an HTML website. Many cards can be inserted into a WML document, and the WML deck is identified by a URL. To access the deck, the user can navigate using the WML browser, which fetches the deck as required. Features of WML: Text and Images: WML gives a clue about how the text and images can be presented to the user. The final presentation depends upon the user. Pictures need to be in WBMP format and will be monochrome. User Interaction: WML supports different elements for input like password entry, option selector and text entry control. The user is free to choose inputs such as keys or voice. Navigation: WML offers hyperlink navigation and browsing history. Context Management: The state can be shared across different decks and can also be saved between different decks. Problems Faced by a Web Application When Used With a Mobile and Wireless Environment: 1. HTTP: Bandwidth and delay: HTTP is not made for low bandwidth and high delay connections in mind. HTTP protocol headers are large and redundant as HTTP is uncompressed and stateless. Caching: Caching is disabled by content providers as client companies cannot get feedback if a cache is placed between a server and a client. Users suffer from downloading the same content repeatedly from the server as HTTP is stateless. Posting: Sending some content from a client to a server will create additional problems if the said client is disconnected at that moment. 2. HTML: HTML was designed for use in creating content for webpages of the World Wide Web (www). It was meant only for desktop initially. Thus, when used in hand-held devices, some problems arise: Small display and low-resolution. Limited User Interfaces. Low-Performance CPU. Enhancements needed for use of HTML in wireless environments: Image scaling Content Transformation: Documents in PDF or PPS should be transformed into the plain text as PDF occupies more memory. Content Extraction: To avoid longer duration waits, some content like headlines can be extracted from the document and presented to the user. This lets the user decide which information alone needs to be downloaded. Enhancements needed for use of HTTP in wireless environments: Connection Re-use: Client and server can be used the same TCP (Transmission Control Protocol) connection for several requests and responses. Pipelining can be used to improve performance. Caching Enhancements: A cache could store cacheable response to reduce response time and bandwidth for further responses. Caching can be done in the mobile client’s web browser itself by using a client proxy. A network proxy can also be used on the network side. Bandwidth Optimization: HTTP supports compression and also negotiates the compression parameters and compression styles. This will allow partial transmissions. WMLScript: WMLScript is the client-side scripting language of WML in Wireless Application Protocol(WAP) and whose content is static. It is similar to JavaScript. It is optimized for low power devices and is a compiled language. Some of the standard libraries of WMLScript are Lang, Float, String, URL, WML Browser, Dialog, and WMLScript Crypto Library. Declaring A WML Document and Cards: To create a WML document, type it in notepad, just like for HTML. The first line should be something like this: <?xml version="1.0"?> <!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.1//EN" "http://www.wapforum.org/DTD/wml_1.1.xml"> <wml> <card id="index" title="My WAP Site Using WML" newcontext="true"> </card> </wml> Which tells the phone that it is going to interpret a WML document and the WML standards. A card with the ID contents (used for linking) will be generated and the output at the top of the screen will be. It is extremely important to close all WML tags, unlike HTML tags. If you do not close a WML tag, a card will not open at all. You have to close both the <card> and <wml> tags. Example: The code below shows a sample WML coding for a small WAP site with two cards and a link to an external website. <?xml version="1.0"?> <!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.2//EN""-//WAPFORUM//DTD WML 1.1//EN" "http://www.wapforum.org/DTD/wml_1.1.xml"> <wml> <!-- This is first card--> <card id="one" title="First Card"> <h1> Geeksforgeeks </h1> <p> A Computer Science Portal for Geeks </p> </card> <!-- This is second card--> <card id="two" title="Second Card"> <p> This is created by WML </p> </card> </wml> Output: Comparison of WML with HTML: WML is used only for WAP sites on mobile phones and can be hosted only be WAP hosts that support WML. HTML can be hosted by any web server. WML sites are monochrome, unlike HTML sites. Coding is similar in many aspects but a badly coded WAP site will definitely not run as compared to a badly coded HTML site. It is must to close all WML tags as compared to the more lenient HTML coding. There are no alignment tags like the <center> tag in WML, as in HTML. Instead, <p align=”center”> has to be used for aligning text in WML. There are problems when using old HTML tags like <br> which have no closing tag. To get around this in WML, some tags have a “/” put on the end like <br />. Only WBMP format monochrome images are supported in WML whereas there is no such restriction in HTML. HTML-Misc WML HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? REST API (Introduction) CSS to put icon inside an input element in a form Types of CSS (Cascading Style Sheet) Design a Tribute Page using HTML & CSS Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array
[ { "code": null, "e": 28, "s": 0, "text": "\n02 Mar, 2020" }, { "code": null, "e": 1211, "s": 28, "text": "WML stands for Wireless Markup Language (WML) which is based on HTML and HDML. It is specified as an XML document type. It is a markup language used to develop websites for mobile phones. While designing with WML, constraints of wireless devices such as small display screens, limited memory, low bandwidth of transmission and small resources have to be considered. WAP (Wireless Application Protocol) sites are different from normal HTML sites in the fact that they are monochromatic (only black and white), concise and has very small screen space, due to which content in the WAP sites will be only the significant matter, much like how telegraph used to work in the olden days. The concept WML follows is that of a deck and card metaphor. A WML document is thought of as made up of many cards. Just like how cards can be grouped to form a deck, a WAP site has many cards. One card will be displayed at a time on the screen, just like how one page is displayed at a time in an HTML website. Many cards can be inserted into a WML document, and the WML deck is identified by a URL. To access the deck, the user can navigate using the WML browser, which fetches the deck as required." }, { "code": null, "e": 1228, "s": 1211, "text": "Features of WML:" }, { "code": null, "e": 1427, "s": 1228, "text": "Text and Images: WML gives a clue about how the text and images can be presented to the user. The final presentation depends upon the user. Pictures need to be in WBMP format and will be monochrome." }, { "code": null, "e": 1605, "s": 1427, "text": "User Interaction: WML supports different elements for input like password entry, option selector and text entry control. The user is free to choose inputs such as keys or voice." }, { "code": null, "e": 1671, "s": 1605, "text": "Navigation: WML offers hyperlink navigation and browsing history." }, { "code": null, "e": 1785, "s": 1671, "text": "Context Management: The state can be shared across different decks and can also be saved between different decks." }, { "code": null, "e": 1871, "s": 1785, "text": "Problems Faced by a Web Application When Used With a Mobile and Wireless Environment:" }, { "code": null, "e": 1880, "s": 1871, "text": "1. HTTP:" }, { "code": null, "e": 2057, "s": 1880, "text": "Bandwidth and delay: HTTP is not made for low bandwidth and high delay connections in mind. HTTP protocol headers are large and redundant as HTTP is uncompressed and stateless." }, { "code": null, "e": 2295, "s": 2057, "text": "Caching: Caching is disabled by content providers as client companies cannot get feedback if a cache is placed between a server and a client. Users suffer from downloading the same content repeatedly from the server as HTTP is stateless." }, { "code": null, "e": 2434, "s": 2295, "text": "Posting: Sending some content from a client to a server will create additional problems if the said client is disconnected at that moment." }, { "code": null, "e": 2631, "s": 2434, "text": "2. HTML: HTML was designed for use in creating content for webpages of the World Wide Web (www). It was meant only for desktop initially. Thus, when used in hand-held devices, some problems arise:" }, { "code": null, "e": 2665, "s": 2631, "text": "Small display and low-resolution." }, { "code": null, "e": 2690, "s": 2665, "text": "Limited User Interfaces." }, { "code": null, "e": 2711, "s": 2690, "text": "Low-Performance CPU." }, { "code": null, "e": 2773, "s": 2711, "text": "Enhancements needed for use of HTML in wireless environments:" }, { "code": null, "e": 2787, "s": 2773, "text": "Image scaling" }, { "code": null, "e": 2906, "s": 2787, "text": "Content Transformation: Documents in PDF or PPS should be transformed into the plain text as PDF occupies more memory." }, { "code": null, "e": 3122, "s": 2906, "text": "Content Extraction: To avoid longer duration waits, some content like headlines can be extracted from the document and presented to the user. This lets the user decide which information alone needs to be downloaded." }, { "code": null, "e": 3184, "s": 3122, "text": "Enhancements needed for use of HTTP in wireless environments:" }, { "code": null, "e": 3372, "s": 3184, "text": "Connection Re-use: Client and server can be used the same TCP (Transmission Control Protocol) connection for several requests and responses. Pipelining can be used to improve performance." }, { "code": null, "e": 3635, "s": 3372, "text": "Caching Enhancements: A cache could store cacheable response to reduce response time and bandwidth for further responses. Caching can be done in the mobile client’s web browser itself by using a client proxy. A network proxy can also be used on the network side." }, { "code": null, "e": 3795, "s": 3635, "text": "Bandwidth Optimization: HTTP supports compression and also negotiates the compression parameters and compression styles. This will allow partial transmissions." }, { "code": null, "e": 4148, "s": 3795, "text": "WMLScript: WMLScript is the client-side scripting language of WML in Wireless Application Protocol(WAP) and whose content is static. It is similar to JavaScript. It is optimized for low power devices and is a compiled language. Some of the standard libraries of WMLScript are Lang, Float, String, URL, WML Browser, Dialog, and WMLScript Crypto Library." }, { "code": null, "e": 4296, "s": 4148, "text": "Declaring A WML Document and Cards: To create a WML document, type it in notepad, just like for HTML. The first line should be something like this:" }, { "code": "<?xml version=\"1.0\"?> <!DOCTYPE wml PUBLIC \"-//WAPFORUM//DTD WML 1.1//EN\" \"http://www.wapforum.org/DTD/wml_1.1.xml\"> <wml> <card id=\"index\" title=\"My WAP Site Using WML\" newcontext=\"true\"> </card> </wml>", "e": 4551, "s": 4296, "text": null }, { "code": null, "e": 4932, "s": 4551, "text": "Which tells the phone that it is going to interpret a WML document and the WML standards. A card with the ID contents (used for linking) will be generated and the output at the top of the screen will be. It is extremely important to close all WML tags, unlike HTML tags. If you do not close a WML tag, a card will not open at all. You have to close both the <card> and <wml> tags." }, { "code": null, "e": 5053, "s": 4932, "text": "Example: The code below shows a sample WML coding for a small WAP site with two cards and a link to an external website." }, { "code": "<?xml version=\"1.0\"?> <!DOCTYPE wml PUBLIC \"-//WAPFORUM//DTD WML 1.2//EN\"\"-//WAPFORUM//DTD WML 1.1//EN\" \"http://www.wapforum.org/DTD/wml_1.1.xml\"> <wml> <!-- This is first card--> <card id=\"one\" title=\"First Card\"> <h1> Geeksforgeeks </h1> <p> A Computer Science Portal for Geeks </p> </card> <!-- This is second card--> <card id=\"two\" title=\"Second Card\"> <p> This is created by WML </p> </card> </wml>", "e": 5614, "s": 5053, "text": null }, { "code": null, "e": 5622, "s": 5614, "text": "Output:" }, { "code": null, "e": 5651, "s": 5622, "text": "Comparison of WML with HTML:" }, { "code": null, "e": 5791, "s": 5651, "text": "WML is used only for WAP sites on mobile phones and can be hosted only be WAP hosts that support WML. HTML can be hosted by any web server." }, { "code": null, "e": 5836, "s": 5791, "text": "WML sites are monochrome, unlike HTML sites." }, { "code": null, "e": 5961, "s": 5836, "text": "Coding is similar in many aspects but a badly coded WAP site will definitely not run as compared to a badly coded HTML site." }, { "code": null, "e": 6039, "s": 5961, "text": "It is must to close all WML tags as compared to the more lenient HTML coding." }, { "code": null, "e": 6178, "s": 6039, "text": "There are no alignment tags like the <center> tag in WML, as in HTML. Instead, <p align=”center”> has to be used for aligning text in WML." }, { "code": null, "e": 6335, "s": 6178, "text": "There are problems when using old HTML tags like <br> which have no closing tag. To get around this in WML, some tags have a “/” put on the end like <br />." }, { "code": null, "e": 6437, "s": 6335, "text": "Only WBMP format monochrome images are supported in WML whereas there is no such restriction in HTML." }, { "code": null, "e": 6447, "s": 6437, "text": "HTML-Misc" }, { "code": null, "e": 6451, "s": 6447, "text": "WML" }, { "code": null, "e": 6456, "s": 6451, "text": "HTML" }, { "code": null, "e": 6473, "s": 6456, "text": "Web Technologies" }, { "code": null, "e": 6478, "s": 6473, "text": "HTML" }, { "code": null, "e": 6576, "s": 6478, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6624, "s": 6576, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 6648, "s": 6624, "text": "REST API (Introduction)" }, { "code": null, "e": 6698, "s": 6648, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 6735, "s": 6698, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 6774, "s": 6735, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 6807, "s": 6774, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 6868, "s": 6807, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 6911, "s": 6868, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 6983, "s": 6911, "text": "Differences between Functional Components and Class Components in React" } ]
Program to print the Diagonals of a Matrix
20 Apr, 2021 Given a 2D square matrix, print the Principal and Secondary diagonals. Examples : Input: 4 1 2 3 4 4 3 2 1 7 8 9 6 6 5 4 3 Output: Principal Diagonal: 1, 3, 9, 3 Secondary Diagonal: 4, 2, 8, 6 Input: 3 1 1 1 1 1 1 1 1 1 Output: Principal Diagonal: 1, 1, 1 Secondary Diagonal: 1, 1, 1 For example, consider the following 4 X 4 input matrix. A00 A01 A02 A03 A10 A11 A12 A13 A20 A21 A22 A23 A30 A31 A32 A33 The primary diagonal is formed by the elements A00, A11, A22, A33.Condition for Principal Diagonal: The row-column condition is row = column. The secondary diagonal is formed by the elements A03, A12, A21, A30. Condition for Secondary Diagonal: The row-column condition is row = numberOfRows - column -1. Method 1: In this method, we use two loops i.e. a loop for columns and a loop for rows and in the inner loop we check for the condition stated above. C++ Java Python3 C# Javascript // C++ Program to print the Diagonals of a Matrix #include <bits/stdc++.h>using namespace std; const int MAX = 100; // Function to print the Principal Diagonalvoid printPrincipalDiagonal(int mat[][MAX], int n){ cout << "Principal Diagonal: "; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // Condition for principal diagonal if (i == j) cout << mat[i][j] << ", "; } } cout << endl;} // Function to print the Secondary Diagonalvoid printSecondaryDiagonal(int mat[][MAX], int n){ cout << "Secondary Diagonal: "; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // Condition for secondary diagonal if ((i + j) == (n - 1)) cout << mat[i][j] << ", "; } } cout << endl;} // Driver codeint main(){ int n = 4; int a[][MAX] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 1, 2, 3, 4 }, { 5, 6, 7, 8 } }; printPrincipalDiagonal(a, n); printSecondaryDiagonal(a, n); return 0;} // Java Program to print the Diagonals of a Matrixclass GFG { static int MAX = 100; // Function to print the Principal Diagonal static void printPrincipalDiagonal(int mat[][], int n) { System.out.print("Principal Diagonal: "); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // Condition for principal diagonal if (i == j) { System.out.print(mat[i][j] + ", "); } } } System.out.println(""); } // Function to print the Secondary Diagonal static void printSecondaryDiagonal(int mat[][], int n) { System.out.print("Secondary Diagonal: "); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // Condition for secondary diagonal if ((i + j) == (n - 1)) { System.out.print(mat[i][j] + ", "); } } } System.out.println(""); } // Driver code public static void main(String args[]) { int n = 4; int a[][] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 1, 2, 3, 4 }, { 5, 6, 7, 8 } }; printPrincipalDiagonal(a, n); printSecondaryDiagonal(a, n); }} // This code is contributed by Rajput-Ji # Python3 Program to print the Diagonals of a MatrixMAX = 100 # Function to print the Principal Diagonaldef printPrincipalDiagonal(mat, n): print("Principal Diagonal: ", end = "") for i in range(n): for j in range(n): # Condition for principal diagonal if (i == j): print(mat[i][j], end = ", ") print() # Function to print the Secondary Diagonaldef printSecondaryDiagonal(mat, n): print("Secondary Diagonal: ", end = "") for i in range(n): for j in range(n): # Condition for secondary diagonal if ((i + j) == (n - 1)): print(mat[i][j], end = ", ") print() # Driver coden = 4a = [[ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ]] printPrincipalDiagonal(a, n)printSecondaryDiagonal(a, n) # This code is contributed by Mohit Kumar // C# Program to print the Diagonals of a Matrixusing System; class GFG { static int MAX = 100; // Function to print the Principal Diagonal static void printPrincipalDiagonal(int[, ] mat, int n) { Console.Write("Principal Diagonal: "); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // Condition for principal diagonal if (i == j) { Console.Write(mat[i, j] + ", "); } } } Console.WriteLine(""); } // Function to print the Secondary Diagonal static void printSecondaryDiagonal(int[, ] mat, int n) { Console.Write("Secondary Diagonal: "); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // Condition for secondary diagonal if ((i + j) == (n - 1)) { Console.Write(mat[i, j] + ", "); } } } Console.WriteLine(""); } // Driver code public static void Main(String[] args) { int n = 4; int[, ] a = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 1, 2, 3, 4 }, { 5, 6, 7, 8 } }; printPrincipalDiagonal(a, n); printSecondaryDiagonal(a, n); }} // This code is contributed by 29AjayKumar <script> // Javascript Program to print the Diagonals of a Matrix let MAX = 100; // Function to print the Principal Diagonal function printPrincipalDiagonal(mat, n) { document.write("Principal Diagonal: "); for (let i = 0; i < n; i++) { for (let j = 0; j < n; j++) { // Condition for principal diagonal if (i == j) { document.write(mat[i][j] + ", "); } } } document.write("</br>"); } // Function to print the Secondary Diagonal function printSecondaryDiagonal(mat, n) { document.write("Secondary Diagonal: "); for (let i = 0; i < n; i++) { for (let j = 0; j < n; j++) { // Condition for secondary diagonal if ((i + j) == (n - 1)) { document.write(mat[i][j] + ", "); } } } document.write("</br>"); } let n = 4; let a = [ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ] ]; printPrincipalDiagonal(a, n); printSecondaryDiagonal(a, n); </script> Principal Diagonal: 1, 6, 3, 8, Secondary Diagonal: 4, 7, 2, 5, Complexity Analysis: Time Complexity: O(n2). As there is a nested loop involved so the time complexity is squared. Auxiliary Space: O(1). As no extra space is occupied. Method 2: In this method, the same condition for printing the diagonal elements can be achieved using a single for loop. Approach: For Principal Diagonal elements: Run a for a loop until n, where n is the number of columns, and print array[i][i] where i is the index variable.For Secondary Diagonal elements: Run a for a loop until n, where n is the number of columns and print array[i][k] where i is the index variable and k = array_length – 1. Decrease k until i < n. For Principal Diagonal elements: Run a for a loop until n, where n is the number of columns, and print array[i][i] where i is the index variable. For Secondary Diagonal elements: Run a for a loop until n, where n is the number of columns and print array[i][k] where i is the index variable and k = array_length – 1. Decrease k until i < n. Below is the implementation of the above approach. C++ Java Python3 C# Javascript // C++ Program to print the Diagonals of a Matrix #include <bits/stdc++.h>using namespace std; const int MAX = 100; // Function to print the Principal Diagonalvoid printPrincipalDiagonal(int mat[][MAX], int n){ cout << "Principal Diagonal: "; for (int i = 0; i < n; i++) { // Printing principal diagonal cout << mat[i][i] << ", "; } cout << endl;} // Function to print the Secondary Diagonalvoid printSecondaryDiagonal(int mat[][MAX], int n){ cout << "Secondary Diagonal: "; int k = n - 1; for (int i = 0; i < n; i++) { // Printing secondary diagonal cout << mat[i][k--] << ", "; } cout << endl;} // Driver codeint main(){ int n = 4; int a[][MAX] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 1, 2, 3, 4 }, { 5, 6, 7, 8 } }; printPrincipalDiagonal(a, n); printSecondaryDiagonal(a, n); return 0;} // This code is contributed by yashbeersingh42 // Java Program to print the// Diagonals of a Matrixclass Main{ static int MAX = 100; // Function to print the Principal Diagonalpublic static void printPrincipalDiagonal(int mat[][], int n){ System.out.print("Principal Diagonal: "); for (int i = 0; i < n; i++) { // Printing principal diagonal System.out.print(mat[i][i] + ", "); } System.out.println();} // Function to print the Secondary Diagonalpublic static void printSecondaryDiagonal(int mat[][], int n){ System.out.print("Secondary Diagonal: "); int k = n - 1; for (int i = 0; i < n; i++) { // Printing secondary diagonal System.out.print(mat[i][k--] + ", "); } System.out.println();} public static void main(String[] args){ int n = 4; int a[][] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {1, 2, 3, 4}, {5, 6, 7, 8}}; printPrincipalDiagonal(a, n); printSecondaryDiagonal(a, n);}} // This code is contributed by divyeshrabadiya07 # Python3 program to print the# Diagonals of a MatrixMAX = 100 # Function to print the Principal Diagonaldef printPrincipalDiagonal(mat, n): print("Principal Diagonal: ", end = "") for i in range(n): # Printing principal diagonal print(mat[i][i], end = ", ") print() # Function to print the Secondary Diagonaldef printSecondaryDiagonal(mat, n): print("Secondary Diagonal: ", end = "") k = n - 1 for i in range(n): # Printing secondary diagonal print(mat[i][k], end = ", ") k -= 1 print() # Driver Coden = 4a = [ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ] ] printPrincipalDiagonal(a, n)printSecondaryDiagonal(a, n) # This code is contributed by divyesh072019 // C# program for the// above approachusing System;class GFG{ // Function to print the// Principal Diagonalstatic void printPrincipalDiagonal(int [,]mat, int n){ Console.Write("Principal Diagonal: "); for (int i = 0; i < n; i++) { // Printing principal diagonal Console.Write(mat[i, i] + ", "); } Console.Write("\n");} // Function to print the// Secondary Diagonalstatic void printSecondaryDiagonal(int [,]mat, int n){ Console.Write("Secondary Diagonal: "); int k = n - 1; for (int i = 0; i < n; i++) { // Printing secondary diagonal Console.Write(mat[i, k--] + ", "); } Console.Write("\n");} // Driver codestatic void Main(){ int n = 4; int [,]a = {{1, 2, 3, 4}, {5, 6, 7, 8}, {1, 2, 3, 4}, {5, 6, 7, 8}}; printPrincipalDiagonal(a, n); printSecondaryDiagonal(a, n);}} // This code is contributed by rutvik_56 <script> // Javascript Program to print the // Diagonals of a Matrix let MAX = 100; // Function to print the Principal Diagonal function printPrincipalDiagonal(mat, n) { document.write("Principal Diagonal: "); for (let i = 0; i < n; i++) { // Printing principal diagonal document.write(mat[i][i] + ", "); } document.write("</br>"); } // Function to print the Secondary Diagonal function printSecondaryDiagonal(mat, n) { document.write("Secondary Diagonal: "); let k = n - 1; for (let i = 0; i < n; i++) { // Printing secondary diagonal document.write(mat[i][k--] + ", "); } document.write("</br>"); } let n = 4; let a = [[1, 2, 3, 4], [5, 6, 7, 8], [1, 2, 3, 4], [5, 6, 7, 8]]; printPrincipalDiagonal(a, n); printSecondaryDiagonal(a, n); </script> Principal Diagonal: 1, 6, 3, 8, Secondary Diagonal: 4, 7, 2, 5, Complexity Analysis: Time Complexity: O(n). As there is only one loop involved so the time complexity is linear. Auxiliary Space: O(1). As no extra space is occupied. mohit kumar 29 Rajput-Ji 29AjayKumar yashbeersingh42 sumanmandal15135 Code_Mech rutvik_56 divyeshrabadiya07 divyesh072019 mukesh07 rameshtravel07 Matrix School Programming Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Sudoku | Backtracking-7 The Celebrity Problem Rotate a matrix by 90 degree in clockwise direction without using any extra space Maximum size rectangle binary sub-matrix with all 1s Inplace rotate square matrix by 90 degrees | Set 1 Python Dictionary Reverse a string in Java Arrays in C/C++ Introduction To PYTHON Interfaces in Java
[ { "code": null, "e": 52, "s": 24, "text": "\n20 Apr, 2021" }, { "code": null, "e": 124, "s": 52, "text": "Given a 2D square matrix, print the Principal and Secondary diagonals. " }, { "code": null, "e": 136, "s": 124, "text": "Examples : " }, { "code": null, "e": 340, "s": 136, "text": "Input: \n4\n1 2 3 4\n4 3 2 1\n7 8 9 6\n6 5 4 3\nOutput:\nPrincipal Diagonal: 1, 3, 9, 3\nSecondary Diagonal: 4, 2, 8, 6\n\nInput:\n3\n1 1 1\n1 1 1\n1 1 1\nOutput:\nPrincipal Diagonal: 1, 1, 1\nSecondary Diagonal: 1, 1, 1" }, { "code": null, "e": 397, "s": 340, "text": "For example, consider the following 4 X 4 input matrix. " }, { "code": null, "e": 461, "s": 397, "text": "A00 A01 A02 A03\nA10 A11 A12 A13\nA20 A21 A22 A23\nA30 A31 A32 A33" }, { "code": null, "e": 561, "s": 461, "text": "The primary diagonal is formed by the elements A00, A11, A22, A33.Condition for Principal Diagonal:" }, { "code": null, "e": 603, "s": 561, "text": "The row-column condition is row = column." }, { "code": null, "e": 706, "s": 603, "text": "The secondary diagonal is formed by the elements A03, A12, A21, A30. Condition for Secondary Diagonal:" }, { "code": null, "e": 766, "s": 706, "text": "The row-column condition is row = numberOfRows - column -1." }, { "code": null, "e": 916, "s": 766, "text": "Method 1: In this method, we use two loops i.e. a loop for columns and a loop for rows and in the inner loop we check for the condition stated above." }, { "code": null, "e": 920, "s": 916, "text": "C++" }, { "code": null, "e": 925, "s": 920, "text": "Java" }, { "code": null, "e": 933, "s": 925, "text": "Python3" }, { "code": null, "e": 936, "s": 933, "text": "C#" }, { "code": null, "e": 947, "s": 936, "text": "Javascript" }, { "code": "// C++ Program to print the Diagonals of a Matrix #include <bits/stdc++.h>using namespace std; const int MAX = 100; // Function to print the Principal Diagonalvoid printPrincipalDiagonal(int mat[][MAX], int n){ cout << \"Principal Diagonal: \"; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // Condition for principal diagonal if (i == j) cout << mat[i][j] << \", \"; } } cout << endl;} // Function to print the Secondary Diagonalvoid printSecondaryDiagonal(int mat[][MAX], int n){ cout << \"Secondary Diagonal: \"; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // Condition for secondary diagonal if ((i + j) == (n - 1)) cout << mat[i][j] << \", \"; } } cout << endl;} // Driver codeint main(){ int n = 4; int a[][MAX] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 1, 2, 3, 4 }, { 5, 6, 7, 8 } }; printPrincipalDiagonal(a, n); printSecondaryDiagonal(a, n); return 0;}", "e": 2034, "s": 947, "text": null }, { "code": "// Java Program to print the Diagonals of a Matrixclass GFG { static int MAX = 100; // Function to print the Principal Diagonal static void printPrincipalDiagonal(int mat[][], int n) { System.out.print(\"Principal Diagonal: \"); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // Condition for principal diagonal if (i == j) { System.out.print(mat[i][j] + \", \"); } } } System.out.println(\"\"); } // Function to print the Secondary Diagonal static void printSecondaryDiagonal(int mat[][], int n) { System.out.print(\"Secondary Diagonal: \"); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // Condition for secondary diagonal if ((i + j) == (n - 1)) { System.out.print(mat[i][j] + \", \"); } } } System.out.println(\"\"); } // Driver code public static void main(String args[]) { int n = 4; int a[][] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 1, 2, 3, 4 }, { 5, 6, 7, 8 } }; printPrincipalDiagonal(a, n); printSecondaryDiagonal(a, n); }} // This code is contributed by Rajput-Ji", "e": 3389, "s": 2034, "text": null }, { "code": "# Python3 Program to print the Diagonals of a MatrixMAX = 100 # Function to print the Principal Diagonaldef printPrincipalDiagonal(mat, n): print(\"Principal Diagonal: \", end = \"\") for i in range(n): for j in range(n): # Condition for principal diagonal if (i == j): print(mat[i][j], end = \", \") print() # Function to print the Secondary Diagonaldef printSecondaryDiagonal(mat, n): print(\"Secondary Diagonal: \", end = \"\") for i in range(n): for j in range(n): # Condition for secondary diagonal if ((i + j) == (n - 1)): print(mat[i][j], end = \", \") print() # Driver coden = 4a = [[ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ]] printPrincipalDiagonal(a, n)printSecondaryDiagonal(a, n) # This code is contributed by Mohit Kumar", "e": 4253, "s": 3389, "text": null }, { "code": "// C# Program to print the Diagonals of a Matrixusing System; class GFG { static int MAX = 100; // Function to print the Principal Diagonal static void printPrincipalDiagonal(int[, ] mat, int n) { Console.Write(\"Principal Diagonal: \"); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // Condition for principal diagonal if (i == j) { Console.Write(mat[i, j] + \", \"); } } } Console.WriteLine(\"\"); } // Function to print the Secondary Diagonal static void printSecondaryDiagonal(int[, ] mat, int n) { Console.Write(\"Secondary Diagonal: \"); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // Condition for secondary diagonal if ((i + j) == (n - 1)) { Console.Write(mat[i, j] + \", \"); } } } Console.WriteLine(\"\"); } // Driver code public static void Main(String[] args) { int n = 4; int[, ] a = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 1, 2, 3, 4 }, { 5, 6, 7, 8 } }; printPrincipalDiagonal(a, n); printSecondaryDiagonal(a, n); }} // This code is contributed by 29AjayKumar", "e": 5608, "s": 4253, "text": null }, { "code": "<script> // Javascript Program to print the Diagonals of a Matrix let MAX = 100; // Function to print the Principal Diagonal function printPrincipalDiagonal(mat, n) { document.write(\"Principal Diagonal: \"); for (let i = 0; i < n; i++) { for (let j = 0; j < n; j++) { // Condition for principal diagonal if (i == j) { document.write(mat[i][j] + \", \"); } } } document.write(\"</br>\"); } // Function to print the Secondary Diagonal function printSecondaryDiagonal(mat, n) { document.write(\"Secondary Diagonal: \"); for (let i = 0; i < n; i++) { for (let j = 0; j < n; j++) { // Condition for secondary diagonal if ((i + j) == (n - 1)) { document.write(mat[i][j] + \", \"); } } } document.write(\"</br>\"); } let n = 4; let a = [ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ] ]; printPrincipalDiagonal(a, n); printSecondaryDiagonal(a, n); </script>", "e": 6801, "s": 5608, "text": null }, { "code": null, "e": 6866, "s": 6801, "text": "Principal Diagonal: 1, 6, 3, 8, \nSecondary Diagonal: 4, 7, 2, 5," }, { "code": null, "e": 6891, "s": 6868, "text": "Complexity Analysis: " }, { "code": null, "e": 6985, "s": 6891, "text": "Time Complexity: O(n2). As there is a nested loop involved so the time complexity is squared." }, { "code": null, "e": 7039, "s": 6985, "text": "Auxiliary Space: O(1). As no extra space is occupied." }, { "code": null, "e": 7171, "s": 7039, "text": "Method 2: In this method, the same condition for printing the diagonal elements can be achieved using a single for loop. Approach: " }, { "code": null, "e": 7510, "s": 7171, "text": "For Principal Diagonal elements: Run a for a loop until n, where n is the number of columns, and print array[i][i] where i is the index variable.For Secondary Diagonal elements: Run a for a loop until n, where n is the number of columns and print array[i][k] where i is the index variable and k = array_length – 1. Decrease k until i < n." }, { "code": null, "e": 7656, "s": 7510, "text": "For Principal Diagonal elements: Run a for a loop until n, where n is the number of columns, and print array[i][i] where i is the index variable." }, { "code": null, "e": 7850, "s": 7656, "text": "For Secondary Diagonal elements: Run a for a loop until n, where n is the number of columns and print array[i][k] where i is the index variable and k = array_length – 1. Decrease k until i < n." }, { "code": null, "e": 7903, "s": 7850, "text": "Below is the implementation of the above approach. " }, { "code": null, "e": 7907, "s": 7903, "text": "C++" }, { "code": null, "e": 7912, "s": 7907, "text": "Java" }, { "code": null, "e": 7920, "s": 7912, "text": "Python3" }, { "code": null, "e": 7923, "s": 7920, "text": "C#" }, { "code": null, "e": 7934, "s": 7923, "text": "Javascript" }, { "code": "// C++ Program to print the Diagonals of a Matrix #include <bits/stdc++.h>using namespace std; const int MAX = 100; // Function to print the Principal Diagonalvoid printPrincipalDiagonal(int mat[][MAX], int n){ cout << \"Principal Diagonal: \"; for (int i = 0; i < n; i++) { // Printing principal diagonal cout << mat[i][i] << \", \"; } cout << endl;} // Function to print the Secondary Diagonalvoid printSecondaryDiagonal(int mat[][MAX], int n){ cout << \"Secondary Diagonal: \"; int k = n - 1; for (int i = 0; i < n; i++) { // Printing secondary diagonal cout << mat[i][k--] << \", \"; } cout << endl;} // Driver codeint main(){ int n = 4; int a[][MAX] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 1, 2, 3, 4 }, { 5, 6, 7, 8 } }; printPrincipalDiagonal(a, n); printSecondaryDiagonal(a, n); return 0;} // This code is contributed by yashbeersingh42", "e": 8901, "s": 7934, "text": null }, { "code": "// Java Program to print the// Diagonals of a Matrixclass Main{ static int MAX = 100; // Function to print the Principal Diagonalpublic static void printPrincipalDiagonal(int mat[][], int n){ System.out.print(\"Principal Diagonal: \"); for (int i = 0; i < n; i++) { // Printing principal diagonal System.out.print(mat[i][i] + \", \"); } System.out.println();} // Function to print the Secondary Diagonalpublic static void printSecondaryDiagonal(int mat[][], int n){ System.out.print(\"Secondary Diagonal: \"); int k = n - 1; for (int i = 0; i < n; i++) { // Printing secondary diagonal System.out.print(mat[i][k--] + \", \"); } System.out.println();} public static void main(String[] args){ int n = 4; int a[][] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {1, 2, 3, 4}, {5, 6, 7, 8}}; printPrincipalDiagonal(a, n); printSecondaryDiagonal(a, n);}} // This code is contributed by divyeshrabadiya07", "e": 9937, "s": 8901, "text": null }, { "code": "# Python3 program to print the# Diagonals of a MatrixMAX = 100 # Function to print the Principal Diagonaldef printPrincipalDiagonal(mat, n): print(\"Principal Diagonal: \", end = \"\") for i in range(n): # Printing principal diagonal print(mat[i][i], end = \", \") print() # Function to print the Secondary Diagonaldef printSecondaryDiagonal(mat, n): print(\"Secondary Diagonal: \", end = \"\") k = n - 1 for i in range(n): # Printing secondary diagonal print(mat[i][k], end = \", \") k -= 1 print() # Driver Coden = 4a = [ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ] ] printPrincipalDiagonal(a, n)printSecondaryDiagonal(a, n) # This code is contributed by divyesh072019", "e": 10718, "s": 9937, "text": null }, { "code": "// C# program for the// above approachusing System;class GFG{ // Function to print the// Principal Diagonalstatic void printPrincipalDiagonal(int [,]mat, int n){ Console.Write(\"Principal Diagonal: \"); for (int i = 0; i < n; i++) { // Printing principal diagonal Console.Write(mat[i, i] + \", \"); } Console.Write(\"\\n\");} // Function to print the// Secondary Diagonalstatic void printSecondaryDiagonal(int [,]mat, int n){ Console.Write(\"Secondary Diagonal: \"); int k = n - 1; for (int i = 0; i < n; i++) { // Printing secondary diagonal Console.Write(mat[i, k--] + \", \"); } Console.Write(\"\\n\");} // Driver codestatic void Main(){ int n = 4; int [,]a = {{1, 2, 3, 4}, {5, 6, 7, 8}, {1, 2, 3, 4}, {5, 6, 7, 8}}; printPrincipalDiagonal(a, n); printSecondaryDiagonal(a, n);}} // This code is contributed by rutvik_56", "e": 11683, "s": 10718, "text": null }, { "code": "<script> // Javascript Program to print the // Diagonals of a Matrix let MAX = 100; // Function to print the Principal Diagonal function printPrincipalDiagonal(mat, n) { document.write(\"Principal Diagonal: \"); for (let i = 0; i < n; i++) { // Printing principal diagonal document.write(mat[i][i] + \", \"); } document.write(\"</br>\"); } // Function to print the Secondary Diagonal function printSecondaryDiagonal(mat, n) { document.write(\"Secondary Diagonal: \"); let k = n - 1; for (let i = 0; i < n; i++) { // Printing secondary diagonal document.write(mat[i][k--] + \", \"); } document.write(\"</br>\"); } let n = 4; let a = [[1, 2, 3, 4], [5, 6, 7, 8], [1, 2, 3, 4], [5, 6, 7, 8]]; printPrincipalDiagonal(a, n); printSecondaryDiagonal(a, n); </script>", "e": 12615, "s": 11683, "text": null }, { "code": null, "e": 12680, "s": 12615, "text": "Principal Diagonal: 1, 6, 3, 8, \nSecondary Diagonal: 4, 7, 2, 5," }, { "code": null, "e": 12704, "s": 12682, "text": "Complexity Analysis: " }, { "code": null, "e": 12796, "s": 12704, "text": "Time Complexity: O(n). As there is only one loop involved so the time complexity is linear." }, { "code": null, "e": 12850, "s": 12796, "text": "Auxiliary Space: O(1). As no extra space is occupied." }, { "code": null, "e": 12867, "s": 12852, "text": "mohit kumar 29" }, { "code": null, "e": 12877, "s": 12867, "text": "Rajput-Ji" }, { "code": null, "e": 12889, "s": 12877, "text": "29AjayKumar" }, { "code": null, "e": 12905, "s": 12889, "text": "yashbeersingh42" }, { "code": null, "e": 12922, "s": 12905, "text": "sumanmandal15135" }, { "code": null, "e": 12932, "s": 12922, "text": "Code_Mech" }, { "code": null, "e": 12942, "s": 12932, "text": "rutvik_56" }, { "code": null, "e": 12960, "s": 12942, "text": "divyeshrabadiya07" }, { "code": null, "e": 12974, "s": 12960, "text": "divyesh072019" }, { "code": null, "e": 12983, "s": 12974, "text": "mukesh07" }, { "code": null, "e": 12998, "s": 12983, "text": "rameshtravel07" }, { "code": null, "e": 13005, "s": 12998, "text": "Matrix" }, { "code": null, "e": 13024, "s": 13005, "text": "School Programming" }, { "code": null, "e": 13031, "s": 13024, "text": "Matrix" }, { "code": null, "e": 13129, "s": 13031, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 13153, "s": 13129, "text": "Sudoku | Backtracking-7" }, { "code": null, "e": 13175, "s": 13153, "text": "The Celebrity Problem" }, { "code": null, "e": 13257, "s": 13175, "text": "Rotate a matrix by 90 degree in clockwise direction without using any extra space" }, { "code": null, "e": 13310, "s": 13257, "text": "Maximum size rectangle binary sub-matrix with all 1s" }, { "code": null, "e": 13361, "s": 13310, "text": "Inplace rotate square matrix by 90 degrees | Set 1" }, { "code": null, "e": 13379, "s": 13361, "text": "Python Dictionary" }, { "code": null, "e": 13404, "s": 13379, "text": "Reverse a string in Java" }, { "code": null, "e": 13420, "s": 13404, "text": "Arrays in C/C++" }, { "code": null, "e": 13443, "s": 13420, "text": "Introduction To PYTHON" } ]
Maximum circular subarray sum of size K
03 Jun, 2021 Given an array arr of size N and an integer K, the task is to find the maximum sum subarray of size k among all contiguous sub-array (considering circular subarray also). Examples: Input: arr = {18, 4, 3, 4, 5, 6, 7, 8, 2, 10}, k = 3 Output: max circular sum = 32 start index = 9 end index = 1 Explanation: Maximum Sum = 10 + 18 + 4 = 32 Input: arr = {8, 2, 5, 9}, k = 4 Output: max circular sum = 24 start index = 0 end index = 3 Approach: Iterate the loop till (n + k) times and Take (i % n) to handle the case when the array index becomes greater than n. Below is the implementation of above approach: C++ Java Python3 C# Javascript // C++ program to find maximum circular// subarray sum of size k #include <bits/stdc++.h>using namespace std; // Function to calculate// maximum sumvoid maxCircularSum(int arr[], int n, int k){ // k must be greater if (n < k) { cout << "Invalid"; return; } int sum = 0, start = 0, end = k - 1; // calculate the sum of first k elements. for (int i = 0; i < k; i++) { sum += arr[i]; } int ans = sum; for (int i = k; i < n + k; i++) { // add current element to sum // and subtract the first element // of the previous window. sum += arr[i % n] - arr[(i - k) % n]; if (sum > ans) { ans = sum; start = (i - k + 1) % n; end = i % n; } } cout << "max circular sum = " << ans << endl; cout << "start index = " << start << "\nend index = " << end << endl;} // Driver Codeint main(){ int arr[] = { 18, 4, 3, 4, 5, 6, 7, 8, 2, 10 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 3; maxCircularSum(arr, n, k); return 0;} // Java program to find maximum circular// subarray sum of size k import java.util.*; class GFG{ // Function to calculate // maximum sum static void maxCircularSum(int[] arr, int n, int k) { // k must be greater if (n < k) { System.out.println("Invalid"); return; } int sum = 0, start = 0, end = k - 1; // calculate the sum of first k elements. for (int i = 0; i < k; i++) sum += arr[i]; int ans = sum; for (int i = k; i < n + k; i++) { // add current element to sum // and subtract the first element // of the previous window. sum += arr[i % n] - arr[(i - k) % n]; if (sum > ans) { ans = sum; start = (i - k + 1) % n; end = i % n; } } System.out.println("max circular sum = " + ans); System.out.println("start index = " + start + "\nend index = " + end); } // Driver Code public static void main(String[] args) { int[] arr = { 18, 4, 3, 4, 5, 6, 7, 8, 2, 10 }; int n = arr.length; int k = 3; maxCircularSum(arr, n, k); }} // This code is contributed by// sanjeev2552 # Python3 program to find maximum circular# subarray sum of size k # Function to calculate# maximum sumdef maxCircularSum(arr, n, k) : # k must be greater if (n < k) : print("Invalid"); return; sum = 0; start = 0; end = k - 1; # calculate the sum of first k elements. for i in range(k) : sum += arr[i]; ans = sum; for i in range(k, n + k) : # add current element to sum # and subtract the first element # of the previous window. sum += arr[i % n] - arr[(i - k) % n]; if (sum > ans) : ans = sum; start = (i - k + 1) % n; end = i % n; print("max circular sum = ",ans); print("start index = ", start, "\nend index = ", end); # Driver Codeif __name__ == "__main__" : arr = [ 18, 4, 3, 4, 5, 6, 7, 8, 2, 10 ]; n = len(arr); k = 3; maxCircularSum(arr, n, k); # This code is contributed by AnkitRai01 // C# program to find maximum circular// subarray sum of size kusing System; class GFG{ // Function to calculate // maximum sum static void maxCircularSum(int[] arr, int n, int k) { // k must be greater if (n < k) { Console.WriteLine("Invalid"); return; } int sum = 0, start = 0, end = k - 1; // calculate the sum of first k elements. for (int i = 0; i < k; i++) sum += arr[i]; int ans = sum; for (int i = k; i < n + k; i++) { // add current element to sum // and subtract the first element // of the previous window. sum += arr[i % n] - arr[(i - k) % n]; if (sum > ans) { ans = sum; start = (i - k + 1) % n; end = i % n; } } Console.WriteLine("max circular sum = " + ans); Console.WriteLine("start index = " + start + "\nend index = " + end); } // Driver Code public static void Main(String[] args) { int[] arr = { 18, 4, 3, 4, 5, 6, 7, 8, 2, 10 }; int n = arr.Length; int k = 3; maxCircularSum(arr, n, k); }} // This code is contributed by 29AjayKumar <script> // Javascript program to find maximum circular// subarray sum of size k // Function to calculate// maximum sumfunction maxCircularSum(arr, n, k){ // k must be greater if (n < k) { document.write("Invalid"); return; } let sum = 0, start = 0, end = k - 1; // Calculate the sum of first k elements. for(let i = 0; i < k; i++) { sum += arr[i]; } let ans = sum; for(let i = k; i < n + k; i++) { // Add current element to sum // and subtract the first element // of the previous window. sum += arr[i % n] - arr[(i - k) % n]; if (sum > ans) { ans = sum; start = (i - k + 1) % n; end = i % n; } } document.write("max circular sum = " + ans + "<br>"); document.write("start index = " + start + "<br>end index = " + end + "<br>");} // Driver Codelet arr = [ 18, 4, 3, 4, 5, 6, 7, 8, 2, 10 ];let n = arr.lengthlet k = 3; maxCircularSum(arr, n, k); // This code is contributed by _saurabh_jaiswal </script> max circular sum = 32 start index = 9 end index = 1 Time Complexity: ankthon sanjeev2552 29AjayKumar _saurabh_jaiswal circular-array subarray subarray-sum Arrays Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Data Structures Search, insert and delete in an unsorted array Window Sliding Technique Chocolate Distribution Problem Find duplicates in O(n) time and O(1) extra space | Set 1 Next Greater Element Move all negative numbers to beginning and positive to end with constant extra space What is Data Structure: Types, Classifications and Applications Count pairs with given sum Find subarray with given sum | Set 1 (Nonnegative Numbers)
[ { "code": null, "e": 54, "s": 26, "text": "\n03 Jun, 2021" }, { "code": null, "e": 225, "s": 54, "text": "Given an array arr of size N and an integer K, the task is to find the maximum sum subarray of size k among all contiguous sub-array (considering circular subarray also)." }, { "code": null, "e": 236, "s": 225, "text": "Examples: " }, { "code": null, "e": 393, "s": 236, "text": "Input: arr = {18, 4, 3, 4, 5, 6, 7, 8, 2, 10}, k = 3 Output: max circular sum = 32 start index = 9 end index = 1 Explanation: Maximum Sum = 10 + 18 + 4 = 32" }, { "code": null, "e": 488, "s": 393, "text": "Input: arr = {8, 2, 5, 9}, k = 4 Output: max circular sum = 24 start index = 0 end index = 3 " }, { "code": null, "e": 500, "s": 488, "text": "Approach: " }, { "code": null, "e": 540, "s": 500, "text": "Iterate the loop till (n + k) times and" }, { "code": null, "e": 617, "s": 540, "text": "Take (i % n) to handle the case when the array index becomes greater than n." }, { "code": null, "e": 666, "s": 617, "text": "Below is the implementation of above approach: " }, { "code": null, "e": 670, "s": 666, "text": "C++" }, { "code": null, "e": 675, "s": 670, "text": "Java" }, { "code": null, "e": 683, "s": 675, "text": "Python3" }, { "code": null, "e": 686, "s": 683, "text": "C#" }, { "code": null, "e": 697, "s": 686, "text": "Javascript" }, { "code": "// C++ program to find maximum circular// subarray sum of size k #include <bits/stdc++.h>using namespace std; // Function to calculate// maximum sumvoid maxCircularSum(int arr[], int n, int k){ // k must be greater if (n < k) { cout << \"Invalid\"; return; } int sum = 0, start = 0, end = k - 1; // calculate the sum of first k elements. for (int i = 0; i < k; i++) { sum += arr[i]; } int ans = sum; for (int i = k; i < n + k; i++) { // add current element to sum // and subtract the first element // of the previous window. sum += arr[i % n] - arr[(i - k) % n]; if (sum > ans) { ans = sum; start = (i - k + 1) % n; end = i % n; } } cout << \"max circular sum = \" << ans << endl; cout << \"start index = \" << start << \"\\nend index = \" << end << endl;} // Driver Codeint main(){ int arr[] = { 18, 4, 3, 4, 5, 6, 7, 8, 2, 10 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 3; maxCircularSum(arr, n, k); return 0;}", "e": 1777, "s": 697, "text": null }, { "code": "// Java program to find maximum circular// subarray sum of size k import java.util.*; class GFG{ // Function to calculate // maximum sum static void maxCircularSum(int[] arr, int n, int k) { // k must be greater if (n < k) { System.out.println(\"Invalid\"); return; } int sum = 0, start = 0, end = k - 1; // calculate the sum of first k elements. for (int i = 0; i < k; i++) sum += arr[i]; int ans = sum; for (int i = k; i < n + k; i++) { // add current element to sum // and subtract the first element // of the previous window. sum += arr[i % n] - arr[(i - k) % n]; if (sum > ans) { ans = sum; start = (i - k + 1) % n; end = i % n; } } System.out.println(\"max circular sum = \" + ans); System.out.println(\"start index = \" + start + \"\\nend index = \" + end); } // Driver Code public static void main(String[] args) { int[] arr = { 18, 4, 3, 4, 5, 6, 7, 8, 2, 10 }; int n = arr.length; int k = 3; maxCircularSum(arr, n, k); }} // This code is contributed by// sanjeev2552", "e": 3057, "s": 1777, "text": null }, { "code": "# Python3 program to find maximum circular# subarray sum of size k # Function to calculate# maximum sumdef maxCircularSum(arr, n, k) : # k must be greater if (n < k) : print(\"Invalid\"); return; sum = 0; start = 0; end = k - 1; # calculate the sum of first k elements. for i in range(k) : sum += arr[i]; ans = sum; for i in range(k, n + k) : # add current element to sum # and subtract the first element # of the previous window. sum += arr[i % n] - arr[(i - k) % n]; if (sum > ans) : ans = sum; start = (i - k + 1) % n; end = i % n; print(\"max circular sum = \",ans); print(\"start index = \", start, \"\\nend index = \", end); # Driver Codeif __name__ == \"__main__\" : arr = [ 18, 4, 3, 4, 5, 6, 7, 8, 2, 10 ]; n = len(arr); k = 3; maxCircularSum(arr, n, k); # This code is contributed by AnkitRai01", "e": 3998, "s": 3057, "text": null }, { "code": "// C# program to find maximum circular// subarray sum of size kusing System; class GFG{ // Function to calculate // maximum sum static void maxCircularSum(int[] arr, int n, int k) { // k must be greater if (n < k) { Console.WriteLine(\"Invalid\"); return; } int sum = 0, start = 0, end = k - 1; // calculate the sum of first k elements. for (int i = 0; i < k; i++) sum += arr[i]; int ans = sum; for (int i = k; i < n + k; i++) { // add current element to sum // and subtract the first element // of the previous window. sum += arr[i % n] - arr[(i - k) % n]; if (sum > ans) { ans = sum; start = (i - k + 1) % n; end = i % n; } } Console.WriteLine(\"max circular sum = \" + ans); Console.WriteLine(\"start index = \" + start + \"\\nend index = \" + end); } // Driver Code public static void Main(String[] args) { int[] arr = { 18, 4, 3, 4, 5, 6, 7, 8, 2, 10 }; int n = arr.Length; int k = 3; maxCircularSum(arr, n, k); }} // This code is contributed by 29AjayKumar", "e": 5340, "s": 3998, "text": null }, { "code": "<script> // Javascript program to find maximum circular// subarray sum of size k // Function to calculate// maximum sumfunction maxCircularSum(arr, n, k){ // k must be greater if (n < k) { document.write(\"Invalid\"); return; } let sum = 0, start = 0, end = k - 1; // Calculate the sum of first k elements. for(let i = 0; i < k; i++) { sum += arr[i]; } let ans = sum; for(let i = k; i < n + k; i++) { // Add current element to sum // and subtract the first element // of the previous window. sum += arr[i % n] - arr[(i - k) % n]; if (sum > ans) { ans = sum; start = (i - k + 1) % n; end = i % n; } } document.write(\"max circular sum = \" + ans + \"<br>\"); document.write(\"start index = \" + start + \"<br>end index = \" + end + \"<br>\");} // Driver Codelet arr = [ 18, 4, 3, 4, 5, 6, 7, 8, 2, 10 ];let n = arr.lengthlet k = 3; maxCircularSum(arr, n, k); // This code is contributed by _saurabh_jaiswal </script>", "e": 6477, "s": 5340, "text": null }, { "code": null, "e": 6529, "s": 6477, "text": "max circular sum = 32\nstart index = 9\nend index = 1" }, { "code": null, "e": 6549, "s": 6531, "text": "Time Complexity: " }, { "code": null, "e": 6557, "s": 6549, "text": "ankthon" }, { "code": null, "e": 6569, "s": 6557, "text": "sanjeev2552" }, { "code": null, "e": 6581, "s": 6569, "text": "29AjayKumar" }, { "code": null, "e": 6598, "s": 6581, "text": "_saurabh_jaiswal" }, { "code": null, "e": 6613, "s": 6598, "text": "circular-array" }, { "code": null, "e": 6622, "s": 6613, "text": "subarray" }, { "code": null, "e": 6635, "s": 6622, "text": "subarray-sum" }, { "code": null, "e": 6642, "s": 6635, "text": "Arrays" }, { "code": null, "e": 6649, "s": 6642, "text": "Arrays" }, { "code": null, "e": 6747, "s": 6649, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6779, "s": 6747, "text": "Introduction to Data Structures" }, { "code": null, "e": 6826, "s": 6779, "text": "Search, insert and delete in an unsorted array" }, { "code": null, "e": 6851, "s": 6826, "text": "Window Sliding Technique" }, { "code": null, "e": 6882, "s": 6851, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 6940, "s": 6882, "text": "Find duplicates in O(n) time and O(1) extra space | Set 1" }, { "code": null, "e": 6961, "s": 6940, "text": "Next Greater Element" }, { "code": null, "e": 7046, "s": 6961, "text": "Move all negative numbers to beginning and positive to end with constant extra space" }, { "code": null, "e": 7110, "s": 7046, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 7137, "s": 7110, "text": "Count pairs with given sum" } ]
C Program For Inserting A Node In A Linked List
22 Dec, 2021 We have introduced Linked Lists in the previous post. We also created a simple linked list with 3 nodes and discussed linked list traversal.All programs discussed in this post consider the following representations of the linked list. C // A linked list nodestruct Node{ int data; struct Node *next;}; In this post, methods to insert a new node in linked list are discussed. A node can be added in three ways 1) At the front of the linked list 2) After a given node. 3) At the end of the linked list. Add a node at the front: (4 steps process) The new node is always added before the head of the given Linked List. And newly added node becomes the new head of the Linked List. For example, if the given Linked List is 10->15->20->25 and we add an item 5 at the front, then the Linked List becomes 5->10->15->20->25. Let us call the function that adds at the front of the list is push(). The push() must receive a pointer to the head pointer, because push must change the head pointer to point to the new node (See this) Following are the 4 steps to add a node at the front. C // Given a reference (pointer to pointer) to // the head of a list and an int, inserts a // new node on the front of the list. void push(struct Node** head_ref, int new_data){ // 1. Allocate node struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); // 2. put in the data new_node->data = new_data; // 3. Make next of new node as head new_node->next = (*head_ref); // 4. move the head to point to // the new node (*head_ref) = new_node;} Time complexity of push() is O(1) as it does a constant amount of work.Add a node after a given node: (5 steps process) We are given a pointer to a node, and the new node is inserted after the given node. C // Given a node prev_node, insert a // new node after the given prev_node void insertAfter(struct Node* prev_node, int new_data) { // 1. Check if the given prev_node // is NULL if (prev_node == NULL) { printf("the given previous node cannot be NULL"); return; } // 2. Allocate new node struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); // 3. Put in the data new_node->data = new_data; // 4. Make next of new node as next // of prev_node new_node->next = prev_node->next; // 5. Move the next of prev_node // as new_node prev_node->next = new_node; } Time complexity of insertAfter() is O(1) as it does a constant amount of work. Add a node at the end: (6 steps process) The new node is always added after the last node of the given Linked List. For example if the given Linked List is 5->10->15->20->25 and we add an item 30 at the end, then the Linked List becomes 5->10->15->20->25->30. Since a Linked List is typically represented by the head of it, we have to traverse the list till the end and then change the next to last node to a new node. Following are the 6 steps to add node at the end. C // Given a reference (pointer to pointer) to // the head of a list and an int, appends a // new node at the end void append(struct Node** head_ref, int new_data){ // 1. Allocate node struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); // Used in step 5 struct Node *last = *head_ref; // 2. Put in the data new_node->data = new_data; // 3. This new node is going to be the // last node, so make next of it as NULL new_node->next = NULL; // 4. If the Linked List is empty, then make // the new node as head if (*head_ref == NULL) { *head_ref = new_node; return; } // 5. Else traverse till the last node while (last->next != NULL) last = last->next; // 6. Change the next of last node last->next = new_node; return; } Time complexity of append is O(n) where n is the number of nodes in the linked list. Since there is a loop from head to end, the function does O(n) work. This method can also be optimized to work in O(1) by keeping an extra pointer to the tail of the linked list. Following is a complete program that uses all of the above methods to create a linked list. C // A complete working C program to demonstrate // all insertion methods on Linked List#include <stdio.h>#include <stdlib.h> // A linked list nodestruct Node{ int data; struct Node *next;}; // Given a reference (pointer to pointer) to // the head of a list and an int, inserts a // new node on the front of the list. void push(struct Node** head_ref, int new_data){ // 1. Allocate node struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); // 2. Put in the data new_node->data = new_data; // 3. Make next of new node as head new_node->next = (*head_ref); // 4. move the head to point to // the new node (*head_ref) = new_node;} // Given a node prev_node, insert a // new node after the given prev_node void insertAfter(struct Node* prev_node, int new_data){ // 1. Check if the given prev_node // is NULL if (prev_node == NULL) { printf("the given previous node cannot be NULL"); return; } // 2. Allocate new node struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); // 3. Put in the data new_node->data = new_data; // 4. Make next of new node as next // of prev_node new_node->next = prev_node->next; // 5. Move the next of prev_node // as new_node prev_node->next = new_node;} // Given a reference (pointer to pointer) to // the head of a list and an int, appends a // new node at the end void append(struct Node** head_ref, int new_data){ // 1. Allocate node struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); // Used in step 5 struct Node *last = *head_ref; // 2. Put in the data new_node->data = new_data; // 3. This new node is going to be the // last node, so make next of it as NULL new_node->next = NULL; // 4. If the Linked List is empty, then make // the new node as head if (*head_ref == NULL) { *head_ref = new_node; return; } // 5. Else traverse till the last node while (last->next != NULL) last = last->next; // 6. Change the next of last node last->next = new_node; return;} // This function prints contents of the // linked list starting from headvoid printList(struct Node *node){ while (node != NULL) { printf(" %d ", node->data); node = node->next; }} // Driver codeint main(){ // Start with the empty list struct Node* head = NULL; // Insert 6. So linked list // becomes 6->NULL append(&head, 6); // Insert 7 at the beginning. // So linked list becomes 7->6->NULL push(&head, 7); // Insert 1 at the beginning. So // linked list becomes 1->7->6->NULL push(&head, 1); // Insert 4 at the end. So linked list // becomes 1->7->6->4->NULL append(&head, 4); // Insert 8, after 7. So linked list // becomes 1->7->8->6->4->NULL insertAfter(head->next, 8); printf("Created Linked list is: "); printList(head); return 0;} Output: Created Linked list is: 1 7 8 6 4 Please refer complete article on Linked List | Set 2 (Inserting a node) for more details! Linked Lists TCS Wipro C Language C Programs Linked List Wipro TCS Linked List Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Dec, 2021" }, { "code": null, "e": 264, "s": 28, "text": "We have introduced Linked Lists in the previous post. We also created a simple linked list with 3 nodes and discussed linked list traversal.All programs discussed in this post consider the following representations of the linked list. " }, { "code": null, "e": 266, "s": 264, "text": "C" }, { "code": "// A linked list nodestruct Node{ int data; struct Node *next;};", "e": 333, "s": 266, "text": null }, { "code": null, "e": 532, "s": 333, "text": "In this post, methods to insert a new node in linked list are discussed. A node can be added in three ways 1) At the front of the linked list 2) After a given node. 3) At the end of the linked list." }, { "code": null, "e": 1051, "s": 532, "text": "Add a node at the front: (4 steps process) The new node is always added before the head of the given Linked List. And newly added node becomes the new head of the Linked List. For example, if the given Linked List is 10->15->20->25 and we add an item 5 at the front, then the Linked List becomes 5->10->15->20->25. Let us call the function that adds at the front of the list is push(). The push() must receive a pointer to the head pointer, because push must change the head pointer to point to the new node (See this)" }, { "code": null, "e": 1105, "s": 1051, "text": "Following are the 4 steps to add a node at the front." }, { "code": null, "e": 1107, "s": 1105, "text": "C" }, { "code": "// Given a reference (pointer to pointer) to // the head of a list and an int, inserts a // new node on the front of the list. void push(struct Node** head_ref, int new_data){ // 1. Allocate node struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); // 2. put in the data new_node->data = new_data; // 3. Make next of new node as head new_node->next = (*head_ref); // 4. move the head to point to // the new node (*head_ref) = new_node;}", "e": 1626, "s": 1107, "text": null }, { "code": null, "e": 1831, "s": 1626, "text": "Time complexity of push() is O(1) as it does a constant amount of work.Add a node after a given node: (5 steps process) We are given a pointer to a node, and the new node is inserted after the given node." }, { "code": null, "e": 1833, "s": 1831, "text": "C" }, { "code": "// Given a node prev_node, insert a // new node after the given prev_node void insertAfter(struct Node* prev_node, int new_data) { // 1. Check if the given prev_node // is NULL if (prev_node == NULL) { printf(\"the given previous node cannot be NULL\"); return; } // 2. Allocate new node struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); // 3. Put in the data new_node->data = new_data; // 4. Make next of new node as next // of prev_node new_node->next = prev_node->next; // 5. Move the next of prev_node // as new_node prev_node->next = new_node; }", "e": 2516, "s": 1833, "text": null }, { "code": null, "e": 2595, "s": 2516, "text": "Time complexity of insertAfter() is O(1) as it does a constant amount of work." }, { "code": null, "e": 3014, "s": 2595, "text": "Add a node at the end: (6 steps process) The new node is always added after the last node of the given Linked List. For example if the given Linked List is 5->10->15->20->25 and we add an item 30 at the end, then the Linked List becomes 5->10->15->20->25->30. Since a Linked List is typically represented by the head of it, we have to traverse the list till the end and then change the next to last node to a new node." }, { "code": null, "e": 3064, "s": 3014, "text": "Following are the 6 steps to add node at the end." }, { "code": null, "e": 3066, "s": 3064, "text": "C" }, { "code": "// Given a reference (pointer to pointer) to // the head of a list and an int, appends a // new node at the end void append(struct Node** head_ref, int new_data){ // 1. Allocate node struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); // Used in step 5 struct Node *last = *head_ref; // 2. Put in the data new_node->data = new_data; // 3. This new node is going to be the // last node, so make next of it as NULL new_node->next = NULL; // 4. If the Linked List is empty, then make // the new node as head if (*head_ref == NULL) { *head_ref = new_node; return; } // 5. Else traverse till the last node while (last->next != NULL) last = last->next; // 6. Change the next of last node last->next = new_node; return; }", "e": 3935, "s": 3066, "text": null }, { "code": null, "e": 4199, "s": 3935, "text": "Time complexity of append is O(n) where n is the number of nodes in the linked list. Since there is a loop from head to end, the function does O(n) work. This method can also be optimized to work in O(1) by keeping an extra pointer to the tail of the linked list." }, { "code": null, "e": 4291, "s": 4199, "text": "Following is a complete program that uses all of the above methods to create a linked list." }, { "code": null, "e": 4293, "s": 4291, "text": "C" }, { "code": "// A complete working C program to demonstrate // all insertion methods on Linked List#include <stdio.h>#include <stdlib.h> // A linked list nodestruct Node{ int data; struct Node *next;}; // Given a reference (pointer to pointer) to // the head of a list and an int, inserts a // new node on the front of the list. void push(struct Node** head_ref, int new_data){ // 1. Allocate node struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); // 2. Put in the data new_node->data = new_data; // 3. Make next of new node as head new_node->next = (*head_ref); // 4. move the head to point to // the new node (*head_ref) = new_node;} // Given a node prev_node, insert a // new node after the given prev_node void insertAfter(struct Node* prev_node, int new_data){ // 1. Check if the given prev_node // is NULL if (prev_node == NULL) { printf(\"the given previous node cannot be NULL\"); return; } // 2. Allocate new node struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); // 3. Put in the data new_node->data = new_data; // 4. Make next of new node as next // of prev_node new_node->next = prev_node->next; // 5. Move the next of prev_node // as new_node prev_node->next = new_node;} // Given a reference (pointer to pointer) to // the head of a list and an int, appends a // new node at the end void append(struct Node** head_ref, int new_data){ // 1. Allocate node struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); // Used in step 5 struct Node *last = *head_ref; // 2. Put in the data new_node->data = new_data; // 3. This new node is going to be the // last node, so make next of it as NULL new_node->next = NULL; // 4. If the Linked List is empty, then make // the new node as head if (*head_ref == NULL) { *head_ref = new_node; return; } // 5. Else traverse till the last node while (last->next != NULL) last = last->next; // 6. Change the next of last node last->next = new_node; return;} // This function prints contents of the // linked list starting from headvoid printList(struct Node *node){ while (node != NULL) { printf(\" %d \", node->data); node = node->next; }} // Driver codeint main(){ // Start with the empty list struct Node* head = NULL; // Insert 6. So linked list // becomes 6->NULL append(&head, 6); // Insert 7 at the beginning. // So linked list becomes 7->6->NULL push(&head, 7); // Insert 1 at the beginning. So // linked list becomes 1->7->6->NULL push(&head, 1); // Insert 4 at the end. So linked list // becomes 1->7->6->4->NULL append(&head, 4); // Insert 8, after 7. So linked list // becomes 1->7->8->6->4->NULL insertAfter(head->next, 8); printf(\"Created Linked list is: \"); printList(head); return 0;}", "e": 7335, "s": 4293, "text": null }, { "code": null, "e": 7343, "s": 7335, "text": "Output:" }, { "code": null, "e": 7383, "s": 7343, "text": " Created Linked list is: 1 7 8 6 4" }, { "code": null, "e": 7473, "s": 7383, "text": "Please refer complete article on Linked List | Set 2 (Inserting a node) for more details!" }, { "code": null, "e": 7486, "s": 7473, "text": "Linked Lists" }, { "code": null, "e": 7490, "s": 7486, "text": "TCS" }, { "code": null, "e": 7496, "s": 7490, "text": "Wipro" }, { "code": null, "e": 7507, "s": 7496, "text": "C Language" }, { "code": null, "e": 7518, "s": 7507, "text": "C Programs" }, { "code": null, "e": 7530, "s": 7518, "text": "Linked List" }, { "code": null, "e": 7536, "s": 7530, "text": "Wipro" }, { "code": null, "e": 7540, "s": 7536, "text": "TCS" }, { "code": null, "e": 7552, "s": 7540, "text": "Linked List" } ]
Wfuzz Download – Web Application Password Cracker in Kali Linux
14 Sep, 2021 Brute-Forcing is the technique to discover the hidden directories and files on the target server. We can even brute-force usernames and passwords. All this process is done through an automated tool. Quickly Request-Response methodology is executed on the domain. Wfuzz tool is an automated tool used to perform all types of brute-forcing on the target domain. Wfuzz tool is developed in the Python Language. Wfuzz tool is available on the GitHub platform, it’s free and open-source to use. We can specify our mode of request and change the User-Agent values to stay anonymous on the target domain. Note: Make Sure You have Python Installed on your System, as this is a python-based tool. Click to check the Installation process: Python Installation Steps on Linux Step 1: Use the following command to install the tool in your Kali Linux operating system. git clone https://github.com/xmendez/wfuzz.git Step 2: Now use the following command to move into the directory of the tool. You have to move in the directory in order to run the tool. cd wfuzz Step 3: You are in the directory of the Wfuzz. Now you have to install a dependency of the Wfuzz using the following command. sudo pip3 install -r requirements.txt Step 4: All the dependencies have been installed in your Kali Linux operating system. Now use the following command to run the tool and check the help section. wfuzz -h Example 1: Simple Directory Scan on geeksforgeeks.org wfuzz -c -z file,wordlist/general/big.txt –hc 404 http://geeksforgeeks.org/FUZZ Example 2: Printing Wfuzz version details wfuzz --version Example 3: Verbose Information/ More Detailed Output wfuzz -v -z file,wordlist/general/big.txt –hc 404,301 http://geeksforgeeks.org/FUZZ Kali-Linux Linux-Tools Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. TCP Server-Client implementation in C tar command in Linux with examples Compiling with g++ 'crontab' in Linux with Examples UDP Server-Client implementation in C touch command in Linux with Examples nohup Command in Linux with Examples echo command in Linux with Examples Cat command in Linux with examples Conditional Statements | Shell Script
[ { "code": null, "e": 28, "s": 0, "text": "\n14 Sep, 2021" }, { "code": null, "e": 626, "s": 28, "text": "Brute-Forcing is the technique to discover the hidden directories and files on the target server. We can even brute-force usernames and passwords. All this process is done through an automated tool. Quickly Request-Response methodology is executed on the domain. Wfuzz tool is an automated tool used to perform all types of brute-forcing on the target domain. Wfuzz tool is developed in the Python Language. Wfuzz tool is available on the GitHub platform, it’s free and open-source to use. We can specify our mode of request and change the User-Agent values to stay anonymous on the target domain." }, { "code": null, "e": 792, "s": 626, "text": "Note: Make Sure You have Python Installed on your System, as this is a python-based tool. Click to check the Installation process: Python Installation Steps on Linux" }, { "code": null, "e": 883, "s": 792, "text": "Step 1: Use the following command to install the tool in your Kali Linux operating system." }, { "code": null, "e": 930, "s": 883, "text": "git clone https://github.com/xmendez/wfuzz.git" }, { "code": null, "e": 1068, "s": 930, "text": "Step 2: Now use the following command to move into the directory of the tool. You have to move in the directory in order to run the tool." }, { "code": null, "e": 1077, "s": 1068, "text": "cd wfuzz" }, { "code": null, "e": 1203, "s": 1077, "text": "Step 3: You are in the directory of the Wfuzz. Now you have to install a dependency of the Wfuzz using the following command." }, { "code": null, "e": 1241, "s": 1203, "text": "sudo pip3 install -r requirements.txt" }, { "code": null, "e": 1401, "s": 1241, "text": "Step 4: All the dependencies have been installed in your Kali Linux operating system. Now use the following command to run the tool and check the help section." }, { "code": null, "e": 1410, "s": 1401, "text": "wfuzz -h" }, { "code": null, "e": 1464, "s": 1410, "text": "Example 1: Simple Directory Scan on geeksforgeeks.org" }, { "code": null, "e": 1544, "s": 1464, "text": "wfuzz -c -z file,wordlist/general/big.txt –hc 404 http://geeksforgeeks.org/FUZZ" }, { "code": null, "e": 1586, "s": 1544, "text": "Example 2: Printing Wfuzz version details" }, { "code": null, "e": 1602, "s": 1586, "text": "wfuzz --version" }, { "code": null, "e": 1656, "s": 1602, "text": "Example 3: Verbose Information/ More Detailed Output" }, { "code": null, "e": 1741, "s": 1656, "text": " wfuzz -v -z file,wordlist/general/big.txt –hc 404,301 http://geeksforgeeks.org/FUZZ" }, { "code": null, "e": 1752, "s": 1741, "text": "Kali-Linux" }, { "code": null, "e": 1764, "s": 1752, "text": "Linux-Tools" }, { "code": null, "e": 1775, "s": 1764, "text": "Linux-Unix" }, { "code": null, "e": 1873, "s": 1775, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1911, "s": 1873, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 1946, "s": 1911, "text": "tar command in Linux with examples" }, { "code": null, "e": 1965, "s": 1946, "text": "Compiling with g++" }, { "code": null, "e": 1998, "s": 1965, "text": "'crontab' in Linux with Examples" }, { "code": null, "e": 2036, "s": 1998, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 2073, "s": 2036, "text": "touch command in Linux with Examples" }, { "code": null, "e": 2110, "s": 2073, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 2146, "s": 2110, "text": "echo command in Linux with Examples" }, { "code": null, "e": 2181, "s": 2146, "text": "Cat command in Linux with examples" } ]
Python | Difference of two lists including duplicates
13 May, 2019 The ways to find difference of two lists has been discussed earlier, but sometimes, we require to remove only the specific occurrences of the elements as much they occur in other list. Let’s discuss certain ways in which this can be performed. Method #1 : Using collections.Counter()The Counter method can be used to get the exact occurrence of the elements in the list and hence can subtract selectively rather than using the set and ignoring the count of elements altogether. Then the subtraction can be performed to get the actual occurrence. # Python3 code to demonstrate# Difference of list including duplicates# Using collections.Counter()from collections import Counter # initializing liststest_list1 = [1, 3, 4, 5, 1, 3, 3]test_list2 = [1, 3, 5] # printing original listsprint("The original list 1 : " + str(test_list1))print("The original list 2 : " + str(test_list2)) # Using collections.Counter()# Difference of list including duplicatesres = list((Counter(test_list1) - Counter(test_list2)).elements()) # print resultprint("The list after performing the subtraction : " + str(res)) The original list 1 : [1, 3, 4, 5, 1, 3, 3] The original list 2 : [1, 3, 5] The list after performing the subtraction : [1, 3, 3, 4] Method #2 : Using map() + lambda + remove()The combination of above functions can be used to perform this particular task. The map function can be used to link the function to all elements and remove removes the first occurrence of it. Hence doesn’t remove repeatedly. Works with Python2 only. # Python code to demonstrate# Difference of list including duplicates# Using map() + lambda + remove() # initializing liststest_list1 = [1, 3, 4, 5, 1, 3, 3]test_list2 = [1, 3, 5] # printing original listsprint("The original list 1 : " + str(test_list1))print("The original list 2 : " + str(test_list2)) # Using map() + lambda + remove()# Difference of list including duplicatesres = map(lambda x: test_list1.remove(x) if x in test_list1 else None, test_list2) # print resultprint("The list after performing the subtraction : " + str(test_list1)) The original list 1 : [1, 3, 4, 5, 1, 3, 3] The original list 2 : [1, 3, 5] The list after performing the subtraction : [1, 3, 3, 4] Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python | Convert string dictionary to dictionary Python Program for Fibonacci numbers
[ { "code": null, "e": 28, "s": 0, "text": "\n13 May, 2019" }, { "code": null, "e": 272, "s": 28, "text": "The ways to find difference of two lists has been discussed earlier, but sometimes, we require to remove only the specific occurrences of the elements as much they occur in other list. Let’s discuss certain ways in which this can be performed." }, { "code": null, "e": 574, "s": 272, "text": "Method #1 : Using collections.Counter()The Counter method can be used to get the exact occurrence of the elements in the list and hence can subtract selectively rather than using the set and ignoring the count of elements altogether. Then the subtraction can be performed to get the actual occurrence." }, { "code": "# Python3 code to demonstrate# Difference of list including duplicates# Using collections.Counter()from collections import Counter # initializing liststest_list1 = [1, 3, 4, 5, 1, 3, 3]test_list2 = [1, 3, 5] # printing original listsprint(\"The original list 1 : \" + str(test_list1))print(\"The original list 2 : \" + str(test_list2)) # Using collections.Counter()# Difference of list including duplicatesres = list((Counter(test_list1) - Counter(test_list2)).elements()) # print resultprint(\"The list after performing the subtraction : \" + str(res))", "e": 1126, "s": 574, "text": null }, { "code": null, "e": 1260, "s": 1126, "text": "The original list 1 : [1, 3, 4, 5, 1, 3, 3]\nThe original list 2 : [1, 3, 5]\nThe list after performing the subtraction : [1, 3, 3, 4]\n" }, { "code": null, "e": 1556, "s": 1262, "text": "Method #2 : Using map() + lambda + remove()The combination of above functions can be used to perform this particular task. The map function can be used to link the function to all elements and remove removes the first occurrence of it. Hence doesn’t remove repeatedly. Works with Python2 only." }, { "code": "# Python code to demonstrate# Difference of list including duplicates# Using map() + lambda + remove() # initializing liststest_list1 = [1, 3, 4, 5, 1, 3, 3]test_list2 = [1, 3, 5] # printing original listsprint(\"The original list 1 : \" + str(test_list1))print(\"The original list 2 : \" + str(test_list2)) # Using map() + lambda + remove()# Difference of list including duplicatesres = map(lambda x: test_list1.remove(x) if x in test_list1 else None, test_list2) # print resultprint(\"The list after performing the subtraction : \" + str(test_list1))", "e": 2117, "s": 1556, "text": null }, { "code": null, "e": 2251, "s": 2117, "text": "The original list 1 : [1, 3, 4, 5, 1, 3, 3]\nThe original list 2 : [1, 3, 5]\nThe list after performing the subtraction : [1, 3, 3, 4]\n" }, { "code": null, "e": 2272, "s": 2251, "text": "Python list-programs" }, { "code": null, "e": 2279, "s": 2272, "text": "Python" }, { "code": null, "e": 2295, "s": 2279, "text": "Python Programs" }, { "code": null, "e": 2393, "s": 2295, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2425, "s": 2393, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2452, "s": 2425, "text": "Python Classes and Objects" }, { "code": null, "e": 2473, "s": 2452, "text": "Python OOPs Concepts" }, { "code": null, "e": 2496, "s": 2473, "text": "Introduction To PYTHON" }, { "code": null, "e": 2552, "s": 2496, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2574, "s": 2552, "text": "Defaultdict in Python" }, { "code": null, "e": 2613, "s": 2574, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2651, "s": 2613, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 2700, "s": 2651, "text": "Python | Convert string dictionary to dictionary" } ]
Python | Extract only characters from given string
03 Apr, 2019 Given a string, the task is to extract only alphabetical characters from a string. Given below are few methods to solve the given problem. Method #1: Using re.split # Python code to demonstrate# to get characters from stringimport re # initialising stringini_string = "123()#$ABGFDabcjw"ini_string2 = "abceddfgh" # printing stringsprint ("initial string : ", ini_string, ini_string2) # code to find characters in stringres1 = " ".join(re.split("[^a-zA-Z]*", ini_string))res2 = " ".join(re.split("[^a-zA-Z]*", ini_string2)) # printing resultant stringprint ("first string result: ", str(res1))print ("second string result: ", str(res2)) Output: initial string : 123()#$ABGFDabcjw abceddfgh first string result: ABGFDabcjw second string result: abceddfgh Method #2: Using re.fidall # Python code to demonstrate# to get characters in stringimport re # initialising stringini_string = "123()#$ABGFDabcjw"ini_string2 = "abceddfgh" # printing stringsprint ("initial string : \n", ini_string, "\n", ini_string2) # code to find characters in stringres1 = " ".join(re.findall("[a-zA-Z]+", ini_string))res2 = " ".join(re.findall("[a-zA-Z]+", ini_string2)) # printing resultant stringprint ("first string result: ", str(res1))print ("second string result: ", str(res2)) Output: initial string : 123()#$ABGFDabcjw abceddfgh first string result: ABGFDabcjw second string result: abceddfgh Method #3: Using isalpha() # Python code to demonstrate# to get characters in a string# if present # initialising stringini_string = "123()#$ABGFDabcjw" # printing string and its lengthprint ("initial string : ", ini_string) # code to find characters in stringres1 = ""for i in ini_string: if i.isalpha(): res1 = "".join([res1, i]) # printing resultant stringprint ("first result: ", str(res1)) Output: initial string : 123()#$ABGFDabcjw first result: ABGFDabcjw Python string-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Iterate over a list in Python How to iterate through Excel rows in Python? Enumerate() in Python Rotate axis tick labels in Seaborn and Matplotlib Python Dictionary Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python | Split string into list of characters
[ { "code": null, "e": 28, "s": 0, "text": "\n03 Apr, 2019" }, { "code": null, "e": 167, "s": 28, "text": "Given a string, the task is to extract only alphabetical characters from a string. Given below are few methods to solve the given problem." }, { "code": null, "e": 193, "s": 167, "text": "Method #1: Using re.split" }, { "code": "# Python code to demonstrate# to get characters from stringimport re # initialising stringini_string = \"123()#$ABGFDabcjw\"ini_string2 = \"abceddfgh\" # printing stringsprint (\"initial string : \", ini_string, ini_string2) # code to find characters in stringres1 = \" \".join(re.split(\"[^a-zA-Z]*\", ini_string))res2 = \" \".join(re.split(\"[^a-zA-Z]*\", ini_string2)) # printing resultant stringprint (\"first string result: \", str(res1))print (\"second string result: \", str(res2))", "e": 668, "s": 193, "text": null }, { "code": null, "e": 676, "s": 668, "text": "Output:" }, { "code": null, "e": 789, "s": 676, "text": "initial string : 123()#$ABGFDabcjw abceddfgh\nfirst string result: ABGFDabcjw\nsecond string result: abceddfgh" }, { "code": null, "e": 817, "s": 789, "text": " Method #2: Using re.fidall" }, { "code": "# Python code to demonstrate# to get characters in stringimport re # initialising stringini_string = \"123()#$ABGFDabcjw\"ini_string2 = \"abceddfgh\" # printing stringsprint (\"initial string : \\n\", ini_string, \"\\n\", ini_string2) # code to find characters in stringres1 = \" \".join(re.findall(\"[a-zA-Z]+\", ini_string))res2 = \" \".join(re.findall(\"[a-zA-Z]+\", ini_string2)) # printing resultant stringprint (\"first string result: \", str(res1))print (\"second string result: \", str(res2))", "e": 1300, "s": 817, "text": null }, { "code": null, "e": 1308, "s": 1300, "text": "Output:" }, { "code": null, "e": 1424, "s": 1308, "text": "initial string : \n 123()#$ABGFDabcjw \n abceddfgh\n\nfirst string result: ABGFDabcjw\nsecond string result: abceddfgh" }, { "code": null, "e": 1452, "s": 1424, "text": " Method #3: Using isalpha()" }, { "code": "# Python code to demonstrate# to get characters in a string# if present # initialising stringini_string = \"123()#$ABGFDabcjw\" # printing string and its lengthprint (\"initial string : \", ini_string) # code to find characters in stringres1 = \"\"for i in ini_string: if i.isalpha(): res1 = \"\".join([res1, i]) # printing resultant stringprint (\"first result: \", str(res1))", "e": 1836, "s": 1452, "text": null }, { "code": null, "e": 1844, "s": 1836, "text": "Output:" }, { "code": null, "e": 1907, "s": 1844, "text": "initial string : 123()#$ABGFDabcjw\nfirst result: ABGFDabcjw\n" }, { "code": null, "e": 1930, "s": 1907, "text": "Python string-programs" }, { "code": null, "e": 1937, "s": 1930, "text": "Python" }, { "code": null, "e": 1953, "s": 1937, "text": "Python Programs" }, { "code": null, "e": 2051, "s": 1953, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2081, "s": 2051, "text": "Iterate over a list in Python" }, { "code": null, "e": 2126, "s": 2081, "text": "How to iterate through Excel rows in Python?" }, { "code": null, "e": 2148, "s": 2126, "text": "Enumerate() in Python" }, { "code": null, "e": 2198, "s": 2148, "text": "Rotate axis tick labels in Seaborn and Matplotlib" }, { "code": null, "e": 2216, "s": 2198, "text": "Python Dictionary" }, { "code": null, "e": 2259, "s": 2216, "text": "Python program to convert a list to string" }, { "code": null, "e": 2281, "s": 2259, "text": "Defaultdict in Python" }, { "code": null, "e": 2320, "s": 2281, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2358, "s": 2320, "text": "Python | Convert a list to dictionary" } ]
jQuery - Interaction Drag-able
The Drag-able function can be used with interactions in JqueryUI.This function can enable drag-able functionality on any DOM element.We can drag the drag-able element by clicking on it with mouse. Here is the simple syntax to use drag-able − $( "#draggable" ).draggable(); Following is a simple example showing the usage of drag-able − <html> <head> <title>The jQuery Example</title> <script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script> <script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/jquery-ui.min.js"> </script> <script type = "text/javascript" language = "javascript"> $(function() { $( "#draggable" ).draggable(); }); </script> <style> #draggable { width: 150px; height: 150px; padding: 0.5em; } .back{ background-color: lightgrey; width: 50px; padding: 25px; border: 25px solid navy; margin: 25px; } </style> </head> <body> <div id = "draggable" class = "ui-widget-content"> <p class = "back">Drag</p> </div> </body> </html> This will produce following result − Drag 27 Lectures 1 hours Mahesh Kumar 27 Lectures 1.5 hours Pratik Singh 72 Lectures 4.5 hours Frahaan Hussain 60 Lectures 9 hours Eduonix Learning Solutions 17 Lectures 2 hours Sandip Bhattacharya 12 Lectures 53 mins Laurence Svekis Print Add Notes Bookmark this page
[ { "code": null, "e": 2519, "s": 2322, "text": "The Drag-able function can be used with interactions in JqueryUI.This function can enable drag-able functionality on any DOM element.We can drag the drag-able element by clicking on it with mouse." }, { "code": null, "e": 2564, "s": 2519, "text": "Here is the simple syntax to use drag-able −" }, { "code": null, "e": 2597, "s": 2564, "text": " $( \"#draggable\" ).draggable();\n" }, { "code": null, "e": 2660, "s": 2597, "text": "Following is a simple example showing the usage of drag-able −" }, { "code": null, "e": 3610, "s": 2660, "text": "<html>\n <head>\n <title>The jQuery Example</title>\n <script type = \"text/javascript\" \n src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\">\n </script>\n\t\t\n <script type = \"text/javascript\" \n src = \"https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/jquery-ui.min.js\">\n </script>\n\t\t\n <script type = \"text/javascript\" language = \"javascript\">\n \n $(function() {\n $( \"#draggable\" ).draggable();\n });\n\t\t \n </script>\n\t\t\n <style>\n #draggable { width: 150px; height: 150px; padding: 0.5em; }\n .back{\n background-color: lightgrey;\n width: 50px;\n padding: 25px;\n border: 25px solid navy;\n margin: 25px;\n }\n </style>\n </head>\n\t\n <body>\n <div id = \"draggable\" class = \"ui-widget-content\">\n <p class = \"back\">Drag</p>\n </div>\n\t \n </body>\n</html>" }, { "code": null, "e": 3647, "s": 3610, "text": "This will produce following result −" }, { "code": null, "e": 3652, "s": 3647, "text": "Drag" }, { "code": null, "e": 3685, "s": 3652, "text": "\n 27 Lectures \n 1 hours \n" }, { "code": null, "e": 3699, "s": 3685, "text": " Mahesh Kumar" }, { "code": null, "e": 3734, "s": 3699, "text": "\n 27 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3748, "s": 3734, "text": " Pratik Singh" }, { "code": null, "e": 3783, "s": 3748, "text": "\n 72 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3800, "s": 3783, "text": " Frahaan Hussain" }, { "code": null, "e": 3833, "s": 3800, "text": "\n 60 Lectures \n 9 hours \n" }, { "code": null, "e": 3861, "s": 3833, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3894, "s": 3861, "text": "\n 17 Lectures \n 2 hours \n" }, { "code": null, "e": 3915, "s": 3894, "text": " Sandip Bhattacharya" }, { "code": null, "e": 3947, "s": 3915, "text": "\n 12 Lectures \n 53 mins\n" }, { "code": null, "e": 3964, "s": 3947, "text": " Laurence Svekis" }, { "code": null, "e": 3971, "s": 3964, "text": " Print" }, { "code": null, "e": 3982, "s": 3971, "text": " Add Notes" } ]
HBase - Listing Table
list is the command that is used to list all the tables in HBase. Given below is the syntax of the list command. hbase(main):001:0 > list When you type this command and execute in HBase prompt, it will display the list of all the tables in HBase as shown below. hbase(main):001:0> list TABLE emp Here you can observe a table named emp. Follow the steps given below to get the list of tables from HBase using java API. You have a method called listTables() in the class HBaseAdmin to get the list of all the tables in HBase. This method returns an array of HTableDescriptor objects. //creating a configuration object Configuration conf = HBaseConfiguration.create(); //Creating HBaseAdmin object HBaseAdmin admin = new HBaseAdmin(conf); //Getting all the list of tables using HBaseAdmin object HTableDescriptor[] tableDescriptor = admin.listTables(); You can get the length of the HTableDescriptor[] array using the length variable of the HTableDescriptor class. Get the name of the tables from this object using getNameAsString() method. Run the ‘for’ loop using these and get the list of the tables in HBase. Given below is the program to list all the tables in HBase using Java API. import java.io.IOException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.HTableDescriptor; import org.apache.hadoop.hbase.MasterNotRunningException; import org.apache.hadoop.hbase.client.HBaseAdmin; public class ListTables { public static void main(String args[])throws MasterNotRunningException, IOException{ // Instantiating a configuration class Configuration conf = HBaseConfiguration.create(); // Instantiating HBaseAdmin class HBaseAdmin admin = new HBaseAdmin(conf); // Getting all the list of tables using HBaseAdmin object HTableDescriptor[] tableDescriptor = admin.listTables(); // printing all the table names. for (int i=0; i<tableDescriptor.length;i++ ){ System.out.println(tableDescriptor[i].getNameAsString()); } } } Compile and execute the above program as shown below. $javac ListTables.java $java ListTables The following should be the output: User emp Print Add Notes Bookmark this page
[ { "code": null, "e": 2150, "s": 2037, "text": "list is the command that is used to list all the tables in HBase. Given below is the syntax of the list command." }, { "code": null, "e": 2176, "s": 2150, "text": "hbase(main):001:0 > list\n" }, { "code": null, "e": 2300, "s": 2176, "text": "When you type this command and execute in HBase prompt, it will display the list of all the tables in HBase as shown below." }, { "code": null, "e": 2335, "s": 2300, "text": "hbase(main):001:0> list\nTABLE\nemp\n" }, { "code": null, "e": 2375, "s": 2335, "text": "Here you can observe a table named emp." }, { "code": null, "e": 2457, "s": 2375, "text": "Follow the steps given below to get the list of tables from HBase using java API." }, { "code": null, "e": 2621, "s": 2457, "text": "You have a method called listTables() in the class HBaseAdmin to get the list of all the tables in HBase. This method returns an array of HTableDescriptor objects." }, { "code": null, "e": 2892, "s": 2621, "text": "//creating a configuration object\nConfiguration conf = HBaseConfiguration.create();\n\n//Creating HBaseAdmin object\nHBaseAdmin admin = new HBaseAdmin(conf);\n\n//Getting all the list of tables using HBaseAdmin object\nHTableDescriptor[] tableDescriptor = admin.listTables();\n" }, { "code": null, "e": 3152, "s": 2892, "text": "You can get the length of the HTableDescriptor[] array using the length variable of the HTableDescriptor class. Get the name of the tables from this object using getNameAsString() method. Run the ‘for’ loop using these and get the list of the tables in HBase." }, { "code": null, "e": 3227, "s": 3152, "text": "Given below is the program to list all the tables in HBase using Java API." }, { "code": null, "e": 4122, "s": 3227, "text": "import java.io.IOException;\n\nimport org.apache.hadoop.conf.Configuration;\n\nimport org.apache.hadoop.hbase.HBaseConfiguration;\nimport org.apache.hadoop.hbase.HTableDescriptor;\nimport org.apache.hadoop.hbase.MasterNotRunningException;\nimport org.apache.hadoop.hbase.client.HBaseAdmin;\n\npublic class ListTables {\n\n public static void main(String args[])throws MasterNotRunningException, IOException{\n\n // Instantiating a configuration class\n Configuration conf = HBaseConfiguration.create();\n\n // Instantiating HBaseAdmin class\n HBaseAdmin admin = new HBaseAdmin(conf);\n\n // Getting all the list of tables using HBaseAdmin object\n HTableDescriptor[] tableDescriptor = admin.listTables();\n\n // printing all the table names.\n for (int i=0; i<tableDescriptor.length;i++ ){\n System.out.println(tableDescriptor[i].getNameAsString());\n }\n \n }\n}" }, { "code": null, "e": 4176, "s": 4122, "text": "Compile and execute the above program as shown below." }, { "code": null, "e": 4217, "s": 4176, "text": "$javac ListTables.java\n$java ListTables\n" }, { "code": null, "e": 4253, "s": 4217, "text": "The following should be the output:" }, { "code": null, "e": 4263, "s": 4253, "text": "User\nemp\n" }, { "code": null, "e": 4270, "s": 4263, "text": " Print" }, { "code": null, "e": 4281, "s": 4270, "text": " Add Notes" } ]
Implementing Checksum Using Java
Following is the code to implement Checksum using Java − Live Demo import java.util.*; public class Demo{ public static void main(String args[]){ Scanner my_scan = new Scanner(System.in); System.out.println("Enter the input string "); String my_in = my_scan.next(); int my_checksum = generate_checksum(my_in); System.out.println("The checksum that has been generated is " + Integer.toHexString(my_checksum)); System.out.println("Enter the data that needs to be sent to the receiver "); my_in = my_scan.next(); System.out.println("Enter the checksum that needs to be sent to the receiver "); my_checksum = Integer.parseInt((my_scan.next()), 16); receive(my_in, my_checksum); my_scan.close(); } static int generate_checksum(String s){ String my_hex_val = new String(); int x, i, my_checksum = 0; for (i = 0; i < s.length() - 2; i = i + 2){ x = (int) (s.charAt(i)); my_hex_val = Integer.toHexString(x); x = (int) (s.charAt(i + 1)); my_hex_val = my_hex_val + Integer.toHexString(x); System.out.println(s.charAt(i) + "" + s.charAt(i + 1) + " : " + my_hex_val); x = Integer.parseInt(my_hex_val, 16); my_checksum += x; } if (s.length() % 2 == 0){ x = (int) (s.charAt(i)); my_hex_val = Integer.toHexString(x); x = (int) (s.charAt(i + 1)); my_hex_val = my_hex_val + Integer.toHexString(x); System.out.println(s.charAt(i) + "" + s.charAt(i + 1) + " : "+ my_hex_val); x = Integer.parseInt(my_hex_val, 16); } else { x = (int) (s.charAt(i)); my_hex_val = "00" + Integer.toHexString(x); x = Integer.parseInt(my_hex_val, 16); System.out.println(s.charAt(i) + " : " + my_hex_val); } my_checksum += x; my_hex_val = Integer.toHexString(my_checksum); if (my_hex_val.length() > 4){ int carry = Integer.parseInt(("" + my_hex_val.charAt(0)), 16); my_hex_val = my_hex_val.substring(1, 5); my_checksum = Integer.parseInt(my_hex_val, 16); my_checksum += carry; } my_checksum = generate_complement(my_checksum); return my_checksum; } static void receive(String s, int my_checksum){ int gen_checksum = generate_checksum(s); gen_checksum = generate_complement(gen_checksum); int syndrome = gen_checksum + my_checksum; syndrome = generate_complement(syndrome); System.out.println("The value of syndrome is " + Integer.toHexString(syndrome)); if (syndrome == 0){ System.out.println("Data has been received without any errors"); } else { System.out.println("An error was encountered in the received data"); } } static int generate_complement(int my_checksum){ my_checksum = Integer.parseInt("FFFF", 16) - my_checksum; return my_checksum; } } sample sample b2c8 Enter the input string sa : 7361 mp : 6d70 le : 6c65 The checksum that has been generated is b2c8 Enter the data that needs to be sent to the receiver Enter the checksum that needs to be sent to the receiver sa : 7361 mp : 6d70 le : 6c65 The value of syndrome is 0 Data has been received without any errors A class named Demo contains the main function. Here, a Scanner instance is defined and an input string is defined. The ‘generate_checksum’ function is defined which creates a new string instance and initializes the checksum to 0. The string passed to this function as parameter is iterated over, and converted to hexadecimal value. Every character is iterated over and converted to integer value. It is then converted to a hexadecimal value. Then, the hexadecimal value is added to the next character’s hexadecimal value. If the length of the string is even, every character is iterated over and converted to integer value. It is then converted to a hexadecimal value. Then, the hexadecimal value is added to the next character’s hexadecimal value. Otherwise, it is concatenated with ‘00’. The ‘receive’ functions calls the ‘generate_checksum’ function and passes the result. Then it is added to the original checksum value (that was initially 0). Then it is converted to hexadecimal value. If this length is greater than 4, then a ‘carry’ value is generated. The original checksum is parsed and added to the ‘carry’ value. Once this snippet executes, the ‘generate_complement’ function is called on the checksum value. The ‘generate_complement’ function subtracts the checksum value from ‘FFFF’-16.
[ { "code": null, "e": 1119, "s": 1062, "text": "Following is the code to implement Checksum using Java −" }, { "code": null, "e": 1130, "s": 1119, "text": " Live Demo" }, { "code": null, "e": 4009, "s": 1130, "text": "import java.util.*;\npublic class Demo{\n public static void main(String args[]){\n Scanner my_scan = new Scanner(System.in);\n System.out.println(\"Enter the input string \");\n String my_in = my_scan.next();\n int my_checksum = generate_checksum(my_in);\n System.out.println(\"The checksum that has been generated is \" + Integer.toHexString(my_checksum));\n System.out.println(\"Enter the data that needs to be sent to the receiver \");\n my_in = my_scan.next();\n System.out.println(\"Enter the checksum that needs to be sent to the receiver \");\n my_checksum = Integer.parseInt((my_scan.next()), 16);\n receive(my_in, my_checksum);\n my_scan.close();\n }\n static int generate_checksum(String s){\n String my_hex_val = new String();\n int x, i, my_checksum = 0;\n for (i = 0; i < s.length() - 2; i = i + 2){\n x = (int) (s.charAt(i));\n my_hex_val = Integer.toHexString(x);\n x = (int) (s.charAt(i + 1));\n my_hex_val = my_hex_val + Integer.toHexString(x);\n System.out.println(s.charAt(i) + \"\" + s.charAt(i + 1) + \" : \" + my_hex_val);\n x = Integer.parseInt(my_hex_val, 16);\n my_checksum += x;\n }\n if (s.length() % 2 == 0){\n x = (int) (s.charAt(i));\n my_hex_val = Integer.toHexString(x);\n x = (int) (s.charAt(i + 1));\n my_hex_val = my_hex_val + Integer.toHexString(x);\n System.out.println(s.charAt(i) + \"\" + s.charAt(i + 1) + \" : \"+ my_hex_val);\n x = Integer.parseInt(my_hex_val, 16);\n } else {\n x = (int) (s.charAt(i));\n my_hex_val = \"00\" + Integer.toHexString(x);\n x = Integer.parseInt(my_hex_val, 16);\n System.out.println(s.charAt(i) + \" : \" + my_hex_val);\n }\n my_checksum += x;\n my_hex_val = Integer.toHexString(my_checksum);\n if (my_hex_val.length() > 4){\n int carry = Integer.parseInt((\"\" + my_hex_val.charAt(0)), 16);\n my_hex_val = my_hex_val.substring(1, 5);\n my_checksum = Integer.parseInt(my_hex_val, 16);\n my_checksum += carry;\n }\n my_checksum = generate_complement(my_checksum);\n return my_checksum;\n }\n static void receive(String s, int my_checksum){\n int gen_checksum = generate_checksum(s);\n gen_checksum = generate_complement(gen_checksum);\n int syndrome = gen_checksum + my_checksum;\n syndrome = generate_complement(syndrome);\n System.out.println(\"The value of syndrome is \" + Integer.toHexString(syndrome));\n if (syndrome == 0){\n System.out.println(\"Data has been received without any errors\");\n } else {\n System.out.println(\"An error was encountered in the received data\");\n }\n }\n static int generate_complement(int my_checksum){\n my_checksum = Integer.parseInt(\"FFFF\", 16) - my_checksum;\n return my_checksum;\n }\n}" }, { "code": null, "e": 4028, "s": 4009, "text": "sample\nsample\nb2c8" }, { "code": null, "e": 4335, "s": 4028, "text": "Enter the input string\nsa : 7361\nmp : 6d70\nle : 6c65\nThe checksum that has been generated is b2c8\nEnter the data that needs to be sent to the receiver\nEnter the checksum that needs to be sent to the receiver\nsa : 7361\nmp : 6d70\nle : 6c65\nThe value of syndrome is 0\nData has been received without any errors" }, { "code": null, "e": 4450, "s": 4335, "text": "A class named Demo contains the main function. Here, a Scanner instance is defined and an input string is defined." }, { "code": null, "e": 4857, "s": 4450, "text": "The ‘generate_checksum’ function is defined which creates a new string instance and initializes the checksum to 0. The string passed to this function as parameter is iterated over, and converted to hexadecimal value. Every character is iterated over and converted to integer value. It is then converted to a hexadecimal value. Then, the hexadecimal value is added to the next character’s hexadecimal value." }, { "code": null, "e": 5125, "s": 4857, "text": "If the length of the string is even, every character is iterated over and converted to integer value. It is then converted to a hexadecimal value. Then, the hexadecimal value is added to the next character’s hexadecimal value. Otherwise, it is concatenated with ‘00’." }, { "code": null, "e": 5635, "s": 5125, "text": "The ‘receive’ functions calls the ‘generate_checksum’ function and passes the result. Then it is added to the original checksum value (that was initially 0). Then it is converted to hexadecimal value. If this length is greater than 4, then a ‘carry’ value is generated. The original checksum is parsed and added to the ‘carry’ value. Once this snippet executes, the ‘generate_complement’ function is called on the checksum value. The ‘generate_complement’ function subtracts the checksum value from ‘FFFF’-16." } ]
GATE | GATE CS 2018 | Question 9 - GeeksforGeeks
22 Feb, 2018 If pqr ≠ 0 and , what is the value of the product xyz ? (A) -1(B) 1 / pqr(C) 1(D) pqrAnswer: (C)Explanation: Taking logs of given three values,we get 1/q = p-x -------(1) 1/r = q-y -------(2) 1/p = r-z -------(3) 1/q = p-x = r-xz [Putting value of p from (3)] = q-xyz [Putting value of r from (2)] = 1 / qxyz On comparing power of q both sides, we get xyz = 1 So, option (C) is correct. Quiz of this Question GATE CS 2018 GATE-GATE CS 2018 GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments GATE | GATE-CS-2016 (Set 2) | Question 48 GATE | GATE-CS-2014-(Set-1) | Question 30 GATE | GATE-CS-2001 | Question 23 GATE | GATE-CS-2015 (Set 1) | Question 65 GATE | GATE CS 2010 | Question 45 GATE | GATE-CS-2015 (Set 3) | Question 65 GATE | GATE-CS-2014-(Set-1) | Question 65 GATE | GATE-CS-2015 (Set 1) | Question 42 C++ Program to count Vowels in a string using Pointer GATE | GATE-CS-2004 | Question 3
[ { "code": null, "e": 23951, "s": 23923, "text": "\n22 Feb, 2018" }, { "code": null, "e": 24008, "s": 23951, "text": "If pqr ≠ 0 and , what is the value of the product xyz ?" }, { "code": null, "e": 24102, "s": 24008, "text": "(A) -1(B) 1 / pqr(C) 1(D) pqrAnswer: (C)Explanation: Taking logs of given three values,we get" }, { "code": null, "e": 24327, "s": 24102, "text": "1/q = p-x -------(1)\n1/r = q-y -------(2)\n1/p = r-z -------(3)\n\n1/q = p-x\n = r-xz [Putting value of p from (3)]\n = q-xyz [Putting value of r from (2)]\n = 1 / qxyz\n\nOn comparing power of q both sides, we get xyz = 1" }, { "code": null, "e": 24354, "s": 24327, "text": "So, option (C) is correct." }, { "code": null, "e": 24376, "s": 24354, "text": "Quiz of this Question" }, { "code": null, "e": 24389, "s": 24376, "text": "GATE CS 2018" }, { "code": null, "e": 24407, "s": 24389, "text": "GATE-GATE CS 2018" }, { "code": null, "e": 24412, "s": 24407, "text": "GATE" }, { "code": null, "e": 24510, "s": 24412, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 24519, "s": 24510, "text": "Comments" }, { "code": null, "e": 24532, "s": 24519, "text": "Old Comments" }, { "code": null, "e": 24574, "s": 24532, "text": "GATE | GATE-CS-2016 (Set 2) | Question 48" }, { "code": null, "e": 24616, "s": 24574, "text": "GATE | GATE-CS-2014-(Set-1) | Question 30" }, { "code": null, "e": 24650, "s": 24616, "text": "GATE | GATE-CS-2001 | Question 23" }, { "code": null, "e": 24692, "s": 24650, "text": "GATE | GATE-CS-2015 (Set 1) | Question 65" }, { "code": null, "e": 24726, "s": 24692, "text": "GATE | GATE CS 2010 | Question 45" }, { "code": null, "e": 24768, "s": 24726, "text": "GATE | GATE-CS-2015 (Set 3) | Question 65" }, { "code": null, "e": 24810, "s": 24768, "text": "GATE | GATE-CS-2014-(Set-1) | Question 65" }, { "code": null, "e": 24852, "s": 24810, "text": "GATE | GATE-CS-2015 (Set 1) | Question 42" }, { "code": null, "e": 24906, "s": 24852, "text": "C++ Program to count Vowels in a string using Pointer" } ]
Python Creating Blockchain
A blockchain contains a list of blocks chained to each other. To store the entire list, we will create a list variable called TPCoins − TPCoins = [] We will also write a utility method called dump_blockchain for dumping the contents of the entire blockchain. We first print the length of the blockchain so that we know how many blocks are currently present in the blockchain. def dump_blockchain (self): print ("Number of blocks in the chain: " + str(len (self))) Note that as the time passes, the number of blocks in the blockchain would be extraordinarily high for printing. Thus, when you print the contents of the blockchain you may have to decide on the range that you would like to examine. In the code below, we have printed the entire blockchain as we would not be adding too many blocks in the current demo. To iterate through the chain, we set up a for loop as follows − for x in range (len(TPCoins)): block_temp = TPCoins[x] Each referenced block is copied to a temporary variable called block_temp. We print the block number as a heading for each block. Note that the numbers would start with zero, the first block is a genesis block that is numbered zero. print ("block # " + str(x)) Within each block, we have stored a list of three transactions (except for the genesis block) in a variable called verified_transactions. We iterate this list in a for loop and for each retrieved item, we call display_transaction function to display the transaction details. for transaction in block_temp.verified_transactions: display_transaction (transaction) The entire function definition is shown below − def dump_blockchain (self): print ("Number of blocks in the chain: " + str(len (self))) for x in range (len(TPCoins)): block_temp = TPCoins[x] print ("block # " + str(x)) for transaction in block_temp.verified_transactions: display_transaction (transaction) print ('--------------') print ('=====================================') Note that here we have inserted the separators at appropriate points in the code to demarcate the blocks and transactions within it. As we have now created a blockchain for storing blocks, our next task is to create blocks and start adding it to the blockchain. For this purpose, we will add a genesis block that you have already created in the earlier step. 187 Lectures 17.5 hours Malhar Lathkar 55 Lectures 8 hours Arnab Chakraborty 136 Lectures 11 hours In28Minutes Official 75 Lectures 13 hours Eduonix Learning Solutions 70 Lectures 8.5 hours Lets Kode It 63 Lectures 6 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 2131, "s": 1995, "text": "A blockchain contains a list of blocks chained to each other. To store the entire list, we will create a list variable called TPCoins −" }, { "code": null, "e": 2145, "s": 2131, "text": "TPCoins = []\n" }, { "code": null, "e": 2372, "s": 2145, "text": "We will also write a utility method called dump_blockchain for dumping the contents of the entire blockchain. We first print the length of the blockchain so that we know how many blocks are currently present in the blockchain." }, { "code": null, "e": 2464, "s": 2372, "text": "def dump_blockchain (self):\n print (\"Number of blocks in the chain: \" + str(len (self)))\n" }, { "code": null, "e": 2817, "s": 2464, "text": "Note that as the time passes, the number of blocks in the blockchain would be extraordinarily high for printing. Thus, when you print the contents of the blockchain you may have to decide on the range that you would like to examine. In the code below, we have printed the entire blockchain as we would not be adding too many blocks in the current demo." }, { "code": null, "e": 2881, "s": 2817, "text": "To iterate through the chain, we set up a for loop as follows −" }, { "code": null, "e": 2941, "s": 2881, "text": "for x in range (len(TPCoins)):\n block_temp = TPCoins[x] \n" }, { "code": null, "e": 3016, "s": 2941, "text": "Each referenced block is copied to a temporary variable called block_temp." }, { "code": null, "e": 3174, "s": 3016, "text": "We print the block number as a heading for each block. Note that the numbers would start with zero, the first block is a genesis block that is numbered zero." }, { "code": null, "e": 3203, "s": 3174, "text": "print (\"block # \" + str(x))\n" }, { "code": null, "e": 3478, "s": 3203, "text": "Within each block, we have stored a list of three transactions (except for the genesis block) in a variable called verified_transactions. We iterate this list in a for loop and for each retrieved item, we call display_transaction function to display the transaction details." }, { "code": null, "e": 3569, "s": 3478, "text": "for transaction in block_temp.verified_transactions:\n display_transaction (transaction)\n" }, { "code": null, "e": 3617, "s": 3569, "text": "The entire function definition is shown below −" }, { "code": null, "e": 3997, "s": 3617, "text": "def dump_blockchain (self):\n print (\"Number of blocks in the chain: \" + str(len (self)))\n for x in range (len(TPCoins)):\n block_temp = TPCoins[x]\n print (\"block # \" + str(x))\n for transaction in block_temp.verified_transactions:\n display_transaction (transaction)\n print ('--------------')\n print ('=====================================')\n" }, { "code": null, "e": 4130, "s": 3997, "text": "Note that here we have inserted the separators at appropriate points in the code to demarcate the blocks and transactions within it." }, { "code": null, "e": 4356, "s": 4130, "text": "As we have now created a blockchain for storing blocks, our next task is to create blocks and start adding it to the blockchain. For this purpose, we will add a genesis block that you have already created in the earlier step." }, { "code": null, "e": 4393, "s": 4356, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 4409, "s": 4393, "text": " Malhar Lathkar" }, { "code": null, "e": 4442, "s": 4409, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 4461, "s": 4442, "text": " Arnab Chakraborty" }, { "code": null, "e": 4496, "s": 4461, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 4518, "s": 4496, "text": " In28Minutes Official" }, { "code": null, "e": 4552, "s": 4518, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 4580, "s": 4552, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 4615, "s": 4580, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 4629, "s": 4615, "text": " Lets Kode It" }, { "code": null, "e": 4662, "s": 4629, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 4679, "s": 4662, "text": " Abhilash Nelson" }, { "code": null, "e": 4686, "s": 4679, "text": " Print" }, { "code": null, "e": 4697, "s": 4686, "text": " Add Notes" } ]
How to implement Dependency Injection using Property in C#?
The process of injecting (converting) coupled (dependent) objects into decoupled (independent) objects is called Dependency Injection. Types of Dependency Injection There are four types of DI − Constructor Injection Constructor Injection Setter Injection Setter Injection Interface-based injection Interface-based injection Service Locator Injection Service Locator Injection Getter and Setter Injection injects the dependency by using default public properties procedure such as Gettter(get(){}) and Setter(set(){}). public interface IService{ string ServiceMethod(); } public class ClaimService:IService{ public string ServiceMethod(){ return "ClaimService is running"; } } public class AdjudicationService:IService{ public string ServiceMethod(){ return "AdjudicationService is running"; } } public class BusinessLogicImplementation{ private IService _client; public IService Client{ get { return _client; } set { _client = value; } } public void SetterInj(){ Console.WriteLine("Getter and Setter Injection ==> Current Service : {0}", Client.ServiceMethod()); } } BusinessLogicImplementation ConInjBusinessLogic = new BusinessLogicImplementation(); ConInjBusinessLogic.Client = new ClaimService(); ConInjBusinessLogic.SetterInj();
[ { "code": null, "e": 1197, "s": 1062, "text": "The process of injecting (converting) coupled (dependent) objects into decoupled (independent) objects is called Dependency Injection." }, { "code": null, "e": 1227, "s": 1197, "text": "Types of Dependency Injection" }, { "code": null, "e": 1256, "s": 1227, "text": "There are four types of DI −" }, { "code": null, "e": 1278, "s": 1256, "text": "Constructor Injection" }, { "code": null, "e": 1300, "s": 1278, "text": "Constructor Injection" }, { "code": null, "e": 1317, "s": 1300, "text": "Setter Injection" }, { "code": null, "e": 1334, "s": 1317, "text": "Setter Injection" }, { "code": null, "e": 1360, "s": 1334, "text": "Interface-based injection" }, { "code": null, "e": 1386, "s": 1360, "text": "Interface-based injection" }, { "code": null, "e": 1412, "s": 1386, "text": "Service Locator Injection" }, { "code": null, "e": 1438, "s": 1412, "text": "Service Locator Injection" }, { "code": null, "e": 1581, "s": 1438, "text": "Getter and Setter Injection injects the dependency by using default public properties procedure such as Gettter(get(){}) and Setter(set(){}). " }, { "code": null, "e": 2196, "s": 1581, "text": "public interface IService{\n string ServiceMethod();\n}\npublic class ClaimService:IService{\n public string ServiceMethod(){\n return \"ClaimService is running\";\n }\n}\npublic class AdjudicationService:IService{\n public string ServiceMethod(){\n return \"AdjudicationService is running\";\n }\n}\npublic class BusinessLogicImplementation{\n private IService _client;\n public IService Client{\n get { return _client; }\n set { _client = value; }\n }\n public void SetterInj(){\n Console.WriteLine(\"Getter and Setter Injection ==>\n Current Service : {0}\", Client.ServiceMethod());\n }\n}" }, { "code": null, "e": 2363, "s": 2196, "text": "BusinessLogicImplementation ConInjBusinessLogic = new BusinessLogicImplementation();\nConInjBusinessLogic.Client = new ClaimService();\nConInjBusinessLogic.SetterInj();" } ]
Python | Pandas Series.loc - GeeksforGeeks
28 Jan, 2019 Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index. Pandas Series.loc attribute is used to access a group of rows and columns by label(s) or a boolean array in the given Series object. Syntax:Series.loc Parameter : None Returns : series Example #1: Use Series.loc attribute to select some values from the given Series object based on the labels. # importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon']) # Creating the row axis labelssr.index = ['City 1', 'City 2', 'City 3', 'City 4'] # Print the seriesprint(sr) Output : Now we will use Series.loc attribute to return the values of the selected labels in the given Series object. # return the selected values.sr.loc[['City 4', 'City 3', 'City 1']] Output : As we can see in the output, the Series.loc attribute has returned the name of the cities whose labels were passed to it. Example #2 : Use Series.loc attribute to select some values from the given Series object based on the labels. # importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['1/1/2018', '2/1/2018', '3/1/2018', '4/1/2018']) # Creating the row axis labelssr.index = ['Day 1', 'Day 2', 'Day 3', 'Day 4'] # Print the seriesprint(sr) Output : Now we will use Series.loc attribute to return the values of the selected labels in the given Series object. # return the selected values.sr.loc[['Day 4', 'Day 3', 'Day 1']] Output :As we can see in the output, the Series.loc attribute has returned the name of the cities whose labels were passed to it. Python pandas-series Python pandas-series-methods Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Pandas dataframe.groupby() Python | Get unique values from a list Defaultdict in Python Python | os.path.join() method Python Classes and Objects Create a directory in Python
[ { "code": null, "e": 23901, "s": 23873, "text": "\n28 Jan, 2019" }, { "code": null, "e": 24115, "s": 23901, "text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier." }, { "code": null, "e": 24372, "s": 24115, "text": "Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index." }, { "code": null, "e": 24505, "s": 24372, "text": "Pandas Series.loc attribute is used to access a group of rows and columns by label(s) or a boolean array in the given Series object." }, { "code": null, "e": 24523, "s": 24505, "text": "Syntax:Series.loc" }, { "code": null, "e": 24540, "s": 24523, "text": "Parameter : None" }, { "code": null, "e": 24557, "s": 24540, "text": "Returns : series" }, { "code": null, "e": 24666, "s": 24557, "text": "Example #1: Use Series.loc attribute to select some values from the given Series object based on the labels." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon']) # Creating the row axis labelssr.index = ['City 1', 'City 2', 'City 3', 'City 4'] # Print the seriesprint(sr)", "e": 24906, "s": 24666, "text": null }, { "code": null, "e": 24915, "s": 24906, "text": "Output :" }, { "code": null, "e": 25024, "s": 24915, "text": "Now we will use Series.loc attribute to return the values of the selected labels in the given Series object." }, { "code": "# return the selected values.sr.loc[['City 4', 'City 3', 'City 1']]", "e": 25092, "s": 25024, "text": null }, { "code": null, "e": 25101, "s": 25092, "text": "Output :" }, { "code": null, "e": 25333, "s": 25101, "text": "As we can see in the output, the Series.loc attribute has returned the name of the cities whose labels were passed to it. Example #2 : Use Series.loc attribute to select some values from the given Series object based on the labels." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['1/1/2018', '2/1/2018', '3/1/2018', '4/1/2018']) # Creating the row axis labelssr.index = ['Day 1', 'Day 2', 'Day 3', 'Day 4'] # Print the seriesprint(sr)", "e": 25572, "s": 25333, "text": null }, { "code": null, "e": 25581, "s": 25572, "text": "Output :" }, { "code": null, "e": 25690, "s": 25581, "text": "Now we will use Series.loc attribute to return the values of the selected labels in the given Series object." }, { "code": "# return the selected values.sr.loc[['Day 4', 'Day 3', 'Day 1']]", "e": 25755, "s": 25690, "text": null }, { "code": null, "e": 25885, "s": 25755, "text": "Output :As we can see in the output, the Series.loc attribute has returned the name of the cities whose labels were passed to it." }, { "code": null, "e": 25906, "s": 25885, "text": "Python pandas-series" }, { "code": null, "e": 25935, "s": 25906, "text": "Python pandas-series-methods" }, { "code": null, "e": 25949, "s": 25935, "text": "Python-pandas" }, { "code": null, "e": 25956, "s": 25949, "text": "Python" }, { "code": null, "e": 26054, "s": 25956, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26063, "s": 26054, "text": "Comments" }, { "code": null, "e": 26076, "s": 26063, "text": "Old Comments" }, { "code": null, "e": 26108, "s": 26076, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26164, "s": 26108, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26206, "s": 26164, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26248, "s": 26206, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26284, "s": 26248, "text": "Python | Pandas dataframe.groupby()" }, { "code": null, "e": 26323, "s": 26284, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26345, "s": 26323, "text": "Defaultdict in Python" }, { "code": null, "e": 26376, "s": 26345, "text": "Python | os.path.join() method" }, { "code": null, "e": 26403, "s": 26376, "text": "Python Classes and Objects" } ]
Water the plants | Practice | GeeksforGeeks
A gallery with plants is divided into n parts, numbered : 0,1,2,3...n-1. There are provisions for attaching water sprinklers at every partition. A sprinkler with range x at partition i can water all partitions from i-x to i+x. Given an array gallery[ ] consisting of n integers, where gallery[i] is the range of sprinkler at partition i (power==-1 indicates no sprinkler attached), return the minimum number of sprinklers that need to be turned on to water the complete gallery. If there is no possible way to water the full length using the given sprinklers, print -1. Example 1: Input: n = 6 gallery[ ] = {-1, 2, 2, -1, 0, 0} Output: 2 Explanation: Sprinklers at index 2 and 5 can water thefull gallery, span of sprinkler at index 2 = [0,4] and span ​of sprinkler at index 5 = [5,5]. Example 2: Input: n = 9 gallery[ ] = {2, 3, 4, -1, 2, 0, 0, -1, 0} Output: -1 Explanation: No sprinkler can throw water at index 7. Hence all plants cannot be watered. Example 3: Input: n = 9 gallery[ ] = {2, 3, 4, -1, 0, 0, 0, 0, 0} Output: 3 Explanation: Sprinkler at indexes 2, 7 and 8 together can water all plants. Your task: Your task is to complete the function min_sprinklers() which takes the array gallery[ ] and the integer n as input parameters and returns the value to be printed. Expected Time Complexity: O(NlogN) Expected Auxiliary Space: O(N) Constraints: 1 ≤ n ≤ 105 gallery[i] ≤ 50 0 himanshujain4575 months ago Time Complexity: O(NLOGN) Space Complexity: O(1) int min_sprinklers(int gallery[], int n) { int mn=0,mx=0,ans=0,index=0,pos=0; if(n==1 and gallery[0]==-1) return -1; while(mn<n) { pos=0; for(int i=index;i<n;i++) { if( gallery[i]!=-1 and i-gallery[i]<=mn and i+gallery[i]>mx) { mx=i+gallery[i]; index=i; pos=1; } } if(!pos) return -1; ans++; mn=mx+1; } return ans; 0 yash76757goel6 months ago class Solution{ public: int min_sprinklers(int gallery[], int n) { // code here vector<pair<int,int>>sprinklers; for(int i=0;i<n;i++) { if(gallery[i]!=-1) sprinklers.push_back({i-gallery[i],i+gallery[i]}); } sort(sprinklers.begin(),sprinklers.end()); int target =0; int ans=0,i=0; while(target<n) { if(i==sprinklers.size()||sprinklers[i].first>target) return -1; int max_range = sprinklers[i].second; while(i+1<sprinklers.size()&&sprinklers[i+1].first<=target) { i++; max_range=max(max_range,sprinklers[i].second); } if(max_range<target) return -1; ans++; target=max_range+1; i++; } return ans; }}; 0 Kaushik Shah9 months ago Kaushik Shah could someone check this?i think the given output is wrong Input: 14-1 5 1 -1 5 -1 -1 5 0 2 -1 -1 2 0 Its Correct output is: 2 And Your Code's output is: 3 my code:https://practice.geeksforge... 0 Kaushik Shah This comment was deleted. +1 Sidharth Priyadarshi10 months ago Sidharth Priyadarshi /*Idea :- first create a range array of size n, initially all values as -1 - traverse all over the array - take a sprinkler, find the maximum range of that sprikler // let at index 3, sprikler value is 5, means this can water the plants range -2 to 8 units // take care of boundary conditions - if arr[i]==-1, i.e it can not give water to any plant // continue - now check if the maximum distance that this sprinkler can watered is greater than range[i] or not - if yes, - then update the range array from i-arr[i] to i+arr[i] with maximum distance i.e. i+arr[i] // this will indicate that a certain region is of plant sprinkled by a specific sprikler - now initialize count as 0 and j as 0 - traverse the range array until u reach last node - check wheter range of j is -1 // means we have some plant which can not be watered if yes , then return -1 // bcz all plants are not watered otherwise j will updated as range of j // range of j contains the maximum distance of watering increment count increment j by 1 // bcz now we have to check from next place // curr place is already sprinkled finally return count*/ https://uploads.disquscdn.c... 0 Shapnesh Singh Tiwari10 months ago Shapnesh Singh Tiwari Complete solution c++https://youtu.be/VVXjhup_NPM 0 Nihal Chaturvedi10 months ago Nihal Chaturvedi Approach -> We are setting our left range and trying to maximize our right range . Intution is similar to Minimum jump Problem . Python Program https://uploads.disquscdn.c... 0 PALASH HIMANSHU RATHORE10 months ago PALASH HIMANSHU RATHORE This is leetcode hard problem why this is medium here? 0 Debashish kumar sahoo10 months ago Debashish kumar sahoo int min_sprinklers(int gallery[], int n) { // code here int temp[n]; memset(temp,-1,sizeof(temp)); for(int i=0; i<n; i++){="" if(gallery[i]="=" 0){="" temp[i]="max(i," temp[i]);="" }else="" if(gallery[i]="" !="-1){" int="" end="i+gallery[i];" int="" start="max(0," i-gallery[i]);="" for(int="" x="start;" x="" <="min(n,end);" x++){="" temp[x]="max(end," temp[x]);="" }="" }="" }="" int="" ans="0," i="0" ;="" while(i="" <="" n){="" if(i="=" -1="" ||="" temp[i]="=" -1)="" return="" -1;="" ans++;="" i="temp[i]" +="" 1;="" }="" return="" ans;="" }<="" code=""> 0 molla Baquar Abbas10 months ago molla Baquar Abbas simple solution in c++ using vectors and sorting!class Solution{ public: int min_sprinklers(int gallery[], int n) { vector<vector<int>> sprinklers; for(int i = 0; i < n;i++){ if(gallery[i] > -1){ sprinklers.push_back({i-gallery[i],i+gallery[i]}); } } sort(sprinklers.begin(),sprinklers.end()); int j = 0,target = 0; int sprinklers_on = 0; while(target < n){ if(j == sprinklers.size() || sprinklers[j][0] > target){ return -1; } int max_range = sprinklers[j][1]; while(j + 1 < sprinklers.size() && sprinklers[j+1][0] <= target){ j += 1; max_range = max(max_range,sprinklers[j][1]); } if(max_range < target){ return -1; } sprinklers_on++; target = max_range + 1; j++; } return sprinklers_on; }}; 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": 808, "s": 238, "text": "A gallery with plants is divided into n parts, numbered : 0,1,2,3...n-1. There are provisions for attaching water sprinklers at every partition. A sprinkler with range x at partition i can water all partitions from i-x to i+x.\nGiven an array gallery[ ] consisting of n integers, where gallery[i] is the range of sprinkler at partition i (power==-1 indicates no sprinkler attached), return the minimum number of sprinklers that need to be turned on to water the complete gallery.\nIf there is no possible way to water the full length using the given sprinklers, print -1." }, { "code": null, "e": 819, "s": 808, "text": "Example 1:" }, { "code": null, "e": 1027, "s": 819, "text": "Input:\nn = 6\ngallery[ ] = {-1, 2, 2, -1, 0, 0}\nOutput:\n2\nExplanation: Sprinklers at index 2 and 5\ncan water thefull gallery, span of\nsprinkler at index 2 = [0,4] and span\n​of sprinkler at index 5 = [5,5]." }, { "code": null, "e": 1038, "s": 1027, "text": "Example 2:" }, { "code": null, "e": 1195, "s": 1038, "text": "Input:\nn = 9\ngallery[ ] = {2, 3, 4, -1, 2, 0, 0, -1, 0}\nOutput:\n-1\nExplanation: No sprinkler can throw water\nat index 7. Hence all plants cannot be\nwatered." }, { "code": null, "e": 1206, "s": 1195, "text": "Example 3:" }, { "code": null, "e": 1347, "s": 1206, "text": "Input:\nn = 9\ngallery[ ] = {2, 3, 4, -1, 0, 0, 0, 0, 0}\nOutput:\n3\nExplanation: Sprinkler at indexes 2, 7 and\n8 together can water all plants." }, { "code": null, "e": 1521, "s": 1347, "text": "Your task:\nYour task is to complete the function min_sprinklers() which takes the array gallery[ ] and the integer n as input parameters and returns the value to be printed." }, { "code": null, "e": 1587, "s": 1521, "text": "Expected Time Complexity: O(NlogN)\nExpected Auxiliary Space: O(N)" }, { "code": null, "e": 1628, "s": 1587, "text": "Constraints:\n1 ≤ n ≤ 105\ngallery[i] ≤ 50" }, { "code": null, "e": 1630, "s": 1628, "text": "0" }, { "code": null, "e": 1658, "s": 1630, "text": "himanshujain4575 months ago" }, { "code": null, "e": 1684, "s": 1658, "text": "Time Complexity: O(NLOGN)" }, { "code": null, "e": 1707, "s": 1684, "text": "Space Complexity: O(1)" }, { "code": null, "e": 2252, "s": 1707, "text": " int min_sprinklers(int gallery[], int n) { int mn=0,mx=0,ans=0,index=0,pos=0; if(n==1 and gallery[0]==-1) return -1; while(mn<n) { pos=0; for(int i=index;i<n;i++) { if( gallery[i]!=-1 and i-gallery[i]<=mn and i+gallery[i]>mx) { mx=i+gallery[i]; index=i; pos=1; } } if(!pos) return -1; ans++; mn=mx+1; } return ans;" }, { "code": null, "e": 2254, "s": 2252, "text": "0" }, { "code": null, "e": 2280, "s": 2254, "text": "yash76757goel6 months ago" }, { "code": null, "e": 3077, "s": 2280, "text": "class Solution{ public: int min_sprinklers(int gallery[], int n) { // code here vector<pair<int,int>>sprinklers; for(int i=0;i<n;i++) { if(gallery[i]!=-1) sprinklers.push_back({i-gallery[i],i+gallery[i]}); } sort(sprinklers.begin(),sprinklers.end()); int target =0; int ans=0,i=0; while(target<n) { if(i==sprinklers.size()||sprinklers[i].first>target) return -1; int max_range = sprinklers[i].second; while(i+1<sprinklers.size()&&sprinklers[i+1].first<=target) { i++; max_range=max(max_range,sprinklers[i].second); } if(max_range<target) return -1; ans++; target=max_range+1; i++; } return ans; }};" }, { "code": null, "e": 3079, "s": 3077, "text": "0" }, { "code": null, "e": 3104, "s": 3079, "text": "Kaushik Shah9 months ago" }, { "code": null, "e": 3117, "s": 3104, "text": "Kaushik Shah" }, { "code": null, "e": 3183, "s": 3117, "text": "could someone check this?i think the given output is wrong Input:" }, { "code": null, "e": 3219, "s": 3183, "text": "14-1 5 1 -1 5 -1 -1 5 0 2 -1 -1 2 0" }, { "code": null, "e": 3242, "s": 3219, "text": "Its Correct output is:" }, { "code": null, "e": 3244, "s": 3242, "text": "2" }, { "code": null, "e": 3271, "s": 3244, "text": "And Your Code's output is:" }, { "code": null, "e": 3273, "s": 3271, "text": "3" }, { "code": null, "e": 3312, "s": 3273, "text": "my code:https://practice.geeksforge..." }, { "code": null, "e": 3314, "s": 3312, "text": "0" }, { "code": null, "e": 3327, "s": 3314, "text": "Kaushik Shah" }, { "code": null, "e": 3353, "s": 3327, "text": "This comment was deleted." }, { "code": null, "e": 3356, "s": 3353, "text": "+1" }, { "code": null, "e": 3390, "s": 3356, "text": "Sidharth Priyadarshi10 months ago" }, { "code": null, "e": 3411, "s": 3390, "text": "Sidharth Priyadarshi" }, { "code": null, "e": 3486, "s": 3411, "text": "/*Idea :- first create a range array of size n, initially all values as -1" }, { "code": null, "e": 3714, "s": 3486, "text": "- traverse all over the array - take a sprinkler, find the maximum range of that sprikler // let at index 3, sprikler value is 5, means this can water the plants range -2 to 8 units // take care of boundary conditions" }, { "code": null, "e": 4108, "s": 3714, "text": " - if arr[i]==-1, i.e it can not give water to any plant // continue - now check if the maximum distance that this sprinkler can watered is greater than range[i] or not - if yes, - then update the range array from i-arr[i] to i+arr[i] with maximum distance i.e. i+arr[i] // this will indicate that a certain region is of plant sprinkled by a specific sprikler" }, { "code": null, "e": 4589, "s": 4108, "text": " - now initialize count as 0 and j as 0 - traverse the range array until u reach last node - check wheter range of j is -1 // means we have some plant which can not be watered if yes , then return -1 // bcz all plants are not watered otherwise j will updated as range of j // range of j contains the maximum distance of watering increment count increment j by 1 // bcz now we have to check from next place // curr place is already sprinkled" }, { "code": null, "e": 4647, "s": 4589, "text": " finally return count*/ https://uploads.disquscdn.c..." }, { "code": null, "e": 4649, "s": 4647, "text": "0" }, { "code": null, "e": 4684, "s": 4649, "text": "Shapnesh Singh Tiwari10 months ago" }, { "code": null, "e": 4706, "s": 4684, "text": "Shapnesh Singh Tiwari" }, { "code": null, "e": 4756, "s": 4706, "text": "Complete solution c++https://youtu.be/VVXjhup_NPM" }, { "code": null, "e": 4758, "s": 4756, "text": "0" }, { "code": null, "e": 4788, "s": 4758, "text": "Nihal Chaturvedi10 months ago" }, { "code": null, "e": 4805, "s": 4788, "text": "Nihal Chaturvedi" }, { "code": null, "e": 4934, "s": 4805, "text": "Approach -> We are setting our left range and trying to maximize our right range . Intution is similar to Minimum jump Problem ." }, { "code": null, "e": 4980, "s": 4934, "text": "Python Program https://uploads.disquscdn.c..." }, { "code": null, "e": 4982, "s": 4980, "text": "0" }, { "code": null, "e": 5019, "s": 4982, "text": "PALASH HIMANSHU RATHORE10 months ago" }, { "code": null, "e": 5043, "s": 5019, "text": "PALASH HIMANSHU RATHORE" }, { "code": null, "e": 5098, "s": 5043, "text": "This is leetcode hard problem why this is medium here?" }, { "code": null, "e": 5100, "s": 5098, "text": "0" }, { "code": null, "e": 5135, "s": 5100, "text": "Debashish kumar sahoo10 months ago" }, { "code": null, "e": 5157, "s": 5135, "text": "Debashish kumar sahoo" }, { "code": null, "e": 5748, "s": 5157, "text": "int min_sprinklers(int gallery[], int n) { // code here int temp[n]; memset(temp,-1,sizeof(temp)); for(int i=0; i<n; i++){=\"\" if(gallery[i]=\"=\" 0){=\"\" temp[i]=\"max(i,\" temp[i]);=\"\" }else=\"\" if(gallery[i]=\"\" !=\"-1){\" int=\"\" end=\"i+gallery[i];\" int=\"\" start=\"max(0,\" i-gallery[i]);=\"\" for(int=\"\" x=\"start;\" x=\"\" <=\"min(n,end);\" x++){=\"\" temp[x]=\"max(end,\" temp[x]);=\"\" }=\"\" }=\"\" }=\"\" int=\"\" ans=\"0,\" i=\"0\" ;=\"\" while(i=\"\" <=\"\" n){=\"\" if(i=\"=\" -1=\"\" ||=\"\" temp[i]=\"=\" -1)=\"\" return=\"\" -1;=\"\" ans++;=\"\" i=\"temp[i]\" +=\"\" 1;=\"\" }=\"\" return=\"\" ans;=\"\" }<=\"\" code=\"\">" }, { "code": null, "e": 5750, "s": 5748, "text": "0" }, { "code": null, "e": 5782, "s": 5750, "text": "molla Baquar Abbas10 months ago" }, { "code": null, "e": 5801, "s": 5782, "text": "molla Baquar Abbas" }, { "code": null, "e": 6120, "s": 5801, "text": "simple solution in c++ using vectors and sorting!class Solution{ public: int min_sprinklers(int gallery[], int n) { vector<vector<int>> sprinklers; for(int i = 0; i < n;i++){ if(gallery[i] > -1){ sprinklers.push_back({i-gallery[i],i+gallery[i]}); } }" }, { "code": null, "e": 6171, "s": 6120, "text": " sort(sprinklers.begin(),sprinklers.end());" }, { "code": null, "e": 6780, "s": 6171, "text": " int j = 0,target = 0; int sprinklers_on = 0; while(target < n){ if(j == sprinklers.size() || sprinklers[j][0] > target){ return -1; } int max_range = sprinklers[j][1]; while(j + 1 < sprinklers.size() && sprinklers[j+1][0] <= target){ j += 1; max_range = max(max_range,sprinklers[j][1]); } if(max_range < target){ return -1; } sprinklers_on++; target = max_range + 1; j++; } return sprinklers_on; }};" }, { "code": null, "e": 6926, "s": 6780, "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": 6962, "s": 6926, "text": " Login to access your submissions. " }, { "code": null, "e": 6972, "s": 6962, "text": "\nProblem\n" }, { "code": null, "e": 6982, "s": 6972, "text": "\nContest\n" }, { "code": null, "e": 7045, "s": 6982, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 7193, "s": 7045, "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": 7401, "s": 7193, "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": 7507, "s": 7401, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]